From e5de9455259ec64fb4d76411279405b9179ff43a Mon Sep 17 00:00:00 2001 From: Eoin Campbell Date: Fri, 17 Nov 2017 14:07:37 +0000 Subject: [PATCH 1/9] Common Props file to bypass Package Warning As of VS2015.3 & a recent .NET Core & MSBuild revisions, a breaking build change was introduced to make NU1605 a build breaking warning by default. This causes hundreds of build errors in the project due to the presence of newer framework and .net core library versions. This common props file ignores the warning. See: https://github.com/NuGet/Home/issues/5594 --- src/Directory.Build.props | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 src/Directory.Build.props diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 0000000..397b62a --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,5 @@ + + + $(NoWarn);NU1605 + + \ No newline at end of file From ea6f704dbf382a9fc5dde658cdbedc20c51990a4 Mon Sep 17 00:00:00 2001 From: Eoin Campbell Date: Fri, 17 Nov 2017 14:14:44 +0000 Subject: [PATCH 2/9] Fix for OnFailure Hook Event returning Valid (instead of Invalid) results --- src/Warden/Core/IIterationProcessor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Warden/Core/IIterationProcessor.cs b/src/Warden/Core/IIterationProcessor.cs index f5b11ed..4a3db06 100644 --- a/src/Warden/Core/IIterationProcessor.cs +++ b/src/Warden/Core/IIterationProcessor.cs @@ -248,7 +248,7 @@ private async Task InvokeAggregatedOnFirstSuccessHooksAsync(IEnumerable results) { - var invalidResults = results.Select(x => x.WardenCheckResult).Where(x => x.IsValid); + var invalidResults = results.Select(x => x.WardenCheckResult).Where(x => !x.IsValid); _logger.Trace("Executing Aggregated Global Watcher hooks OnFailure."); _configuration.AggregatedGlobalWatcherHooks.OnFailure.Execute(invalidResults); _logger.Trace("Executing Aggregated Global Watcher hooks OnFailureAsync."); From 2834b4325a75d80672f64a4b740114f2adca4ea9 Mon Sep 17 00:00:00 2001 From: Eoin Campbell Date: Fri, 17 Nov 2017 16:58:11 +0000 Subject: [PATCH 3/9] Warden.Integration.Smtp Implementation --- src/Directory.Build.props | 5 + .../Warden.Examples.Console.csproj | 1 + .../Warden.Integrations.Smtp/Extensions.cs | 36 ++++ .../Warden.Integrations.Smtp/ISmtpService.cs | 116 +++++++++++ .../Properties/AssemblyInfo.cs | 19 ++ .../SmtpIntegration.cs | 111 +++++++++++ .../SmtpIntegrationConfiguration.cs | 181 ++++++++++++++++++ .../Warden.Integrations.Smtp.csproj | 47 +++++ src/Warden.sln | 12 +- 9 files changed, 527 insertions(+), 1 deletion(-) create mode 100644 src/Directory.Build.props create mode 100644 src/Integrations/Warden.Integrations.Smtp/Extensions.cs create mode 100644 src/Integrations/Warden.Integrations.Smtp/ISmtpService.cs create mode 100644 src/Integrations/Warden.Integrations.Smtp/Properties/AssemblyInfo.cs create mode 100644 src/Integrations/Warden.Integrations.Smtp/SmtpIntegration.cs create mode 100644 src/Integrations/Warden.Integrations.Smtp/SmtpIntegrationConfiguration.cs create mode 100644 src/Integrations/Warden.Integrations.Smtp/Warden.Integrations.Smtp.csproj diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 0000000..397b62a --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,5 @@ + + + $(NoWarn);NU1605 + + \ No newline at end of file diff --git a/src/Examples/Warden.Examples.Console/Warden.Examples.Console.csproj b/src/Examples/Warden.Examples.Console/Warden.Examples.Console.csproj index cd77ba5..a48a5e8 100644 --- a/src/Examples/Warden.Examples.Console/Warden.Examples.Console.csproj +++ b/src/Examples/Warden.Examples.Console/Warden.Examples.Console.csproj @@ -26,6 +26,7 @@ + diff --git a/src/Integrations/Warden.Integrations.Smtp/Extensions.cs b/src/Integrations/Warden.Integrations.Smtp/Extensions.cs new file mode 100644 index 0000000..7424381 --- /dev/null +++ b/src/Integrations/Warden.Integrations.Smtp/Extensions.cs @@ -0,0 +1,36 @@ +using System; +using Warden.Core; +using Warden.Integrations; + +namespace Warden.Integrations.Smtp +{ + + public static class Extensions + { + + public static WardenConfiguration.Builder IntegrateWithSmtp( + this WardenConfiguration.Builder builder, + string host, + int port, + bool enableSsl, + Action configurator = null) + { + builder.AddIntegration(SmtpIntegration.Create(host, port, enableSsl, configurator)); + + return builder; + } + + + public static WardenConfiguration.Builder IntegrateWithSmtp( + this WardenConfiguration.Builder builder, + SmtpIntegrationConfiguration configuration) + { + builder.AddIntegration(SmtpIntegration.Create(configuration)); + + return builder; + } + + public static SmtpIntegration Smtp(this IIntegrator integrator) + => integrator.Resolve(); + } +} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Smtp/ISmtpService.cs b/src/Integrations/Warden.Integrations.Smtp/ISmtpService.cs new file mode 100644 index 0000000..5558233 --- /dev/null +++ b/src/Integrations/Warden.Integrations.Smtp/ISmtpService.cs @@ -0,0 +1,116 @@ +using System; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using MailKit.Net.Smtp; +using MimeKit; +using MailKit.Security; + + +namespace Warden.Integrations.Smtp +{ + public interface ISmtpService + { + Task SendEmailAsync( + string to, + string from, + string subject, + string body, + IEnumerable cc = null, + bool isBodyHtml = false, + + string username = null, + string password = null, + TimeSpan? timeout = null); + } + + + public class SmtpService : ISmtpService + { + private readonly string _host; + private readonly int _port; + private readonly bool _enableSsl; + + public SmtpService(string host, int port, bool enableSsl) + { + _host = host; + _port = port; + _enableSsl = enableSsl; + } + + public async Task SendEmailAsync( + string to, + string from, + string subject, + string body, + IEnumerable cc = null, + bool isBodyHtml = false, + + string username = null, + string password = null, + TimeSpan? timeout = null) + { + try + { + using (var _client = new SmtpClient()) + { + await _client.ConnectAsync(_host + , _port + , _enableSsl ? SecureSocketOptions.StartTlsWhenAvailable : SecureSocketOptions.None); + + _client.AuthenticationMechanisms.Remove("XOAUTH2"); + + + if (!string.IsNullOrWhiteSpace(username) && + !string.IsNullOrWhiteSpace(password)) + { + await _client.AuthenticateAsync(username, password); + } + + if (timeout.HasValue) + { + _client.Timeout = (int)timeout.Value.TotalMilliseconds; + } + + var message = PrepareMessage(from, to, subject, body, cc, isBodyHtml); + + await _client.SendAsync(message); + + await _client.DisconnectAsync(true); + } + } + catch (Exception exception) + { + throw new IntegrationException("There was an error while executing the SendEmailAsync(): " + + $"{exception}", exception); + } + } + + private MimeMessage PrepareMessage(string from, string to, string subject, string body, + IEnumerable cc, bool isBodyHtml) + { + var message = new MimeMessage(); + + message.From.Add(new MailboxAddress(from)); + + message.To.Add(new MailboxAddress(to)); + + message.Subject = subject; + + message.Body = new TextPart(isBodyHtml ? "html" : "plain") + { + Text = body + }; + + if (cc != null && cc.Any()) + { + foreach (var address in cc) + { + message.Cc.Add(new MailboxAddress(address)); + } + } + + return message; + } + } +} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Smtp/Properties/AssemblyInfo.cs b/src/Integrations/Warden.Integrations.Smtp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e4b1d6b --- /dev/null +++ b/src/Integrations/Warden.Integrations.Smtp/Properties/AssemblyInfo.cs @@ -0,0 +1,19 @@ +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: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Warden.Integrations.Smtp")] +[assembly: AssemblyTrademark("")] + +// 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("b300174e-d096-4ef4-81cd-ad7448a6a642")] diff --git a/src/Integrations/Warden.Integrations.Smtp/SmtpIntegration.cs b/src/Integrations/Warden.Integrations.Smtp/SmtpIntegration.cs new file mode 100644 index 0000000..afd5fb1 --- /dev/null +++ b/src/Integrations/Warden.Integrations.Smtp/SmtpIntegration.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace Warden.Integrations.Smtp +{ + public class SmtpIntegration : IIntegration + { + private readonly SmtpIntegrationConfiguration _configuration; + private readonly ISmtpService _smtpService; + + public SmtpIntegration(SmtpIntegrationConfiguration configuration) + { + if (configuration == null) + { + throw new ArgumentNullException(nameof(configuration), + "Smtp Integration configuration has not been provided."); + } + + _configuration = configuration; + _smtpService = _configuration.SmtpServiceProvider(); + } + + public async Task SendEmailAsync(string body) + { + await _smtpService.SendEmailAsync( + _configuration.DefaultToAddress, + _configuration.DefaultFromAddress, + _configuration.DefaultSubject, + body, + _configuration.DefaultCCAddresses, + _configuration.DefaultIsBodyHtml, + _configuration.Username, + _configuration.Password, + _configuration.Timeout); + } + + public async Task SendEmailAsync(string subject, string body) + { + await _smtpService.SendEmailAsync( + _configuration.DefaultToAddress, + _configuration.DefaultFromAddress, + subject, + body, + _configuration.DefaultCCAddresses, + _configuration.DefaultIsBodyHtml, + _configuration.Username, + _configuration.Password, + _configuration.Timeout); + } + + public async Task SendEmailAsync(string to, string from, string subject, string body) + { + await _smtpService.SendEmailAsync( + to, + from, + subject, + body, + _configuration.DefaultCCAddresses, + _configuration.DefaultIsBodyHtml, + _configuration.Username, + _configuration.Password, + _configuration.Timeout); + } + + public async Task SendEmailAsync(string to, string from, string subject, string body, + string username, string password) + { + await _smtpService.SendEmailAsync( + to, + from, + subject, + body, + _configuration.DefaultCCAddresses, + _configuration.DefaultIsBodyHtml, + username, + password, + _configuration.Timeout); + } + + public async Task SendEmailAsync( + string to, + string from, + string subject, + string body, + IEnumerable cc = null, + bool isBodyHtml = false, + string username = null, + string password = null, + TimeSpan? timeout = null) + { + await _smtpService.SendEmailAsync(to, from, subject, body, cc, isBodyHtml, + username, password, timeout); + } + + public static SmtpIntegration Create(string host, + int port, + bool enableSsl, + Action configurator = null) + { + var config = new SmtpIntegrationConfiguration.Builder(host, port, enableSsl); + configurator?.Invoke(config); + + return Create(config.Build()); + } + + public static SmtpIntegration Create(SmtpIntegrationConfiguration configuration) + => new SmtpIntegration(configuration); + } +} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Smtp/SmtpIntegrationConfiguration.cs b/src/Integrations/Warden.Integrations.Smtp/SmtpIntegrationConfiguration.cs new file mode 100644 index 0000000..9fc0a56 --- /dev/null +++ b/src/Integrations/Warden.Integrations.Smtp/SmtpIntegrationConfiguration.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Warden.Integrations.Smtp +{ + public class SmtpIntegrationConfiguration + { + //All Parameters + + public string Host { get; protected set; } + + public int Port { get; protected set; } + + public bool EnableSsl { get; protected set; } + + public string Username { get; protected set; } + + public string Password { get; protected set; } + + public TimeSpan? Timeout { get; protected set; } + + public string DefaultToAddress { get; protected set; } + + public string DefaultFromAddress { get; protected set; } + + public string DefaultSubject { get; protected set; } + + public string DefaultBody { get; protected set; } + + public bool DefaultIsBodyHtml { get; protected set; } + + public IEnumerable DefaultCCAddresses { get; protected set; } + + public Func SmtpServiceProvider { get; protected set; } + + public static Builder Create(string host, int port, bool enableSsl) => new Builder(host, port, enableSsl); + + protected SmtpIntegrationConfiguration(string host, int port, bool enableSsl) + { + Host = host; + Port = port; + EnableSsl = enableSsl; + + SmtpServiceProvider = () => new SmtpService(Host, Port, EnableSsl); + } + + public class Builder + { + protected readonly SmtpIntegrationConfiguration Configuration; + + public Builder(string host, int port, bool enableSsl) + { + Configuration = new SmtpIntegrationConfiguration(host, port, enableSsl); + } + + public Builder WithDefaultCredentials() + { + Configuration.Username = null; + Configuration.Password = null; + return this; + } + + public Builder WithCredentials(string username, string password) + { + if (string.IsNullOrWhiteSpace(username)) + throw new ArgumentException("Username can not be empty.", nameof(username)); + + if (string.IsNullOrWhiteSpace(password)) + throw new ArgumentException("Password can not be empty.", nameof(password)); + + Configuration.Username = username; + Configuration.Password = password; + return this; + } + + public Builder WithDefaultTimeout(TimeSpan timeout) + { + if (timeout == null) + throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); + + if (timeout == TimeSpan.Zero) + throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); + + Configuration.Timeout = timeout; + + return this; + } + + public Builder WithDefaultToAddress(string toAddress) + { + if (string.IsNullOrWhiteSpace(toAddress)) + throw new ArgumentException("To Address can not be empty.", nameof(toAddress)); + + Configuration.DefaultToAddress = toAddress; + + return this; + } + + public Builder WithDefaultFromAddress(string fromAddress) + { + if (string.IsNullOrWhiteSpace(fromAddress)) + throw new ArgumentException("From Address can not be empty.", nameof(fromAddress)); + + Configuration.DefaultFromAddress = fromAddress; + + return this; + } + + public Builder WithDefaultSubject(string subject) + { + if (string.IsNullOrWhiteSpace(subject)) + throw new ArgumentException("Subject can not be empty.", nameof(subject)); + + Configuration.DefaultSubject = subject; + + return this; + } + + public Builder WithDefaultBody(string body) + { + if (string.IsNullOrWhiteSpace(body)) + throw new ArgumentException("Body can not be empty.", nameof(body)); + + Configuration.DefaultBody = body; + + return this; + } + + public Builder WithDefaultIsBodyHtml(bool isBodyHtml) + { + Configuration.DefaultIsBodyHtml = isBodyHtml; + + return this; + } + + public Builder WithDefaultCCAddress(IEnumerable ccAddresses) + { + if (ccAddresses == null) + throw new ArgumentNullException(nameof(ccAddresses), "CC Addresses can not be null."); + + if (!ccAddresses.Any()) + throw new ArgumentException("CC Addresses must contain at least one address.", nameof(ccAddresses)); + + + List defaultAddresses = new List(); + + foreach (var address in ccAddresses) + { + if (!string.IsNullOrWhiteSpace(address)) + { + defaultAddresses.Add(address); + } + } + + if (!defaultAddresses.Any()) + throw new ArgumentException("CC Addresses can not be empty/blank.", nameof(ccAddresses)); + + Configuration.DefaultCCAddresses = defaultAddresses; + + return this; + } + + public Builder WithSmtpServiceProvider(Func smtpServiceProvider) + { + if (smtpServiceProvider == null) + { + throw new ArgumentNullException(nameof(smtpServiceProvider), + "Smtp service provider can not be null."); + } + + Configuration.SmtpServiceProvider = smtpServiceProvider; + + return this; + } + + public SmtpIntegrationConfiguration Build() => Configuration; + } + } +} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Smtp/Warden.Integrations.Smtp.csproj b/src/Integrations/Warden.Integrations.Smtp/Warden.Integrations.Smtp.csproj new file mode 100644 index 0000000..3110f62 --- /dev/null +++ b/src/Integrations/Warden.Integrations.Smtp/Warden.Integrations.Smtp.csproj @@ -0,0 +1,47 @@ + + + + Warden integration with MS SQL. + 1.3.1 + Piotr Gankiewicz, Eoin Campbell + net461;netstandard1.6 + Warden.Integrations.Smtp + Warden.Integrations.Smtp + Warden + https://getwarden.net + https://github.com/warden-stack/Warden/blob/master/LICENSE + $(PackageTargetFallback);dotnet5.6;dnxcore50 + false + false + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Warden.sln b/src/Warden.sln index ac67201..7384b61 100644 --- a/src/Warden.sln +++ b/src/Warden.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26228.12 +VisualStudioVersion = 15.0.27004.2008 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{E19861BB-3F4A-4FFB-9AD7-452DFBEBEED0}" EndProject @@ -61,6 +61,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Warden.Examples.CommandsAnd EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Warden.Examples.CommandsAndEvents.App", "Examples\Warden.Examples.CommandsAndEvents.App\Warden.Examples.CommandsAndEvents.App.csproj", "{C03A000B-EEC8-46AB-88FC-339E035F8A3F}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Warden.Integrations.Smtp", "Integrations\Warden.Integrations.Smtp\Warden.Integrations.Smtp.csproj", "{B069178E-A125-4780-AE78-0B49F8F0920A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -159,6 +161,10 @@ Global {C03A000B-EEC8-46AB-88FC-339E035F8A3F}.Debug|Any CPU.Build.0 = Debug|Any CPU {C03A000B-EEC8-46AB-88FC-339E035F8A3F}.Release|Any CPU.ActiveCfg = Release|Any CPU {C03A000B-EEC8-46AB-88FC-339E035F8A3F}.Release|Any CPU.Build.0 = Release|Any CPU + {B069178E-A125-4780-AE78-0B49F8F0920A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B069178E-A125-4780-AE78-0B49F8F0920A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B069178E-A125-4780-AE78-0B49F8F0920A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B069178E-A125-4780-AE78-0B49F8F0920A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -186,5 +192,9 @@ Global {59533599-205A-4878-813F-FE2044DAA79D} = {DB63BF6C-E9C3-4777-9F83-258AF50EC58D} {75B125DA-D804-44B6-88C4-DCCA585FD438} = {E19861BB-3F4A-4FFB-9AD7-452DFBEBEED0} {C03A000B-EEC8-46AB-88FC-339E035F8A3F} = {E19861BB-3F4A-4FFB-9AD7-452DFBEBEED0} + {B069178E-A125-4780-AE78-0B49F8F0920A} = {DB63BF6C-E9C3-4777-9F83-258AF50EC58D} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {64777858-697F-4FBB-A7D9-4A4E5B8C0B8B} EndGlobalSection EndGlobal From 63cc1e5c11f0e2f684f076e47ebe203b4574bff1 Mon Sep 17 00:00:00 2001 From: Eoin Campbell Date: Fri, 17 Nov 2017 17:15:30 +0000 Subject: [PATCH 4/9] Supply Example Usage --- src/Examples/Warden.Examples.Console/Program.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/Examples/Warden.Examples.Console/Program.cs b/src/Examples/Warden.Examples.Console/Program.cs index 0ec42e6..815617d 100644 --- a/src/Examples/Warden.Examples.Console/Program.cs +++ b/src/Examples/Warden.Examples.Console/Program.cs @@ -7,6 +7,7 @@ using Warden.Integrations.HttpApi; using Warden.Integrations.MsSql; using Warden.Integrations.Slack; +using Warden.Integrations.Smtp; using Warden.Utils; using Warden.Watchers; using Warden.Watchers.Disk; @@ -87,6 +88,21 @@ private static IWarden ConfigureWarden() // .OnFirstSuccessAsync(results => // integrations.SendGrid().SendEmailAsync("Everything is up and running again!")); //}) + //Set SMTP Details + //.IntegrateWithSmtp("smtp.office365.com", 587, true, cfg => + //{ + // cfg.WithCredentials("notifications@domain.domin", "mySecretPassword") + // .WithDefaultSubject("Notification Email from Warden") + // .WithDefaultToAddress("monitoring@domain.com") + // .WithDefaultFromAddress("notifications@domain.com"); + //}) + //.SetAggregatedWatcherHooks((hooks, integrations) => + //{ + // hooks.OnFirstFailureAsync(result => + // integrations.Smtp().SendEmailAsync("Monitoring errors have occured.")) + // .OnFirstSuccessAsync(results => + // integrations.Smtp().SendEmailAsync("Everything is up and running again!")); + //}) //Set proper URL of the Warden Web API .IntegrateWithHttpApi("https://panel.getwarden.net/api", "pMBXwekquqlfvGPXTNT1k32RHisgguAV2yv3tJq1Wq0d2eqMsx2HuR97Lfc=", From 4ea912fc109e6ff51bb65b72e0bd7210e9e7c49e Mon Sep 17 00:00:00 2001 From: Piotr Gankiewicz Date: Thu, 15 Feb 2018 16:04:24 +0100 Subject: [PATCH 5/9] #150 migrating to .netstandard2.0 --- README.md | 2 +- Warden.sln | 56 ++ src/Directory.Build.props | 5 - .../GenericCommandHandler.cs | 40 -- .../Program.cs | 73 --- .../Properties/AssemblyInfo.cs | 19 - .../RebusWardenCommandSource.cs | 19 - .../RebusWardenEventHandler.cs | 21 - ...rden.Examples.CommandsAndEvents.App.csproj | 47 -- .../GenericEventHandler.cs | 23 - .../Program.cs | 70 --- .../Properties/AssemblyInfo.cs | 19 - ....Examples.CommandsAndEvents.Manager.csproj | 33 - .../Warden.Examples.Console/Program.cs | 233 ------- .../Properties/AssemblyInfo.cs | 23 - .../Warden.Examples.Console.csproj | 46 -- .../Warden.Examples.WindowsService/Program.cs | 31 - .../Properties/AssemblyInfo.cs | 23 - .../Warden.Examples.WindowsService.csproj | 50 -- .../WardenService.cs | 226 ------- .../CachetIntegration.cs | 266 -------- .../CachetIntegrationConfiguration.cs | 317 ---------- .../Warden.Integrations.Cachet/Component.cs | 125 ---- .../ComponentStatus.cs | 11 - .../Warden.Integrations.Cachet/Envelope.cs | 11 - .../EnvelopeCollection.cs | 13 - .../Warden.Integrations.Cachet/Extensions.cs | 77 --- .../ICachetService.cs | 373 ----------- .../Warden.Integrations.Cachet/Incident.cs | 152 ----- .../IncidentStatus.cs | 11 - .../Properties/AssemblyInfo.cs | 19 - .../Warden.Integrations.Cachet.csproj | 45 -- .../Warden.Integrations.HttpApi/Extensions.cs | 182 ------ .../HttpApiIntegration.cs | 131 ---- .../HttpApiIntegrationConfiguration.cs | 214 ------- .../IHttpService.cs | 90 --- .../Properties/AssemblyInfo.cs | 23 - .../Warden.Integrations.HttpApi.csproj | 48 -- .../Warden.Integrations.MsSql/Extensions.cs | 48 -- .../IMsSqlService.cs | 74 --- .../MsSqlIntegration.cs | 210 ------- .../MsSqlIntegrationConfiguration.cs | 223 ------- .../Properties/AssemblyInfo.cs | 19 - .../Warden.Integrations.MsSql/Schema.sql | 44 -- .../Warden.Integrations.MsSql.csproj | 45 -- .../EmailTemplateParameter.cs | 33 - .../Extensions.cs | 82 --- .../IEmailSender.cs | 43 -- .../Properties/AssemblyInfo.cs | 23 - .../SendGridEmailMessage.cs | 34 - .../SendGridIntegration.cs | 244 -------- .../SendGridIntegrationConfiguration.cs | 211 ------- .../Warden.Integrations.SendGrid.csproj | 40 -- .../Warden.Integrations.Slack/Extensions.cs | 50 -- .../ISlackService.cs | 137 ---- .../Properties/AssemblyInfo.cs | 19 - .../SlackIntegration.cs | 155 ----- .../SlackIntegrationConfiguration.cs | 178 ------ .../Warden.Integrations.Slack.csproj | 45 -- .../Warden.Integrations.Smtp/Extensions.cs | 36 -- .../Warden.Integrations.Smtp/ISmtpService.cs | 116 ---- .../Properties/AssemblyInfo.cs | 19 - .../SmtpIntegration.cs | 111 ---- .../SmtpIntegrationConfiguration.cs | 181 ------ .../Warden.Integrations.Smtp.csproj | 47 -- .../Warden.Integrations.Twilio/Extensions.cs | 50 -- .../ITwilioService.cs | 39 -- .../Properties/AssemblyInfo.cs | 23 - .../TwilioIntegration.cs | 94 --- .../TwilioIntegrationConfiguration.cs | 142 ----- .../Properties/AssemblyInfo.cs | 23 - .../Warden.Tests.EndToEnd.csproj | 56 -- .../Watchers/Web/WebWatcherTests.cs | 76 --- .../Cachet/CachetIntegration_specs.cs | 130 ---- .../HttpApi/HttpApiIntegration_specs.cs | 148 ----- .../MsSql/MsSqlIntegration_specs.cs | 135 ---- .../SendGrid/SendGridIntegration_specs.cs | 183 ------ .../Slack/SlackIntegration_specs.cs | 64 -- .../Twilio/TwilioIntegrationTests.cs | 143 ----- .../Properties/launchSettings.json | 8 - src/Tests/Warden.Tests/Warden.Tests.csproj | 56 -- .../Watchers/Disk/PerformanceWatcherTests.cs | 270 -------- .../Watchers/MongoDb/MongoDbWatcherTests.cs | 300 --------- .../Watchers/MsSql/MsSqlWatcherTests.cs | 383 ------------ .../Performance/PerformanceWatcherTests.cs | 250 -------- .../Process/PerformanceWatcherTests.cs | 320 ---------- .../Watchers/Redis/RedisWatcherTests.cs | 298 --------- .../Watchers/Server/ServerWatcherTests.cs | 264 -------- .../Watchers/Web/WebWatcherTests.cs | 272 -------- src/UpgradeLog.htm | Bin 167470 -> 0 bytes src/Warden.sln | 200 ------ src/Warden/Warden.csproj | 30 +- .../Warden.Watchers.Disk/DirectoryInfo.cs | 62 -- .../Warden.Watchers.Disk/DiskCheck.cs | 67 -- .../Warden.Watchers.Disk/DiskWatcher.cs | 117 ---- .../DiskWatcherCheckResult.cs | 29 - .../DiskWatcherConfiguration.cs | 183 ------ .../Warden.Watchers.Disk/Extensions.cs | 139 ----- src/Watchers/Warden.Watchers.Disk/FileInfo.cs | 82 --- .../Warden.Watchers.Disk/IDiskChecker.cs | 89 --- .../Warden.Watchers.Disk/PartitionInfo.cs | 59 -- .../Properties/AssemblyInfo.cs | 23 - .../Warden.Watchers.Disk.csproj | 39 -- .../Warden.Watchers.MongoDb/Extensions.cs | 168 ----- .../Warden.Watchers.MongoDb/IMongoDb.cs | 42 -- .../IMongoDbConnection.cs | 86 --- .../Warden.Watchers.MongoDb/MongoDbWatcher.cs | 135 ---- .../MongoDbWatcherCheckResult.cs | 71 --- .../MongoDbWatcherConfiguration.cs | 256 -------- .../Properties/AssemblyInfo.cs | 23 - .../Warden.Watchers.MongoDb.csproj | 39 -- .../Warden.Watchers.MsSql/Extensions.cs | 150 ----- src/Watchers/Warden.Watchers.MsSql/IMsSql.cs | 47 -- .../Warden.Watchers.MsSql/MsSqlWatcher.cs | 131 ---- .../MsSqlWatcherCheckResult.cs | 62 -- .../MsSqlWatcherConfiguration.cs | 239 ------- .../Properties/AssemblyInfo.cs | 23 - .../Warden.Watchers.MsSql.csproj | 48 -- .../Warden.Watchers.Performance/Extensions.cs | 155 ----- .../IPerformance.cs | 47 -- .../PerformanceWatcher.cs | 109 ---- .../PerformanceWatcherCheckResult.cs | 48 -- .../PerformanceWatcherConfiguration.cs | 148 ----- .../Properties/AssemblyInfo.cs | 23 - .../ResourceUsage.cs | 33 - .../Warden.Watchers.Performance.csproj | 34 - .../Warden.Watchers.Process/Extensions.cs | 156 ----- .../IProcessService.cs | 40 -- .../Warden.Watchers.Process/ProcessInfo.cs | 64 -- .../Warden.Watchers.Process/ProcessWatcher.cs | 100 --- .../ProcessWatcherCheckResult.cs | 32 - .../ProcessWatcherConfiguration.cs | 167 ----- .../Properties/AssemblyInfo.cs | 19 - .../Warden.Watchers.Process.csproj | 41 -- .../Warden.Watchers.Redis/Extensions.cs | 168 ----- src/Watchers/Warden.Watchers.Redis/IRedis.cs | 92 --- .../Warden.Watchers.Redis/IRedisConnection.cs | 69 --- .../Properties/AssemblyInfo.cs | 23 - .../Warden.Watchers.Redis/RedisWatcher.cs | 137 ---- .../RedisWatcherCheckResult.cs | 72 --- .../RedisWatcherConfiguration.cs | 228 ------- .../Warden.Watchers.Redis.csproj | 39 -- .../Warden.Watchers.Server/ConnectionInfo.cs | 67 -- .../Warden.Watchers.Server/Extensions.cs | 175 ------ .../Warden.Watchers.Server/IDnsResolver.cs | 37 -- .../Warden.Watchers.Server/IPinger.cs | 47 -- .../Warden.Watchers.Server/ITcpClient.cs | 84 --- .../Properties/AssemblyInfo.cs | 19 - .../Warden.Watchers.Server/ServerWatcher.cs | 292 --------- .../ServerWatcherCheckResult.cs | 29 - .../ServerWatcherConfiguration.cs | 233 ------- .../Warden.Watchers.Server.csproj | 32 - .../Warden.Watchers.Web/Extensions.cs | 212 ------- .../Warden.Watchers.Web/IHttpRequest.cs | 135 ---- .../Warden.Watchers.Web/IHttpResponse.cs | 82 --- .../Warden.Watchers.Web/IHttpService.cs | 106 ---- .../Properties/AssemblyInfo.cs | 23 - .../Warden.Watchers.Web.csproj | 48 -- .../Warden.Watchers.Web/WebWatcher.cs | 148 ----- .../WebWatcherCheckResult.cs | 49 -- .../WebWatcherConfiguration.cs | 222 ------- src/Web/Warden.Web.Core/Domain/ApiKey.cs | 28 - .../Warden.Web.Core/Domain/DomainException.cs | 20 - src/Web/Warden.Web.Core/Domain/Entity.cs | 14 - .../Warden.Web.Core/Domain/ExceptionInfo.cs | 32 - .../Warden.Web.Core/Domain/ICompletable.cs | 9 - .../Warden.Web.Core/Domain/IIdentifiable.cs | 9 - .../Warden.Web.Core/Domain/ITimestampable.cs | 9 - .../Warden.Web.Core/Domain/IValidatable.cs | 7 - .../Warden.Web.Core/Domain/Organization.cs | 168 ----- .../Domain/OrganizationRole.cs | 9 - .../Warden.Web.Core/Domain/PagedQueryBase.cs | 8 - src/Web/Warden.Web.Core/Domain/PagedResult.cs | 35 -- .../Warden.Web.Core/Domain/PagedResultBase.cs | 23 - src/Web/Warden.Web.Core/Domain/Role.cs | 9 - .../Domain/SecuredOperation.cs | 72 --- .../Domain/ServiceException.cs | 20 - src/Web/Warden.Web.Core/Domain/State.cs | 10 - src/Web/Warden.Web.Core/Domain/User.cs | 117 ---- .../Domain/UserInOrganization.cs | 30 - src/Web/Warden.Web.Core/Domain/UserSession.cs | 30 - src/Web/Warden.Web.Core/Domain/Warden.cs | 100 --- .../Domain/WardenCheckResult.cs | 36 -- src/Web/Warden.Web.Core/Domain/WardenInfo.cs | 31 - .../Warden.Web.Core/Domain/WardenIteration.cs | 52 -- src/Web/Warden.Web.Core/Domain/Watcher.cs | 28 - .../Domain/WatcherCheckResult.cs | 29 - src/Web/Warden.Web.Core/Domain/WatcherType.cs | 15 - src/Web/Warden.Web.Core/Dto/ExceptionDto.cs | 28 - .../Warden.Web.Core/Dto/OrganizationDto.cs | 31 - src/Web/Warden.Web.Core/Dto/StatsDto.cs | 11 - src/Web/Warden.Web.Core/Dto/UserDto.cs | 31 - .../Dto/UserInOrganizationDto.cs | 25 - .../Dto/WardenCheckResultDto.cs | 30 - src/Web/Warden.Web.Core/Dto/WardenDto.cs | 28 - .../Warden.Web.Core/Dto/WardenIterationDto.cs | 38 -- src/Web/Warden.Web.Core/Dto/WardenStatsDto.cs | 20 - .../Dto/WatcherCheckResultDto.cs | 26 - src/Web/Warden.Web.Core/Dto/WatcherDto.cs | 20 - .../Warden.Web.Core/Dto/WatcherStatsDto.cs | 13 - .../Extensions/ObjectExtensions.cs | 38 -- .../Extensions/StringExtensions.cs | 62 -- .../Factories/ISecuredOperationFactory.cs | 32 - .../Mongo/MongoConfigurator.cs | 34 - src/Web/Warden.Web.Core/Mongo/Pagination.cs | 53 -- .../Mongo/Queries/ApiKeyQueries.cs | 40 -- .../Mongo/Queries/OrganizationQueries.cs | 72 --- .../Mongo/Queries/SecuredOperationQueries.cs | 49 -- .../Mongo/Queries/UserQueries.cs | 46 -- .../Mongo/Queries/UserSessionQueries.cs | 11 - .../Mongo/Queries/WardenIterationQueries.cs | 102 --- .../Properties/AssemblyInfo.cs | 23 - .../Properties/launchSettings.json | 19 - .../Queries/BrowseOrganizations.cs | 15 - .../Queries/BrowseWardenCheckResults.cs | 15 - .../Queries/BrowseWardenIterations.cs | 24 - .../Warden.Web.Core/Queries/BrowseWatchers.cs | 14 - .../Warden.Web.Core/Queries/GetWardenStats.cs | 13 - .../Queries/GetWatcherStats.cs | 14 - .../Services/IApiKeyService.cs | 99 --- .../Warden.Web.Core/Services/IEmailSender.cs | 146 ----- .../Warden.Web.Core/Services/IEncrypter.cs | 107 ---- .../Services/IOrganizationService.cs | 256 -------- .../Services/ISignalRService.cs | 33 - .../Services/IStatsCalculator.cs | 38 -- .../Warden.Web.Core/Services/IUserService.cs | 203 ------ .../Services/IWardenService.cs | 228 ------- .../Services/IWatcherService.cs | 110 ---- .../Settings/AccountSettings.cs | 7 - .../Warden.Web.Core/Settings/EmailSettings.cs | 12 - .../EmailTemplateParameterSettings.cs | 10 - .../Settings/EmailTemplateSettings.cs | 12 - .../Settings/FeatureSettings.cs | 12 - .../Warden.Web.Core/Warden.Web.Core.csproj | 33 - src/Web/Warden.Web/.bowerrc | 3 - src/Web/Warden.Web/Api/ApiController.cs | 49 -- .../Warden.Web/Api/OrganizationController.cs | 35 -- src/Web/Warden.Web/Api/WardenController.cs | 44 -- .../Api/WardenIterationController.cs | 60 -- src/Web/Warden.Web/Bower.json | 13 - .../Controllers/AccountController.cs | 145 ----- .../Warden.Web/Controllers/ControllerBase.cs | 47 -- .../Controllers/DashboardController.cs | 88 --- .../Warden.Web/Controllers/HomeController.cs | 55 -- .../Controllers/OrganizationController.cs | 347 ----------- .../Controllers/ResetPasswordController.cs | 154 ----- .../Controllers/SettingsController.cs | 93 --- .../Controllers/WardenController.cs | 210 ------- .../Controllers/WatcherController.cs | 61 -- .../Warden.Web/Extensions/AspNetExtensions.cs | 37 -- .../Warden.Web/Extensions/TaskExtensions.cs | 76 --- .../Extensions/UrlHelperExtensions.cs | 113 ---- .../Framework/Filters/ExceptionFilter.cs | 15 - .../Filters/ExportModelStateToTempData.cs | 37 -- .../Filters/ImportModelStateFromTempData.cs | 44 -- .../Filters/ModelStateTempDataTransfer.cs | 32 - .../Framework/FlashNotificationType.cs | 9 - .../Warden.Web/Framework/GeneralSettings.cs | 13 - src/Web/Warden.Web/Hubs/WardenHub.cs | 64 -- .../Warden.Web/Properties/launchSettings.json | 25 - src/Web/Warden.Web/Startup.cs | 155 ----- .../AddUserToOrganizationViewModel.cs | 13 - .../AddWardenToOrganizationViewModel.cs | 13 - .../ViewModels/ChangePasswordViewModel.cs | 24 - .../ViewModels/CreateOrganizationViewModel.cs | 13 - .../ViewModels/DashboardViewModel.cs | 14 - .../ViewModels/EditOrganizationViewModel.cs | 13 - .../ViewModels/EditWardenViewModel.cs | 13 - .../Warden.Web/ViewModels/LoginViewModel.cs | 22 - .../ViewModels/OrganizationViewModel.cs | 13 - .../ViewModels/RegisterViewModel.cs | 24 - .../ViewModels/ResetPasswordViewModel.cs | 13 - .../ViewModels/SetNewPasswordViewModel.cs | 28 - .../ViewModels/UserInOrganizationViewModel.cs | 12 - .../ViewModels/WardenIterationViewModel.cs | 12 - .../Warden.Web/ViewModels/WardenViewModel.cs | 17 - .../Warden.Web/ViewModels/WatcherViewModel.cs | 14 - src/Web/Warden.Web/Views/Account/Login.cshtml | 44 -- .../Warden.Web/Views/Account/Register.cshtml | 37 -- .../Warden.Web/Views/Dashboard/Details.cshtml | 150 ----- .../Views/Dashboard/Unavailable.cshtml | 8 - src/Web/Warden.Web/Views/Home/About.cshtml | 5 - .../Views/Organization/AddUser.cshtml | 24 - .../Views/Organization/AddWarden.cshtml | 24 - .../Views/Organization/Create.cshtml | 24 - .../Views/Organization/Details.cshtml | 116 ---- .../Warden.Web/Views/Organization/Edit.cshtml | 24 - .../Views/Organization/Index.cshtml | 20 - .../Views/Organization/UserDetails.cshtml | 45 -- .../_DeleteOrganizationModal.cshtml | 15 - .../Organization/_DeleteUserModal.cshtml | 16 - .../Views/ResetPassword/Complete.cshtml | 7 - .../Views/ResetPassword/Initiate.cshtml | 24 - .../Views/ResetPassword/SetNew.cshtml | 32 - .../Views/ResetPassword/Status.cshtml | 7 - .../Warden.Web/Views/Settings/Index.cshtml | 73 --- .../Warden.Web/Views/Settings/Password.cshtml | 35 -- .../Views/Settings/_DeletApiKeyModal.cshtml | 15 - .../Warden.Web/Views/Shared/_Layout.cshtml | 55 -- src/Web/Warden.Web/Views/Shared/_Nav.cshtml | 40 -- .../Views/Shared/_Notifications.cshtml | 38 -- .../Warden.Web/Views/Warden/Details.cshtml | 118 ---- src/Web/Warden.Web/Views/Warden/Edit.cshtml | 24 - .../Warden.Web/Views/Warden/Iteration.cshtml | 109 ---- .../Views/Warden/_DeleteWardenModal.cshtml | 16 - .../Warden.Web/Views/Warden/_Exception.cshtml | 21 - .../Warden.Web/Views/Watcher/Details.cshtml | 65 -- src/Web/Warden.Web/Views/_ViewStart.cshtml | 3 - src/Web/Warden.Web/Warden.Web.csproj | 54 -- src/Web/Warden.Web/config.development.json | 2 - src/Web/Warden.Web/config.json | 50 -- src/Web/Warden.Web/config.production.json | 7 - src/Web/Warden.Web/config.staging.json | 7 - src/Web/Warden.Web/gulpfile.js | 60 -- src/Web/Warden.Web/nlog.config | 10 - src/Web/Warden.Web/package.json | 14 - src/Web/Warden.Web/web.config | 9 - .../Warden.Web/wwwroot/content/css/site.css | 38 -- .../wwwroot/content/css/site.min.css | 1 - .../Warden.Web/wwwroot/content/css/site.scss | 60 -- .../Warden.Web/wwwroot/content/img/logo.png | Bin 2972 -> 0 bytes src/Web/Warden.Web/wwwroot/content/js/app.js | 93 --- .../wwwroot/content/js/dashboard.js | 583 ------------------ .../Warden.Web/wwwroot/content/js/site.min.js | 1 - .../Warden.Tests/Core/WardenTests.cs | 0 .../Warden.Tests/Properties/AssemblyInfo.cs | 0 .../Properties/launchSettings.json | 0 .../Warden.Tests/Warden.Tests.csproj | 34 +- 328 files changed, 72 insertions(+), 23784 deletions(-) create mode 100644 Warden.sln delete mode 100644 src/Directory.Build.props delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.App/GenericCommandHandler.cs delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.App/Program.cs delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.App/Properties/AssemblyInfo.cs delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.App/RebusWardenCommandSource.cs delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.App/RebusWardenEventHandler.cs delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.App/Warden.Examples.CommandsAndEvents.App.csproj delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.Manager/GenericEventHandler.cs delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.Manager/Program.cs delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.Manager/Properties/AssemblyInfo.cs delete mode 100644 src/Examples/Warden.Examples.CommandsAndEvents.Manager/Warden.Examples.CommandsAndEvents.Manager.csproj delete mode 100644 src/Examples/Warden.Examples.Console/Program.cs delete mode 100644 src/Examples/Warden.Examples.Console/Properties/AssemblyInfo.cs delete mode 100644 src/Examples/Warden.Examples.Console/Warden.Examples.Console.csproj delete mode 100644 src/Examples/Warden.Examples.WindowsService/Program.cs delete mode 100644 src/Examples/Warden.Examples.WindowsService/Properties/AssemblyInfo.cs delete mode 100644 src/Examples/Warden.Examples.WindowsService/Warden.Examples.WindowsService.csproj delete mode 100644 src/Examples/Warden.Examples.WindowsService/WardenService.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/CachetIntegration.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/CachetIntegrationConfiguration.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/Component.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/ComponentStatus.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/Envelope.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/EnvelopeCollection.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/Extensions.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/ICachetService.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/Incident.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/IncidentStatus.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/Properties/AssemblyInfo.cs delete mode 100644 src/Integrations/Warden.Integrations.Cachet/Warden.Integrations.Cachet.csproj delete mode 100644 src/Integrations/Warden.Integrations.HttpApi/Extensions.cs delete mode 100644 src/Integrations/Warden.Integrations.HttpApi/HttpApiIntegration.cs delete mode 100644 src/Integrations/Warden.Integrations.HttpApi/HttpApiIntegrationConfiguration.cs delete mode 100644 src/Integrations/Warden.Integrations.HttpApi/IHttpService.cs delete mode 100644 src/Integrations/Warden.Integrations.HttpApi/Properties/AssemblyInfo.cs delete mode 100644 src/Integrations/Warden.Integrations.HttpApi/Warden.Integrations.HttpApi.csproj delete mode 100644 src/Integrations/Warden.Integrations.MsSql/Extensions.cs delete mode 100644 src/Integrations/Warden.Integrations.MsSql/IMsSqlService.cs delete mode 100644 src/Integrations/Warden.Integrations.MsSql/MsSqlIntegration.cs delete mode 100644 src/Integrations/Warden.Integrations.MsSql/MsSqlIntegrationConfiguration.cs delete mode 100644 src/Integrations/Warden.Integrations.MsSql/Properties/AssemblyInfo.cs delete mode 100644 src/Integrations/Warden.Integrations.MsSql/Schema.sql delete mode 100644 src/Integrations/Warden.Integrations.MsSql/Warden.Integrations.MsSql.csproj delete mode 100644 src/Integrations/Warden.Integrations.SendGrid/EmailTemplateParameter.cs delete mode 100644 src/Integrations/Warden.Integrations.SendGrid/Extensions.cs delete mode 100644 src/Integrations/Warden.Integrations.SendGrid/IEmailSender.cs delete mode 100644 src/Integrations/Warden.Integrations.SendGrid/Properties/AssemblyInfo.cs delete mode 100644 src/Integrations/Warden.Integrations.SendGrid/SendGridEmailMessage.cs delete mode 100644 src/Integrations/Warden.Integrations.SendGrid/SendGridIntegration.cs delete mode 100644 src/Integrations/Warden.Integrations.SendGrid/SendGridIntegrationConfiguration.cs delete mode 100644 src/Integrations/Warden.Integrations.SendGrid/Warden.Integrations.SendGrid.csproj delete mode 100644 src/Integrations/Warden.Integrations.Slack/Extensions.cs delete mode 100644 src/Integrations/Warden.Integrations.Slack/ISlackService.cs delete mode 100644 src/Integrations/Warden.Integrations.Slack/Properties/AssemblyInfo.cs delete mode 100644 src/Integrations/Warden.Integrations.Slack/SlackIntegration.cs delete mode 100644 src/Integrations/Warden.Integrations.Slack/SlackIntegrationConfiguration.cs delete mode 100644 src/Integrations/Warden.Integrations.Slack/Warden.Integrations.Slack.csproj delete mode 100644 src/Integrations/Warden.Integrations.Smtp/Extensions.cs delete mode 100644 src/Integrations/Warden.Integrations.Smtp/ISmtpService.cs delete mode 100644 src/Integrations/Warden.Integrations.Smtp/Properties/AssemblyInfo.cs delete mode 100644 src/Integrations/Warden.Integrations.Smtp/SmtpIntegration.cs delete mode 100644 src/Integrations/Warden.Integrations.Smtp/SmtpIntegrationConfiguration.cs delete mode 100644 src/Integrations/Warden.Integrations.Smtp/Warden.Integrations.Smtp.csproj delete mode 100644 src/Integrations/Warden.Integrations.Twilio/Extensions.cs delete mode 100644 src/Integrations/Warden.Integrations.Twilio/ITwilioService.cs delete mode 100644 src/Integrations/Warden.Integrations.Twilio/Properties/AssemblyInfo.cs delete mode 100644 src/Integrations/Warden.Integrations.Twilio/TwilioIntegration.cs delete mode 100644 src/Integrations/Warden.Integrations.Twilio/TwilioIntegrationConfiguration.cs delete mode 100644 src/Tests/Warden.Tests.EndToEnd/Properties/AssemblyInfo.cs delete mode 100644 src/Tests/Warden.Tests.EndToEnd/Warden.Tests.EndToEnd.csproj delete mode 100644 src/Tests/Warden.Tests.EndToEnd/Watchers/Web/WebWatcherTests.cs delete mode 100644 src/Tests/Warden.Tests/Integrations/Cachet/CachetIntegration_specs.cs delete mode 100644 src/Tests/Warden.Tests/Integrations/HttpApi/HttpApiIntegration_specs.cs delete mode 100644 src/Tests/Warden.Tests/Integrations/MsSql/MsSqlIntegration_specs.cs delete mode 100644 src/Tests/Warden.Tests/Integrations/SendGrid/SendGridIntegration_specs.cs delete mode 100644 src/Tests/Warden.Tests/Integrations/Slack/SlackIntegration_specs.cs delete mode 100644 src/Tests/Warden.Tests/Integrations/Twilio/TwilioIntegrationTests.cs delete mode 100644 src/Tests/Warden.Tests/Properties/launchSettings.json delete mode 100644 src/Tests/Warden.Tests/Warden.Tests.csproj delete mode 100644 src/Tests/Warden.Tests/Watchers/Disk/PerformanceWatcherTests.cs delete mode 100644 src/Tests/Warden.Tests/Watchers/MongoDb/MongoDbWatcherTests.cs delete mode 100644 src/Tests/Warden.Tests/Watchers/MsSql/MsSqlWatcherTests.cs delete mode 100644 src/Tests/Warden.Tests/Watchers/Performance/PerformanceWatcherTests.cs delete mode 100644 src/Tests/Warden.Tests/Watchers/Process/PerformanceWatcherTests.cs delete mode 100644 src/Tests/Warden.Tests/Watchers/Redis/RedisWatcherTests.cs delete mode 100644 src/Tests/Warden.Tests/Watchers/Server/ServerWatcherTests.cs delete mode 100644 src/Tests/Warden.Tests/Watchers/Web/WebWatcherTests.cs delete mode 100644 src/UpgradeLog.htm delete mode 100644 src/Warden.sln delete mode 100644 src/Watchers/Warden.Watchers.Disk/DirectoryInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/DiskCheck.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/DiskWatcher.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/DiskWatcherCheckResult.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/DiskWatcherConfiguration.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/Extensions.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/FileInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/IDiskChecker.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/PartitionInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/Properties/AssemblyInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Disk/Warden.Watchers.Disk.csproj delete mode 100644 src/Watchers/Warden.Watchers.MongoDb/Extensions.cs delete mode 100644 src/Watchers/Warden.Watchers.MongoDb/IMongoDb.cs delete mode 100644 src/Watchers/Warden.Watchers.MongoDb/IMongoDbConnection.cs delete mode 100644 src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcher.cs delete mode 100644 src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcherCheckResult.cs delete mode 100644 src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcherConfiguration.cs delete mode 100644 src/Watchers/Warden.Watchers.MongoDb/Properties/AssemblyInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.MongoDb/Warden.Watchers.MongoDb.csproj delete mode 100644 src/Watchers/Warden.Watchers.MsSql/Extensions.cs delete mode 100644 src/Watchers/Warden.Watchers.MsSql/IMsSql.cs delete mode 100644 src/Watchers/Warden.Watchers.MsSql/MsSqlWatcher.cs delete mode 100644 src/Watchers/Warden.Watchers.MsSql/MsSqlWatcherCheckResult.cs delete mode 100644 src/Watchers/Warden.Watchers.MsSql/MsSqlWatcherConfiguration.cs delete mode 100644 src/Watchers/Warden.Watchers.MsSql/Properties/AssemblyInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.MsSql/Warden.Watchers.MsSql.csproj delete mode 100644 src/Watchers/Warden.Watchers.Performance/Extensions.cs delete mode 100644 src/Watchers/Warden.Watchers.Performance/IPerformance.cs delete mode 100644 src/Watchers/Warden.Watchers.Performance/PerformanceWatcher.cs delete mode 100644 src/Watchers/Warden.Watchers.Performance/PerformanceWatcherCheckResult.cs delete mode 100644 src/Watchers/Warden.Watchers.Performance/PerformanceWatcherConfiguration.cs delete mode 100644 src/Watchers/Warden.Watchers.Performance/Properties/AssemblyInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Performance/ResourceUsage.cs delete mode 100644 src/Watchers/Warden.Watchers.Performance/Warden.Watchers.Performance.csproj delete mode 100644 src/Watchers/Warden.Watchers.Process/Extensions.cs delete mode 100644 src/Watchers/Warden.Watchers.Process/IProcessService.cs delete mode 100644 src/Watchers/Warden.Watchers.Process/ProcessInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Process/ProcessWatcher.cs delete mode 100644 src/Watchers/Warden.Watchers.Process/ProcessWatcherCheckResult.cs delete mode 100644 src/Watchers/Warden.Watchers.Process/ProcessWatcherConfiguration.cs delete mode 100644 src/Watchers/Warden.Watchers.Process/Properties/AssemblyInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Process/Warden.Watchers.Process.csproj delete mode 100644 src/Watchers/Warden.Watchers.Redis/Extensions.cs delete mode 100644 src/Watchers/Warden.Watchers.Redis/IRedis.cs delete mode 100644 src/Watchers/Warden.Watchers.Redis/IRedisConnection.cs delete mode 100644 src/Watchers/Warden.Watchers.Redis/Properties/AssemblyInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Redis/RedisWatcher.cs delete mode 100644 src/Watchers/Warden.Watchers.Redis/RedisWatcherCheckResult.cs delete mode 100644 src/Watchers/Warden.Watchers.Redis/RedisWatcherConfiguration.cs delete mode 100644 src/Watchers/Warden.Watchers.Redis/Warden.Watchers.Redis.csproj delete mode 100644 src/Watchers/Warden.Watchers.Server/ConnectionInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Server/Extensions.cs delete mode 100644 src/Watchers/Warden.Watchers.Server/IDnsResolver.cs delete mode 100644 src/Watchers/Warden.Watchers.Server/IPinger.cs delete mode 100644 src/Watchers/Warden.Watchers.Server/ITcpClient.cs delete mode 100644 src/Watchers/Warden.Watchers.Server/Properties/AssemblyInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Server/ServerWatcher.cs delete mode 100644 src/Watchers/Warden.Watchers.Server/ServerWatcherCheckResult.cs delete mode 100644 src/Watchers/Warden.Watchers.Server/ServerWatcherConfiguration.cs delete mode 100644 src/Watchers/Warden.Watchers.Server/Warden.Watchers.Server.csproj delete mode 100644 src/Watchers/Warden.Watchers.Web/Extensions.cs delete mode 100644 src/Watchers/Warden.Watchers.Web/IHttpRequest.cs delete mode 100644 src/Watchers/Warden.Watchers.Web/IHttpResponse.cs delete mode 100644 src/Watchers/Warden.Watchers.Web/IHttpService.cs delete mode 100644 src/Watchers/Warden.Watchers.Web/Properties/AssemblyInfo.cs delete mode 100644 src/Watchers/Warden.Watchers.Web/Warden.Watchers.Web.csproj delete mode 100644 src/Watchers/Warden.Watchers.Web/WebWatcher.cs delete mode 100644 src/Watchers/Warden.Watchers.Web/WebWatcherCheckResult.cs delete mode 100644 src/Watchers/Warden.Watchers.Web/WebWatcherConfiguration.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/ApiKey.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/DomainException.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/Entity.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/ExceptionInfo.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/ICompletable.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/IIdentifiable.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/ITimestampable.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/IValidatable.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/Organization.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/OrganizationRole.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/PagedQueryBase.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/PagedResult.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/PagedResultBase.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/Role.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/SecuredOperation.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/ServiceException.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/State.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/User.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/UserInOrganization.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/UserSession.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/Warden.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/WardenCheckResult.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/WardenInfo.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/WardenIteration.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/Watcher.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/WatcherCheckResult.cs delete mode 100644 src/Web/Warden.Web.Core/Domain/WatcherType.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/ExceptionDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/OrganizationDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/StatsDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/UserDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/UserInOrganizationDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/WardenCheckResultDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/WardenDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/WardenIterationDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/WardenStatsDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/WatcherCheckResultDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/WatcherDto.cs delete mode 100644 src/Web/Warden.Web.Core/Dto/WatcherStatsDto.cs delete mode 100644 src/Web/Warden.Web.Core/Extensions/ObjectExtensions.cs delete mode 100644 src/Web/Warden.Web.Core/Extensions/StringExtensions.cs delete mode 100644 src/Web/Warden.Web.Core/Factories/ISecuredOperationFactory.cs delete mode 100644 src/Web/Warden.Web.Core/Mongo/MongoConfigurator.cs delete mode 100644 src/Web/Warden.Web.Core/Mongo/Pagination.cs delete mode 100644 src/Web/Warden.Web.Core/Mongo/Queries/ApiKeyQueries.cs delete mode 100644 src/Web/Warden.Web.Core/Mongo/Queries/OrganizationQueries.cs delete mode 100644 src/Web/Warden.Web.Core/Mongo/Queries/SecuredOperationQueries.cs delete mode 100644 src/Web/Warden.Web.Core/Mongo/Queries/UserQueries.cs delete mode 100644 src/Web/Warden.Web.Core/Mongo/Queries/UserSessionQueries.cs delete mode 100644 src/Web/Warden.Web.Core/Mongo/Queries/WardenIterationQueries.cs delete mode 100644 src/Web/Warden.Web.Core/Properties/AssemblyInfo.cs delete mode 100644 src/Web/Warden.Web.Core/Properties/launchSettings.json delete mode 100644 src/Web/Warden.Web.Core/Queries/BrowseOrganizations.cs delete mode 100644 src/Web/Warden.Web.Core/Queries/BrowseWardenCheckResults.cs delete mode 100644 src/Web/Warden.Web.Core/Queries/BrowseWardenIterations.cs delete mode 100644 src/Web/Warden.Web.Core/Queries/BrowseWatchers.cs delete mode 100644 src/Web/Warden.Web.Core/Queries/GetWardenStats.cs delete mode 100644 src/Web/Warden.Web.Core/Queries/GetWatcherStats.cs delete mode 100644 src/Web/Warden.Web.Core/Services/IApiKeyService.cs delete mode 100644 src/Web/Warden.Web.Core/Services/IEmailSender.cs delete mode 100644 src/Web/Warden.Web.Core/Services/IEncrypter.cs delete mode 100644 src/Web/Warden.Web.Core/Services/IOrganizationService.cs delete mode 100644 src/Web/Warden.Web.Core/Services/ISignalRService.cs delete mode 100644 src/Web/Warden.Web.Core/Services/IStatsCalculator.cs delete mode 100644 src/Web/Warden.Web.Core/Services/IUserService.cs delete mode 100644 src/Web/Warden.Web.Core/Services/IWardenService.cs delete mode 100644 src/Web/Warden.Web.Core/Services/IWatcherService.cs delete mode 100644 src/Web/Warden.Web.Core/Settings/AccountSettings.cs delete mode 100644 src/Web/Warden.Web.Core/Settings/EmailSettings.cs delete mode 100644 src/Web/Warden.Web.Core/Settings/EmailTemplateParameterSettings.cs delete mode 100644 src/Web/Warden.Web.Core/Settings/EmailTemplateSettings.cs delete mode 100644 src/Web/Warden.Web.Core/Settings/FeatureSettings.cs delete mode 100644 src/Web/Warden.Web.Core/Warden.Web.Core.csproj delete mode 100644 src/Web/Warden.Web/.bowerrc delete mode 100644 src/Web/Warden.Web/Api/ApiController.cs delete mode 100644 src/Web/Warden.Web/Api/OrganizationController.cs delete mode 100644 src/Web/Warden.Web/Api/WardenController.cs delete mode 100644 src/Web/Warden.Web/Api/WardenIterationController.cs delete mode 100644 src/Web/Warden.Web/Bower.json delete mode 100644 src/Web/Warden.Web/Controllers/AccountController.cs delete mode 100644 src/Web/Warden.Web/Controllers/ControllerBase.cs delete mode 100644 src/Web/Warden.Web/Controllers/DashboardController.cs delete mode 100644 src/Web/Warden.Web/Controllers/HomeController.cs delete mode 100644 src/Web/Warden.Web/Controllers/OrganizationController.cs delete mode 100644 src/Web/Warden.Web/Controllers/ResetPasswordController.cs delete mode 100644 src/Web/Warden.Web/Controllers/SettingsController.cs delete mode 100644 src/Web/Warden.Web/Controllers/WardenController.cs delete mode 100644 src/Web/Warden.Web/Controllers/WatcherController.cs delete mode 100644 src/Web/Warden.Web/Extensions/AspNetExtensions.cs delete mode 100644 src/Web/Warden.Web/Extensions/TaskExtensions.cs delete mode 100644 src/Web/Warden.Web/Extensions/UrlHelperExtensions.cs delete mode 100644 src/Web/Warden.Web/Framework/Filters/ExceptionFilter.cs delete mode 100644 src/Web/Warden.Web/Framework/Filters/ExportModelStateToTempData.cs delete mode 100644 src/Web/Warden.Web/Framework/Filters/ImportModelStateFromTempData.cs delete mode 100644 src/Web/Warden.Web/Framework/Filters/ModelStateTempDataTransfer.cs delete mode 100644 src/Web/Warden.Web/Framework/FlashNotificationType.cs delete mode 100644 src/Web/Warden.Web/Framework/GeneralSettings.cs delete mode 100644 src/Web/Warden.Web/Hubs/WardenHub.cs delete mode 100644 src/Web/Warden.Web/Properties/launchSettings.json delete mode 100644 src/Web/Warden.Web/Startup.cs delete mode 100644 src/Web/Warden.Web/ViewModels/AddUserToOrganizationViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/AddWardenToOrganizationViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/ChangePasswordViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/CreateOrganizationViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/DashboardViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/EditOrganizationViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/EditWardenViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/LoginViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/OrganizationViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/RegisterViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/ResetPasswordViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/SetNewPasswordViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/UserInOrganizationViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/WardenIterationViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/WardenViewModel.cs delete mode 100644 src/Web/Warden.Web/ViewModels/WatcherViewModel.cs delete mode 100644 src/Web/Warden.Web/Views/Account/Login.cshtml delete mode 100644 src/Web/Warden.Web/Views/Account/Register.cshtml delete mode 100644 src/Web/Warden.Web/Views/Dashboard/Details.cshtml delete mode 100644 src/Web/Warden.Web/Views/Dashboard/Unavailable.cshtml delete mode 100644 src/Web/Warden.Web/Views/Home/About.cshtml delete mode 100644 src/Web/Warden.Web/Views/Organization/AddUser.cshtml delete mode 100644 src/Web/Warden.Web/Views/Organization/AddWarden.cshtml delete mode 100644 src/Web/Warden.Web/Views/Organization/Create.cshtml delete mode 100644 src/Web/Warden.Web/Views/Organization/Details.cshtml delete mode 100644 src/Web/Warden.Web/Views/Organization/Edit.cshtml delete mode 100644 src/Web/Warden.Web/Views/Organization/Index.cshtml delete mode 100644 src/Web/Warden.Web/Views/Organization/UserDetails.cshtml delete mode 100644 src/Web/Warden.Web/Views/Organization/_DeleteOrganizationModal.cshtml delete mode 100644 src/Web/Warden.Web/Views/Organization/_DeleteUserModal.cshtml delete mode 100644 src/Web/Warden.Web/Views/ResetPassword/Complete.cshtml delete mode 100644 src/Web/Warden.Web/Views/ResetPassword/Initiate.cshtml delete mode 100644 src/Web/Warden.Web/Views/ResetPassword/SetNew.cshtml delete mode 100644 src/Web/Warden.Web/Views/ResetPassword/Status.cshtml delete mode 100644 src/Web/Warden.Web/Views/Settings/Index.cshtml delete mode 100644 src/Web/Warden.Web/Views/Settings/Password.cshtml delete mode 100644 src/Web/Warden.Web/Views/Settings/_DeletApiKeyModal.cshtml delete mode 100644 src/Web/Warden.Web/Views/Shared/_Layout.cshtml delete mode 100644 src/Web/Warden.Web/Views/Shared/_Nav.cshtml delete mode 100644 src/Web/Warden.Web/Views/Shared/_Notifications.cshtml delete mode 100644 src/Web/Warden.Web/Views/Warden/Details.cshtml delete mode 100644 src/Web/Warden.Web/Views/Warden/Edit.cshtml delete mode 100644 src/Web/Warden.Web/Views/Warden/Iteration.cshtml delete mode 100644 src/Web/Warden.Web/Views/Warden/_DeleteWardenModal.cshtml delete mode 100644 src/Web/Warden.Web/Views/Warden/_Exception.cshtml delete mode 100644 src/Web/Warden.Web/Views/Watcher/Details.cshtml delete mode 100644 src/Web/Warden.Web/Views/_ViewStart.cshtml delete mode 100644 src/Web/Warden.Web/Warden.Web.csproj delete mode 100644 src/Web/Warden.Web/config.development.json delete mode 100644 src/Web/Warden.Web/config.json delete mode 100644 src/Web/Warden.Web/config.production.json delete mode 100644 src/Web/Warden.Web/config.staging.json delete mode 100644 src/Web/Warden.Web/gulpfile.js delete mode 100644 src/Web/Warden.Web/nlog.config delete mode 100644 src/Web/Warden.Web/package.json delete mode 100644 src/Web/Warden.Web/web.config delete mode 100644 src/Web/Warden.Web/wwwroot/content/css/site.css delete mode 100644 src/Web/Warden.Web/wwwroot/content/css/site.min.css delete mode 100644 src/Web/Warden.Web/wwwroot/content/css/site.scss delete mode 100644 src/Web/Warden.Web/wwwroot/content/img/logo.png delete mode 100644 src/Web/Warden.Web/wwwroot/content/js/app.js delete mode 100644 src/Web/Warden.Web/wwwroot/content/js/dashboard.js delete mode 100644 src/Web/Warden.Web/wwwroot/content/js/site.min.js rename {src/Tests => tests}/Warden.Tests/Core/WardenTests.cs (100%) rename {src/Tests => tests}/Warden.Tests/Properties/AssemblyInfo.cs (100%) rename {src/Tests/Warden.Tests.EndToEnd => tests/Warden.Tests}/Properties/launchSettings.json (100%) rename src/Integrations/Warden.Integrations.Twilio/Warden.Integrations.Twilio.csproj => tests/Warden.Tests/Warden.Tests.csproj (53%) diff --git a/README.md b/README.md index ffda37c..b72a5f0 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ Install-Package Warden **Cross-platform support** ---------------- -| Project | .NET 4.6.1 | .NET Core | Comment | +| Project | .NET Framework | .NET Standard | Comment | |----------------------|:-------------:|:------------:|--------------------------------- | **[Warden Core](https://github.com/spetz/Warden/wiki/Warden)** | + | + | | **[Disk Watcher](https://github.com/spetz/Warden/wiki/Watcher-type-Disk)** | + | + | diff --git a/Warden.sln b/Warden.sln new file mode 100644 index 0000000..4b4ee20 --- /dev/null +++ b/Warden.sln @@ -0,0 +1,56 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{6657E665-2874-47D1-B019-E558294C9BDE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Warden", "src\Warden\Warden.csproj", "{8376E3C5-EF43-4880-BC09-561AA7E5C034}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{1233A803-2DE4-4D5B-AA08-936B7FB4F05A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Warden.Tests", "tests\Warden.Tests\Warden.Tests.csproj", "{451B2B83-A347-41EC-AD31-425EA203FB06}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Debug|x64.ActiveCfg = Debug|x64 + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Debug|x64.Build.0 = Debug|x64 + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Debug|x86.ActiveCfg = Debug|x86 + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Debug|x86.Build.0 = Debug|x86 + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Release|Any CPU.Build.0 = Release|Any CPU + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Release|x64.ActiveCfg = Release|x64 + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Release|x64.Build.0 = Release|x64 + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Release|x86.ActiveCfg = Release|x86 + {8376E3C5-EF43-4880-BC09-561AA7E5C034}.Release|x86.Build.0 = Release|x86 + {451B2B83-A347-41EC-AD31-425EA203FB06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {451B2B83-A347-41EC-AD31-425EA203FB06}.Debug|Any CPU.Build.0 = Debug|Any CPU + {451B2B83-A347-41EC-AD31-425EA203FB06}.Debug|x64.ActiveCfg = Debug|x64 + {451B2B83-A347-41EC-AD31-425EA203FB06}.Debug|x64.Build.0 = Debug|x64 + {451B2B83-A347-41EC-AD31-425EA203FB06}.Debug|x86.ActiveCfg = Debug|x86 + {451B2B83-A347-41EC-AD31-425EA203FB06}.Debug|x86.Build.0 = Debug|x86 + {451B2B83-A347-41EC-AD31-425EA203FB06}.Release|Any CPU.ActiveCfg = Release|Any CPU + {451B2B83-A347-41EC-AD31-425EA203FB06}.Release|Any CPU.Build.0 = Release|Any CPU + {451B2B83-A347-41EC-AD31-425EA203FB06}.Release|x64.ActiveCfg = Release|x64 + {451B2B83-A347-41EC-AD31-425EA203FB06}.Release|x64.Build.0 = Release|x64 + {451B2B83-A347-41EC-AD31-425EA203FB06}.Release|x86.ActiveCfg = Release|x86 + {451B2B83-A347-41EC-AD31-425EA203FB06}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {8376E3C5-EF43-4880-BC09-561AA7E5C034} = {6657E665-2874-47D1-B019-E558294C9BDE} + {451B2B83-A347-41EC-AD31-425EA203FB06} = {1233A803-2DE4-4D5B-AA08-936B7FB4F05A} + EndGlobalSection +EndGlobal diff --git a/src/Directory.Build.props b/src/Directory.Build.props deleted file mode 100644 index 397b62a..0000000 --- a/src/Directory.Build.props +++ /dev/null @@ -1,5 +0,0 @@ - - - $(NoWarn);NU1605 - - \ No newline at end of file diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.App/GenericCommandHandler.cs b/src/Examples/Warden.Examples.CommandsAndEvents.App/GenericCommandHandler.cs deleted file mode 100644 index 20da231..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.App/GenericCommandHandler.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Threading.Tasks; -using Rebus.Handlers; -using Warden.Manager.Commands; - -namespace Warden.Examples.CommandsAndEvents.App -{ - public class GenericCommandHandler : IHandleMessages, IHandleMessages, - IHandleMessages, IHandleMessages, IHandleMessages - { - private readonly RebusWardenCommandSource _commandSource; - - public GenericCommandHandler(RebusWardenCommandSource commandSource) - { - _commandSource = commandSource; - } - - public async Task Handle(StopWarden message) - => await HandleCommandAsync(message); - - public async Task Handle(StartWarden message) - => await HandleCommandAsync(message); - - public async Task Handle(PauseWarden message) - => await HandleCommandAsync(message); - - public async Task Handle(KillWarden message) - => await HandleCommandAsync(message); - - public async Task Handle(PingWarden message) - => await HandleCommandAsync(message); - - private async Task HandleCommandAsync(T command) where T : IWardenCommand - { - var commandName = command.GetType().Name; - Console.WriteLine($"Received {commandName} command."); - await _commandSource.AddCommandAsync(command); - } - } -} \ No newline at end of file diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.App/Program.cs b/src/Examples/Warden.Examples.CommandsAndEvents.App/Program.cs deleted file mode 100644 index e31eddb..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.App/Program.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Threading.Tasks; -using Rebus.Activation; -using Rebus.Config; -using Rebus.Logging; -using Rebus.Routing.TypeBased; -using Warden.Core; -using Warden.Manager; -using Warden.Manager.Commands; -using Warden.Utils; -using Warden.Watchers.Server; -using Warden.Watchers.Web; - -namespace Warden.Examples.CommandsAndEvents.App -{ - public class Program - { - private static readonly RebusWardenCommandSource CommandSource = new RebusWardenCommandSource(); - private static RebusWardenEventHandler _eventHandler; - private static readonly string CommandsRoute = "Warden.Examples.CommandsAndEvents.Manager"; - - public static void Main(string[] args) - { - using (var activator = new BuiltinHandlerActivator()) - { - Console.Title = "Warden.Examples.CommandsAndEvents.App"; - activator.Register((bus, message) => new GenericCommandHandler(CommandSource)); - Configure.With(activator) - .Logging(l => l.ColoredConsole(minLevel: LogLevel.Debug)) - .Transport(t => t.UseMsmq("Warden.Examples.CommandsAndEvents.App")) - .Routing(r => r.TypeBased() - .Map(CommandsRoute) - .Map(CommandsRoute) - .Map(CommandsRoute) - .Map(CommandsRoute) - .Map(CommandsRoute)) - .Start(); - - _eventHandler = new RebusWardenEventHandler(activator.Bus); - activator.Bus.Subscribe().Wait(); - activator.Bus.Subscribe().Wait(); - activator.Bus.Subscribe().Wait(); - activator.Bus.Subscribe().Wait(); - activator.Bus.Subscribe().Wait(); - - var wardenManager = ConfigureWardenManager(); - Task.WaitAll(wardenManager.StartAsync()); - - Console.WriteLine("Stopping the bus..."); - } - } - - private static IWardenManager ConfigureWardenManager() - { - var wardenConfiguration = WardenConfiguration - .Create() - .AddWebWatcher("http://httpstat.us/200", - interval: TimeSpan.FromMilliseconds(1000), group: "websites") - .AddServerWatcher("www.google.pl", 80) - .WithConsoleLogger(minLevel: WardenLoggerLevel.All, useColors: true) - .Build(); - - var warden = WardenInstance.Create(wardenConfiguration); - - return WardenManager.Create(warden, cfg => - { - cfg.SetCommandSource(() => CommandSource) - .SetEventHandler(() => _eventHandler) - .WithConsoleLogger(minLevel: WardenLoggerLevel.All, useColors: true); - }); - } - } -} diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.App/Properties/AssemblyInfo.cs b/src/Examples/Warden.Examples.CommandsAndEvents.App/Properties/AssemblyInfo.cs deleted file mode 100644 index a2acc3c..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.App/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -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: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Examples.CommandsAndEvents.App")] -[assembly: AssemblyTrademark("")] - -// 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("c03a000b-eec8-46ab-88fc-339e035f8a3f")] diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.App/RebusWardenCommandSource.cs b/src/Examples/Warden.Examples.CommandsAndEvents.App/RebusWardenCommandSource.cs deleted file mode 100644 index 5e572cf..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.App/RebusWardenCommandSource.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Threading.Tasks; -using Warden.Manager.Commands; - -namespace Warden.Examples.CommandsAndEvents.App -{ - public class RebusWardenCommandSource : IWardenCommandSource - { - public Func CommandReceivedAsync { get; set; } - - public async Task AddCommandAsync(IWardenCommand command) - { - if(CommandReceivedAsync == null) - return; - - await CommandReceivedAsync.Invoke(command); - } - } -} \ No newline at end of file diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.App/RebusWardenEventHandler.cs b/src/Examples/Warden.Examples.CommandsAndEvents.App/RebusWardenEventHandler.cs deleted file mode 100644 index 23419f2..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.App/RebusWardenEventHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Threading.Tasks; -using Rebus.Bus; -using Warden.Manager.Events; - -namespace Warden.Examples.CommandsAndEvents.App -{ - public class RebusWardenEventHandler : IWardenEventHandler - { - private readonly IBus _bus; - - public RebusWardenEventHandler(IBus bus) - { - _bus = bus; - } - - public async Task HandleAsync(T @event) where T : IWardenEvent - { - await _bus.Publish(@event); - } - } -} \ No newline at end of file diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.App/Warden.Examples.CommandsAndEvents.App.csproj b/src/Examples/Warden.Examples.CommandsAndEvents.App/Warden.Examples.CommandsAndEvents.App.csproj deleted file mode 100644 index 284a39f..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.App/Warden.Examples.CommandsAndEvents.App.csproj +++ /dev/null @@ -1,47 +0,0 @@ - - - - Example of Warden Commands & Events app using Rebus. - 1.3.1 - Piotr Gankiewicz - net461 - Warden.Examples.CommandsAndEvents.App - Exe - Warden.Examples.CommandsAndEvents.App - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.Manager/GenericEventHandler.cs b/src/Examples/Warden.Examples.CommandsAndEvents.Manager/GenericEventHandler.cs deleted file mode 100644 index 86de374..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.Manager/GenericEventHandler.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Threading.Tasks; -using Rebus.Handlers; -using Warden.Manager.Events; - -namespace Warden.Examples.CommandsAndEvents.Manager -{ - public class GenericEventHandler : IHandleMessages, IHandleMessages - { - public async Task Handle(WardenCommandExecuted message) - => await HandleEventAsync(message); - - public async Task Handle(WardenPingResponded message) - => await HandleEventAsync(message); - - private async Task HandleEventAsync(T @event) where T : IWardenEvent - { - var eventName = @event.GetType().Name; - Console.WriteLine($"Received {eventName} event."); - await Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.Manager/Program.cs b/src/Examples/Warden.Examples.CommandsAndEvents.Manager/Program.cs deleted file mode 100644 index 673ab4c..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.Manager/Program.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using Rebus.Activation; -using Rebus.Config; -using Rebus.Logging; -using Rebus.Routing.TypeBased; -using Warden.Manager.Commands; -using Warden.Manager.Events; - -namespace Warden.Examples.CommandsAndEvents.Manager -{ - public class Program - { - private static readonly string EventsRoute = "Warden.Examples.CommandsAndEvents.App"; - - public static void Main(string[] args) - { - using (var activator = new BuiltinHandlerActivator()) - { - Console.Title = "Warden.Examples.CommandsAndEvents.Manager"; - activator.Register((bus, message) => new GenericEventHandler()); - Configure.With(activator) - .Logging(l => l.ColoredConsole(minLevel: LogLevel.Debug)) - .Transport(t => t.UseMsmq("Warden.Examples.CommandsAndEvents.Manager")) - .Routing(r => r.TypeBased() - .Map(EventsRoute) - .Map(EventsRoute)) - .Start(); - - activator.Bus.Subscribe().Wait(); - activator.Bus.Subscribe().Wait(); - - Console.WriteLine("Type q to quit\n1 to send PingWarden\n2 to send PauseWarden\n3 to send StopWarden" + - "\n4 to send StartWarden\n5 to send KillWarden"); - var isRunning = true; - while (isRunning) - { - var key = Console.ReadKey(true); - switch (char.ToLower(key.KeyChar)) - { - case '1': - Console.WriteLine("Sending PingWarden!"); - activator.Bus.Publish(new PingWarden()).Wait(); - break; - case '2': - Console.WriteLine("Sending PauseWarden!"); - activator.Bus.Publish(new PauseWarden()).Wait(); - break; - case '3': - Console.WriteLine("Sending StopWarden!"); - activator.Bus.Publish(new StopWarden()).Wait(); - break; - case '4': - Console.WriteLine("Sending StartWarden!"); - activator.Bus.Publish(new StartWarden()).Wait(); - break; - case '5': - Console.WriteLine("Sending KillWarden!"); - activator.Bus.Publish(new KillWarden()).Wait(); - break; - case 'q': - Console.WriteLine("Bye!"); - isRunning = false; - break; - } - } - Console.WriteLine("Stopping the bus..."); - } - } - } -} diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.Manager/Properties/AssemblyInfo.cs b/src/Examples/Warden.Examples.CommandsAndEvents.Manager/Properties/AssemblyInfo.cs deleted file mode 100644 index dccdf4e..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.Manager/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -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: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Examples.CommandsAndEvents.Manager")] -[assembly: AssemblyTrademark("")] - -// 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("75b125da-d804-44b6-88c4-dcca585fd438")] diff --git a/src/Examples/Warden.Examples.CommandsAndEvents.Manager/Warden.Examples.CommandsAndEvents.Manager.csproj b/src/Examples/Warden.Examples.CommandsAndEvents.Manager/Warden.Examples.CommandsAndEvents.Manager.csproj deleted file mode 100644 index 1e8b391..0000000 --- a/src/Examples/Warden.Examples.CommandsAndEvents.Manager/Warden.Examples.CommandsAndEvents.Manager.csproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - Example of Warden Commands & Events manager using Rebus. - 1.3.1 - Piotr Gankiewicz - net461 - Warden.Examples.CommandsAndEvents.Manager - Exe - Warden.Examples.CommandsAndEvents.Manager - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - false - false - false - - - - - - - - - - - - - - - - - diff --git a/src/Examples/Warden.Examples.Console/Program.cs b/src/Examples/Warden.Examples.Console/Program.cs deleted file mode 100644 index 815617d..0000000 --- a/src/Examples/Warden.Examples.Console/Program.cs +++ /dev/null @@ -1,233 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Warden.Core; -using Warden.Integrations.Cachet; -using Warden.Integrations.HttpApi; -using Warden.Integrations.MsSql; -using Warden.Integrations.Slack; -using Warden.Integrations.Smtp; -using Warden.Utils; -using Warden.Watchers; -using Warden.Watchers.Disk; -using Warden.Watchers.MongoDb; -using Warden.Watchers.MsSql; -using Warden.Watchers.Performance; -using Warden.Watchers.Process; -using Warden.Watchers.Redis; -using Warden.Watchers.Server; -using Warden.Watchers.Web; - -namespace Warden.Examples.Console -{ - - public class Program - { - public static void Main(string[] args) - { - var warden = ConfigureWarden(); - Task.WaitAll(warden.StartAsync()); - } - - private static IWarden ConfigureWarden() - { - var wardenConfiguration = WardenConfiguration - .Create() - .AddDiskWatcher(cfg => - { - cfg.WithFilesToCheck(@"D:\Test\File1.txt", @"D:\Test\File2.txt") - .WithPartitionsToCheck("D", @"E:\") - .WithDirectoriesToCheck(@"D:\Test"); - }) - .AddMongoDbWatcher("mongodb://localhost:27017", "MyDatabase", cfg => - { - cfg.WithQuery("Users", "{\"name\": \"admin\"}") - .EnsureThat(users => users.Any(user => user.role == "admin")); - }) - .AddMsSqlWatcher(@"Data Source=.\sqlexpress;Initial Catalog=MyDatabase;Integrated Security=True", cfg => - { - cfg.WithQuery("select * from users where id = @id", new Dictionary {["id"] = 1}) - .EnsureThat(users => users.Any(user => user.Name == "admin")); - }) - .AddPerformanceWatcher(cfg => cfg.EnsureThat(usage => usage.Cpu < 50 && usage.Ram < 5000), - hooks => - hooks.OnCompleted(result => System.Console.WriteLine(result.WatcherCheckResult.Description))) - .AddProcessWatcher("mongod") - .AddRedisWatcher("localhost", 1, cfg => - { - cfg.WithQuery("get test") - .EnsureThat(results => results.Any(x => x == "test-value")); - }) - .AddWebWatcher("http://httpstat.us/200", hooks => - { - hooks.OnStartAsync(check => WebsiteHookOnStartAsync(check)) - .OnSuccessAsync(check => WebsiteHookOnSuccessAsync(check)) - .OnCompletedAsync(check => WebsiteHookOnCompletedAsync(check)) - .OnFailureAsync(check => WebsiteHookOnFailureAsync(check)); - }, interval: TimeSpan.FromMilliseconds(1000), group: "websites") - .AddServerWatcher("www.google.pl", 80) - .AddWebWatcher("API watcher", "http://httpstat.us/200", HttpRequest.Post("users", new {name = "test"}, - headers: new Dictionary - { - ["User-Agent"] = "Warden", - ["Authorization"] = "Token MyBase64EncodedString" - }), cfg => cfg.EnsureThat(response => response.Headers.Any()), interval: TimeSpan.FromSeconds(3) - ) - .IntegrateWithMsSql(@"Data Source=.\sqlexpress;Initial Catalog=MyDatabase;Integrated Security=True") - //Set proper API key or credentials. - //.IntegrateWithSendGrid("api-key", "noreply@system.com", cfg => - //{ - // cfg.WithDefaultSubject("Monitoring status") - // .WithDefaultReceivers("admin@system.com"); - //}) - //.SetAggregatedWatcherHooks((hooks, integrations) => - //{ - // hooks.OnFirstFailureAsync(result => - // integrations.SendGrid().SendEmailAsync("Monitoring errors have occured.")) - // .OnFirstSuccessAsync(results => - // integrations.SendGrid().SendEmailAsync("Everything is up and running again!")); - //}) - //Set SMTP Details - //.IntegrateWithSmtp("smtp.office365.com", 587, true, cfg => - //{ - // cfg.WithCredentials("notifications@domain.domin", "mySecretPassword") - // .WithDefaultSubject("Notification Email from Warden") - // .WithDefaultToAddress("monitoring@domain.com") - // .WithDefaultFromAddress("notifications@domain.com"); - //}) - //.SetAggregatedWatcherHooks((hooks, integrations) => - //{ - // hooks.OnFirstFailureAsync(result => - // integrations.Smtp().SendEmailAsync("Monitoring errors have occured.")) - // .OnFirstSuccessAsync(results => - // integrations.Smtp().SendEmailAsync("Everything is up and running again!")); - //}) - //Set proper URL of the Warden Web API - .IntegrateWithHttpApi("https://panel.getwarden.net/api", - "pMBXwekquqlfvGPXTNT1k32RHisgguAV2yv3tJq1Wq0d2eqMsx2HuR97Lfc=", - "150bd13b-ef0d-41e7-8817-e52c3831b319") - //New Warden API integration - //.IntegrateWithHttpApi("http://localhost:20899", - // "9l5G2m695GOUvcfnIVIDX/QptT/2U30QFa95cdfmNMzBJirqF6Epcr2h", - // "WzoJnQI0oEq5tmu9irTKXg", "R8wO5nNnXU6kFojXyiG1GA") - //Set proper Slack webhook URL - //.IntegrateWithSlack("https://hooks.slack.com/services/XXX/YYY/ZZZ") - //Set proper URL of Cachet API and access token or username & password - //.IntegrateWithCachet("http://localhost/api/v1", "XYZ") - .SetGlobalWatcherHooks((hooks, integrations) => - { - hooks.OnStart(check => GlobalHookOnStart(check)) - .OnFailure(result => GlobalHookOnFailure(result)) - .OnSuccess(result => GlobalHookOnSuccess(result)) - //.OnCompletedAsync(result => GlobalHookOnCompletedPostToNewApiAsync(result, integrations.HttpApi())) - .OnCompleted(result => GlobalHookOnCompleted(result)); - }) - .SetHooks((hooks, integrations) => - { - hooks.OnIterationCompleted(iteration => OnIterationCompleted(iteration)) - //.OnIterationCompletedAsync(iteration => OnIterationCompletedCachetAsync(iteration, integrations.Cachet())) - .OnIterationCompletedAsync(iteration => integrations.MsSql() - .QueryAsync("select * from users where id = @id", GetSqlQueryParams())) - .OnIterationCompletedAsync(iteration => integrations.MsSql() - .ExecuteAsync("insert into messages values(@message)", GetSqlCommandParams())); - }) - .WithConsoleLogger(minLevel: WardenLoggerLevel.Info, useColors: true) - .Build(); - - return WardenInstance.Create(wardenConfiguration); - } - - private static IDictionary GetSqlQueryParams() - => new Dictionary {["id"] = 1}; - - private static IDictionary GetSqlCommandParams() - => new Dictionary {["message"] = "Iteration completed"}; - - private static async Task WebsiteHookOnStartAsync(IWatcherCheck check) - { - System.Console.WriteLine($"Invoking the hook OnStartAsync() by watcher: '{check.WatcherName}'."); - await Task.FromResult(true); - } - - private static async Task WebsiteHookOnSuccessAsync(IWardenCheckResult check) - { - var webWatcherCheckResult = (WebWatcherCheckResult) check.WatcherCheckResult; - System.Console.WriteLine("Invoking the hook OnSuccessAsync() " + - $"by watcher: '{webWatcherCheckResult.WatcherName}'."); - await Task.FromResult(true); - } - - private static async Task WebsiteHookOnCompletedAsync(IWardenCheckResult check) - { - System.Console.WriteLine("Invoking the hook OnCompletedAsync() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}' " + - $"in group '{check.WatcherCheckResult.WatcherGroup}'."); - await Task.FromResult(true); - } - - private static async Task WebsiteHookOnFailureAsync(IWardenCheckResult check) - { - System.Console.WriteLine("Invoking the hook OnFailureAsync() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}'."); - await Task.FromResult(true); - } - - private static void GlobalHookOnStart(IWatcherCheck check) - { - System.Console.WriteLine("Invoking the global hook OnStart() " + - $"by watcher: '{check.WatcherName}'."); - } - - private static void GlobalHookOnSuccess(IWardenCheckResult check) - { - System.Console.WriteLine("Invoking the global hook OnSuccess() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}'."); - } - - private static void GlobalHookOnCompleted(IWardenCheckResult check) - { - System.Console.WriteLine("Invoking the global hook OnCompleted() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}'."); - } - - private static async Task GlobalHookOnCompletedPostToNewApiAsync(IWardenCheckResult check, - HttpApiIntegration httpApiIntegration) - { - await httpApiIntegration.PostCheckResultToWardenPanelAsync(check); - } - - private static void GlobalHookOnFailure(IWardenCheckResult check) - { - System.Console.WriteLine("Invoking the global hook OnFailure() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}'."); - } - - private static void OnIterationCompleted(IWardenIteration wardenIteration) - { - var newLine = Environment.NewLine; - System.Console.WriteLine($"{wardenIteration.WardenName} iteration {wardenIteration.Ordinal} has completed."); - foreach (var result in wardenIteration.Results) - { - System.Console.WriteLine($"Watcher: '{result.WatcherCheckResult.WatcherName}'{newLine}" + - $"Description: {result.WatcherCheckResult.Description}{newLine}" + - $"Is valid: {result.IsValid}{newLine}" + - $"Started at: {result.StartedAt}{newLine}" + - $"Completed at: {result.CompletedAt}{newLine}" + - $"Execution time: {result.ExecutionTime}{newLine}"); - } - } - - private static async Task OnIterationCompletedMsSqlAsync(IWardenIteration wardenIteration, - MsSqlIntegration integration) - { - await integration.SaveIterationAsync(wardenIteration); - } - - private static async Task OnIterationCompletedCachetAsync(IWardenIteration wardenIteration, - CachetIntegration cachet) - { - await cachet.SaveIterationAsync(wardenIteration); - } - } -} diff --git a/src/Examples/Warden.Examples.Console/Properties/AssemblyInfo.cs b/src/Examples/Warden.Examples.Console/Properties/AssemblyInfo.cs deleted file mode 100644 index 94efcbe..0000000 --- a/src/Examples/Warden.Examples.Console/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Examples.Console")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Examples.Console")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("7e6be198-d6cd-4ca4-b3ba-7b8fd81fada1")] diff --git a/src/Examples/Warden.Examples.Console/Warden.Examples.Console.csproj b/src/Examples/Warden.Examples.Console/Warden.Examples.Console.csproj deleted file mode 100644 index a48a5e8..0000000 --- a/src/Examples/Warden.Examples.Console/Warden.Examples.Console.csproj +++ /dev/null @@ -1,46 +0,0 @@ - - - - Example of Warden Console Application. - 1.3.1 - Piotr Gankiewicz - net461 - Warden.Examples.Console - Exe - Warden.Examples.Console - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Examples/Warden.Examples.WindowsService/Program.cs b/src/Examples/Warden.Examples.WindowsService/Program.cs deleted file mode 100644 index b24c2ac..0000000 --- a/src/Examples/Warden.Examples.WindowsService/Program.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Linq; -using Topshelf; - -namespace Warden.Examples.WindowsService -{ - public class Program - { - private const string ServiceName = "Warden"; - - public static void Main(string[] args) - { - args = args.Where(a => a != ServiceName).ToArray(); - HostFactory.Run(x => - { - x.ApplyCommandLine(string.Join(" ", args)); - x.Service(service => - { - service.ConstructUsing(name => new WardenService()); - service.WhenStarted(async warden => await warden.StartAsync()); - service.WhenPaused(async warden => await warden.PauseAsync()); - service.WhenContinued(async warden => await warden.StartAsync()); - service.WhenStopped(async warden => await warden.StopAsync()); - }); - x.RunAsLocalSystem(); - x.SetDescription(ServiceName); - x.SetDisplayName(ServiceName); - x.SetServiceName(ServiceName); - }); - } - } -} diff --git a/src/Examples/Warden.Examples.WindowsService/Properties/AssemblyInfo.cs b/src/Examples/Warden.Examples.WindowsService/Properties/AssemblyInfo.cs deleted file mode 100644 index f3e38b1..0000000 --- a/src/Examples/Warden.Examples.WindowsService/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Examples.WindowsService")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Examples.WindowsService")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("0e55eec7-2b49-436e-8207-4e50bdb4112a")] diff --git a/src/Examples/Warden.Examples.WindowsService/Warden.Examples.WindowsService.csproj b/src/Examples/Warden.Examples.WindowsService/Warden.Examples.WindowsService.csproj deleted file mode 100644 index 227cddb..0000000 --- a/src/Examples/Warden.Examples.WindowsService/Warden.Examples.WindowsService.csproj +++ /dev/null @@ -1,50 +0,0 @@ - - - - Example of Warden Windows Service. - 1.3.1 - Piotr Gankiewicz - net461 - Warden.Examples.WindowsService - Exe - Warden.Examples.WindowsService - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Examples/Warden.Examples.WindowsService/WardenService.cs b/src/Examples/Warden.Examples.WindowsService/WardenService.cs deleted file mode 100644 index e235883..0000000 --- a/src/Examples/Warden.Examples.WindowsService/WardenService.cs +++ /dev/null @@ -1,226 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Warden.Core; -using Warden.Integrations.Cachet; -using Warden.Integrations.HttpApi; -using Warden.Integrations.MsSql; -using Warden.Utils; -using Warden.Watchers; -using Warden.Watchers.Disk; -using Warden.Watchers.MongoDb; -using Warden.Watchers.MsSql; -using Warden.Watchers.Performance; -using Warden.Watchers.Process; -using Warden.Watchers.Redis; -using Warden.Watchers.Server; -using Warden.Watchers.Web; - -namespace Warden.Examples.WindowsService -{ - public class WardenService - { - private static readonly IWarden Warden = ConfigureWarden(); - - public async Task StartAsync() - { - Console.WriteLine("Warden service has been started."); - await Warden.StartAsync(); - } - - public async Task PauseAsync() - { - await Warden.PauseAsync(); - Console.WriteLine("Warden service has been paused."); - } - - public async Task StopAsync() - { - await Warden.StopAsync(); - Console.WriteLine("Warden service has been stopped."); - } - - private static IWarden ConfigureWarden() - { - var wardenConfiguration = WardenConfiguration - .Create() - .AddDiskWatcher(cfg => - { - cfg.WithFilesToCheck(@"D:\Test\File1.txt", @"D:\Test\File2.txt") - .WithPartitionsToCheck("D", @"E:\") - .WithDirectoriesToCheck(@"D:\Test"); - }) - .AddMongoDbWatcher("mongodb://localhost:27017", "MyDatabase", cfg => - { - cfg.WithQuery("Users", "{\"name\": \"admin\"}") - .EnsureThat(users => users.Any(user => user.role == "admin")); - }) - .AddMsSqlWatcher(@"Data Source=.\sqlexpress;Initial Catalog=MyDatabase;Integrated Security=True", - cfg => - { - cfg.WithQuery("select * from users where id = @id", new Dictionary {["id"] = 1}) - .EnsureThat(users => users.Any(user => user.Name == "admin")); - }) - .AddPerformanceWatcher(cfg => cfg.EnsureThat(usage => usage.Cpu < 50 && usage.Ram < 5000), - hooks => - hooks.OnCompleted(result => Console.WriteLine(result.WatcherCheckResult.Description))) - .AddProcessWatcher("mongod") - .AddRedisWatcher("localhost", 1, cfg => - { - cfg.WithQuery("get test") - .EnsureThat(results => results.Any(x => x == "test-value")); - }) - .AddWebWatcher("http://httpstat.us/200", hooks => - { - hooks.OnStartAsync(check => WebsiteHookOnStartAsync(check)) - .OnSuccessAsync(check => WebsiteHookOnSuccessAsync(check)) - .OnCompletedAsync(check => WebsiteHookOnCompletedAsync(check)) - .OnFailureAsync(check => WebsiteHookOnFailureAsync(check)); - }, interval: TimeSpan.FromMilliseconds(1000)) - .AddServerWatcher("www.google.pl", 80) - .AddWebWatcher("http://httpstat.us/200", HttpRequest.Post("users", new {name = "test"}, - headers: new Dictionary - { - ["User-Agent"] = "Warden", - ["Authorization"] = "Token MyBase64EncodedString" - }), cfg => cfg.EnsureThat(response => response.Headers.Any()) - ) - .IntegrateWithMsSql(@"Data Source=.\sqlexpress;Initial Catalog=MyDatabase;Integrated Security=True") - //Set proper API key or credentials. - //.IntegrateWithSendGrid("api-key", "noreply@system.com", cfg => - //{ - // cfg.WithDefaultSubject("Monitoring status") - // .WithDefaultReceivers("admin@system.com"); - //}) - //.SetAggregatedWatcherHooks((hooks, integrations) => - //{ - // hooks.OnFirstFailureAsync(result => - // integrations.SendGrid().SendEmailAsync("Monitoring errors have occured.")) - // .OnFirstSuccessAsync(results => - // integrations.SendGrid().SendEmailAsync("Everything is up and running again!")); - //}) - //Set proper URL of the Warden Web API - .IntegrateWithHttpApi("http://localhost:11223/api", - "yroWbGkozycDLMI7+Jkyw0FzJv/O6xHzhR8+DcKTNEQECZHFBFmBbYCKJ2wiHYI=", - "20afbd7c-f803-4a2d-be64-640776930930") - //New Warden API integration - //.IntegrateWithHttpApi("http://localhost:20899", - // "9l5G2m695GOUvcfnIVIDX/QptT/2U30QFa95cdfmNMzBJirqF6Epcr2h", - // "WzoJnQI0oEq5tmu9irTKXg", "R8wO5nNnXU6kFojXyiG1GA") - //Set proper Slack webhook URL - //.IntegrateWithSlack("https://hooks.slack.com/services/XXX/YYY/ZZZ") - //Set proper URL of Cachet API and access token or username & password - //.IntegrateWithCachet("http://localhost/api/v1", "XYZ") - .SetGlobalWatcherHooks((hooks, integrations) => - { - hooks.OnStart(check => GlobalHookOnStart(check)) - .OnFailure(result => GlobalHookOnFailure(result)) - .OnSuccess(result => GlobalHookOnSuccess(result)) - //.OnCompletedAsync(result => GlobalHookOnCompletedPostToNewApiAsync(result, integrations.HttpApi())) - .OnCompleted(result => GlobalHookOnCompleted(result)); - }) - .SetHooks((hooks, integrations) => - { - hooks.OnIterationCompleted(iteration => OnIterationCompleted(iteration)) - .OnIterationCompletedAsync(iteration => OnIterationCompletedCachetAsync(iteration, integrations.Cachet())) - //.OnIterationCompletedAsync(iteration => - // integrations.Slack().SendMessageAsync($"Iteration {iteration.Ordinal} has completed.")) - .OnIterationCompletedAsync(iteration => integrations.HttpApi() - .PostIterationToWardenPanelAsync(iteration)) - .OnError(exception => Console.WriteLine(exception)) - .OnIterationCompletedAsync( - iteration => OnIterationCompletedMsSqlAsync(iteration, integrations.MsSql())); - }) - .WithConsoleLogger(minLevel: WardenLoggerLevel.Info, useColors: true) - .Build(); - - return WardenInstance.Create(wardenConfiguration); - } - - private static async Task WebsiteHookOnStartAsync(IWatcherCheck check) - { - Console.WriteLine($"Invoking the hook OnStartAsync() by watcher: '{check.WatcherName}'."); - await Task.FromResult(true); - } - - private static async Task WebsiteHookOnSuccessAsync(IWardenCheckResult check) - { - var webWatcherCheckResult = (WebWatcherCheckResult) check.WatcherCheckResult; - Console.WriteLine("Invoking the hook OnSuccessAsync() " + - $"by watcher: '{webWatcherCheckResult.WatcherName}'."); - await Task.FromResult(true); - } - - private static async Task WebsiteHookOnCompletedAsync(IWardenCheckResult check) - { - Console.WriteLine("Invoking the hook OnCompletedAsync() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}'."); - await Task.FromResult(true); - } - - private static async Task WebsiteHookOnFailureAsync(IWardenCheckResult check) - { - Console.WriteLine("Invoking the hook OnFailureAsync() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}'."); - await Task.FromResult(true); - } - - private static void GlobalHookOnStart(IWatcherCheck check) - { - Console.WriteLine("Invoking the global hook OnStart() " + - $"by watcher: '{check.WatcherName}'."); - } - - private static void GlobalHookOnSuccess(IWardenCheckResult check) - { - Console.WriteLine("Invoking the global hook OnSuccess() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}'."); - } - - private static void GlobalHookOnCompleted(IWardenCheckResult check) - { - Console.WriteLine("Invoking the global hook OnCompleted() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}'."); - } - - private static async Task GlobalHookOnCompletedPostToNewApiAsync(IWardenCheckResult check, - HttpApiIntegration httpApiIntegration) - { - await httpApiIntegration.PostCheckResultToWardenPanelAsync(check); - } - - private static void GlobalHookOnFailure(IWardenCheckResult check) - { - Console.WriteLine("Invoking the global hook OnFailure() " + - $"by watcher: '{check.WatcherCheckResult.WatcherName}'."); - } - - private static void OnIterationCompleted(IWardenIteration wardenIteration) - { - var newLine = Environment.NewLine; - Console.WriteLine($"{wardenIteration.WardenName} iteration {wardenIteration.Ordinal} has completed."); - foreach (var result in wardenIteration.Results) - { - Console.WriteLine($"Watcher: '{result.WatcherCheckResult.WatcherName}'{newLine}" + - $"Description: {result.WatcherCheckResult.Description}{newLine}" + - $"Is valid: {result.IsValid}{newLine}" + - $"Started at: {result.StartedAt}{newLine}" + - $"Completed at: {result.CompletedAt}{newLine}" + - $"Execution time: {result.ExecutionTime}{newLine}"); - } - } - - private static async Task OnIterationCompletedMsSqlAsync(IWardenIteration wardenIteration, - MsSqlIntegration integration) - { - await integration.SaveIterationAsync(wardenIteration); - } - - private static async Task OnIterationCompletedCachetAsync(IWardenIteration wardenIteration, - CachetIntegration cachet) - { - await cachet.SaveIterationAsync(wardenIteration); - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/CachetIntegration.cs b/src/Integrations/Warden.Integrations.Cachet/CachetIntegration.cs deleted file mode 100644 index bcbcfa3..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/CachetIntegration.cs +++ /dev/null @@ -1,266 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Warden.Watchers; - -namespace Warden.Integrations.Cachet -{ - /// - /// Integration with the Cachet (https://cachethq.io) - an open source status page system. - /// - public class CachetIntegration : IIntegration - { - private readonly CachetIntegrationConfiguration _configuration; - private readonly ICachetService _cachetService; - - public CachetIntegration(CachetIntegrationConfiguration configuration) - { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Cachet Integration configuration has not been provided."); - } - - _configuration = configuration; - _cachetService = _configuration.CachetServiceProvider(); - } - - /// - /// Gets a component by id using the Cachet API. - /// - /// Id of the component. - /// Details of component if exists. - public async Task GetComponentAsync(int id) - => await _cachetService.GetComponentAsync(id); - - /// - /// Gets a component by name and group id using the Cachet API. - /// - /// Name of the component. - /// The group id that the component is within (0 by default). - /// Details of component if exists. - public async Task GetComponentAsync(string name, int groupId) - => await _cachetService.GetComponentAsync(name, groupId); - - /// - /// Gets a components by name using the Cachet API. - /// - /// Name of the component. - /// Details of components if exist. - public async Task> GetComponentsAsync(string name) - => await _cachetService.GetComponentsAsync(name); - - /// - /// Creates a component using the Cachet API. - /// - /// Name of the component. - /// Status of the component (1-4). - /// Description of the component. - /// A hyperlink to the component. - /// Order of the component (0 by default) - /// The group id that the component is within (0 by default). - /// Whether the component is enabled (true by default). - /// Details of created component if operation has succeeded. - public async Task CreateComponentAsync(string name, int status, string description = null, - string link = null, int order = 0, int groupId = 0, bool enabled = true) - => await _cachetService.CreateComponentAsync(name, status, description, link, order, groupId, enabled); - - /// - /// Updates a component using the Cachet API. - /// - /// Id of the component. - /// Name of the component. - /// Status of the component (1-4). - /// A hyperlink to the component. - /// Order of the component (0 by default) - /// The group id that the component is within (0 by default). - /// Whether the component is enabled (true by default). - /// Details of created component if operation has succeeded. - public async Task UpdateComponentAsync(int id, string name = null, int status = 1, - string link = null, int order = 0, int groupId = 0, bool enabled = true) - => await _cachetService.UpdateComponentAsync(id, name, status, link, order, groupId, enabled); - - /// - /// Deletes a component using the Cachet API. - /// - /// Id of the component. - /// True if operation has succeeded, otherwise false. - public async Task DeleteComponentAsync(int id) - => await _cachetService.DeleteComponentAsync(id); - - /// - /// Gets incidents by component id using the Cachet API. - /// - /// Id of the component. - /// Details of incidents if exist. - public async Task> GetIncidentsAsync(int componentId) - => await _cachetService.GetIncidentsAsync(componentId); - - /// - /// Creates an incident using the Cachet API. - /// - /// Name of the incident. - /// A message (supporting Markdown) to explain more. - /// Status of the incident (1-4). - /// Whether the incident is publicly visible (1 = true by default). - /// Id of the component (0 by default). - /// The status to update the given component with (1-4). - /// Whether to notify subscribers (false by default). - /// When the incident was created. - /// The template slug to use. - /// The variables to pass to the template. - /// Details of created incident if operation has succeeded. - public async Task CreateIncidentAsync(string name, string message, int status, int visible = 1, - int componentId = 0, int componentStatus = 1, bool notify = false, - DateTime? createdAt = null, string template = null, params string[] vars) - => await _cachetService.CreateIncidentAsync(name, message, status, visible, componentId, - componentStatus, notify, createdAt, template, vars); - - /// - /// Updates an incident using the Cachet API. - /// - /// Id of the incident. - /// Name of the incident. - /// A message (supporting Markdown) to explain more. - /// Status of the incident (1-4). - /// Whether the incident is publicly visible (1 = true by default). - /// Id of the component (0 by default). - /// The status to update the given component with (1-4). - /// Whether to notify subscribers (false by default). - /// Details of updated incident if operation has succeeded. - public async Task UpdateIncidentAsync(int id, string name = null, string message = null, - int status = 1, int visible = 1, int componentId = 0, int componentStatus = 1, bool notify = false) - => await _cachetService.UpdateIncidentAsync(id, name, message, status, visible, componentId, - componentStatus, notify); - - /// - /// Deletes an incident using the Cachet API. - /// - /// Id of the incident. - /// True if operation has succeeded, otherwise false. - public async Task DeleteIncidentAsync(int id) - => await _cachetService.DeleteIncidentAsync(id); - - /// - /// Saves the IWardenIteration using Cachet API. - /// - /// Iteration object that will be saved using Cachet API. - /// Flag determining whether to notify the system administrator(s). - /// Flag determining whether to save the valid incidents even if there were no errors previously reported. - /// Flag determining whether to update the components and/or incidents even if the previous status is the same (false by default). - /// - public async Task SaveIterationAsync(IWardenIteration iteration, bool notify = false, - bool saveValidIncidents = false, bool updateIfStatusesAreTheSame = false) - { - var tasks = iteration.Results.Select(x => SaveCheckResultAsync(x, notify, saveValidIncidents)); - await Task.WhenAll(tasks); - } - - /// - /// Saves the IWardenCheckResult using Cachet API. - /// - /// Result object that will be saved using Cachet API. - /// Flag determining whether to notify the system administrator(s). - /// Flag determining whether to save the valid incidents even if there were no errors previously reported (false by default). - /// Flag determining whether to update the component and/or incident even if the previous status is the same (false by default). - /// - public async Task SaveCheckResultAsync(IWardenCheckResult result, bool notify = false, - bool saveValidIncidents = false, bool updateIfStatusIsTheSame = false) - { - var groupKey = result.WatcherCheckResult.WatcherGroup ?? string.Empty; - var groupId = _configuration.WatcherGroups.ContainsKey(groupKey) - ? _configuration.WatcherGroups[groupKey] - : _configuration.GroupId; - var checkResult = result.WatcherCheckResult; - var name = checkResult.WatcherName; - var status = checkResult.IsValid ? ComponentStatus.Operational : ComponentStatus.MajorOutage; - var component = await _cachetService.GetComponentAsync(checkResult.WatcherName, groupId); - if (component == null) - { - component = await _cachetService.CreateComponentAsync(name, - status, groupId: groupId); - } - else - { - component = await _cachetService.UpdateComponentAsync(component.Id, - name, status, groupId: groupId, updateIfStatusIsTheSame: updateIfStatusIsTheSame); - } - await SaveIncidentAsync(component.Id, checkResult, notify, saveValidIncidents, updateIfStatusIsTheSame); - } - - private async Task SaveIncidentAsync(int componentId, IWatcherCheckResult result, bool notify = false, - bool saveValidIncident = false, bool updateIfStatusIsTheSame = false) - { - var date = _configuration.DateTimeProvider().Date; - var componentStatus = result.IsValid ? ComponentStatus.Operational : ComponentStatus.MajorOutage; - var incidentStatus = result.IsValid ? IncidentStatus.Fixed : IncidentStatus.Identified; - var incidents = await _cachetService.GetIncidentsAsync(componentId); - var existingIncidentStatus = incidents.FirstOrDefault(x => x.ComponentId == componentId)?.Status; - - //If there's neither failure nor previous incident reported, do not report a valid service check. - if (!saveValidIncident && result.IsValid && existingIncidentStatus == null) - return; - if(!updateIfStatusIsTheSame && existingIncidentStatus == incidentStatus) - return; - - var name = $"{result.WatcherName} check is {(result.IsValid ? "valid" : "invalid")}"; - var incident = incidents.FirstOrDefault(x => x.ComponentId == componentId && - x.CreatedAt?.Date == date); - var message = result.Description; - if (incident == null) - { - incident = await _cachetService.CreateIncidentAsync(name, message, - incidentStatus, notify: notify, componentId: componentId, - componentStatus: componentStatus); - } - else - { - incident = await _cachetService.UpdateIncidentAsync(incident.Id, name, - message, incidentStatus, notify: notify, componentId: componentId, - componentStatus: componentStatus); - } - } - - /// - /// Factory method for creating a new instance of CachetIntegration. - /// - /// URL of the Cachet API. - /// Access token of the Cachet account. - /// Lambda expression for configuring the Cachet integration. - /// Instance of CachetIntegration. - public static CachetIntegration Create(string apiUrl, string accessToken, - Action configurator = null) - { - var config = new CachetIntegrationConfiguration.Builder(apiUrl, accessToken); - configurator?.Invoke(config); - - return Create(config.Build()); - } - - /// - /// Factory method for creating a new instance of CachetIntegration. - /// - /// URL of the Cachet API. - /// Username of the Cachet account. - /// Password of the Cachet account. - /// Lambda expression for configuring the Cachet integration. - /// Instance of CachetIntegration. - public static CachetIntegration Create(string apiUrl, string username, string password, - Action configurator) - { - var config = new CachetIntegrationConfiguration.Builder(apiUrl, username, password); - configurator?.Invoke(config); - - return Create(config.Build()); - } - - /// - /// Factory method for creating a new instance of CachetIntegration. - /// - /// Configuration of Cachet integration. - /// Instance of CachetIntegration. - public static CachetIntegration Create(CachetIntegrationConfiguration configuration) - => new CachetIntegration(configuration); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/CachetIntegrationConfiguration.cs b/src/Integrations/Warden.Integrations.Cachet/CachetIntegrationConfiguration.cs deleted file mode 100644 index cee86f8..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/CachetIntegrationConfiguration.cs +++ /dev/null @@ -1,317 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Warden.Integrations.Cachet -{ - /// - /// Configuration of the CachetIntegration. - /// - public class CachetIntegrationConfiguration - { - public static readonly JsonSerializerSettings DefaultJsonSerializerSettings = new JsonSerializerSettings - { - ReferenceLoopHandling = ReferenceLoopHandling.Ignore, - ContractResolver = new CamelCasePropertyNamesContractResolver(), - DateFormatString = "yyyy-MM-dd H:mm:ss", - Formatting = Formatting.Indented, - DefaultValueHandling = DefaultValueHandling.Populate, - NullValueHandling = NullValueHandling.Include, - Error = (serializer, error) => { error.ErrorContext.Handled = true; }, - Converters = new List - { - new Newtonsoft.Json.Converters.StringEnumConverter - { - AllowIntegerValues = true, - CamelCaseText = true - } - } - }; - - /// - /// Default request header name of the API key. - /// - public const string AccessTokenHeader = "X-Cachet-Token"; - - /// - /// URL of the Cachet API. - /// - public Uri ApiUrl { get; protected set; } - - /// - /// Access token of the Cachet account. - /// - public string AccessToken { get; protected set; } - - /// - /// Username of the Cachet account. - /// - public string Username { get; protected set; } - - /// - /// Password of the Cachet account. - /// - public string Password { get; protected set; } - - /// - /// Request headers. - /// - public IDictionary Headers { get; protected set; } - - /// - /// Optional timeout of the HTTP request. - /// - public TimeSpan? Timeout { get; protected set; } - - /// - /// Flag determining whether an exception should be thrown if HTTP request returns invalid reponse (false by default). - /// - public bool FailFast { get; protected set; } - - /// - /// Id of the group to which will be assigned the watchers (components) - 0 by default. - /// - public int GroupId { get; protected set; } - - /// - /// Custom JSON serializer settings of the Newtonsoft.Json library. - /// - public JsonSerializerSettings JsonSerializerSettings { get; protected set; } = DefaultJsonSerializerSettings; - - /// - /// Custom provider for the DateTime (UTC by default). - /// - public Func DateTimeProvider { get; protected set; } - - /// - /// Custom provider for the ICachetService. - /// - public Func CachetServiceProvider { get; protected set; } - - /// - /// Mappings between the Watcher group names and group ids used in Cachet to organize the similar components. - /// - public IDictionary WatcherGroups { get; protected set; } = new Dictionary(); - - /// - /// Factory method for creating a new instance of fluent builder for the CachetIntegrationConfiguration. - /// - /// URL of the Cachet API. - /// Access token of the Cachet account. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public static Builder Create(string apiUrl, string accessToken) - => new Builder(apiUrl, accessToken); - - /// - /// Factory method for creating a new instance of fluent builder for the CachetIntegrationConfiguration. - /// - /// URL of the Cachet API. - /// Username of the Cachet account. - /// Password of the Cachet account. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public static Builder Create(string apiUrl, string username, string password) - => new Builder(apiUrl, username, password); - - protected CachetIntegrationConfiguration(string apiUrl, string accessToken) - { - if (string.IsNullOrEmpty(apiUrl)) - throw new ArgumentException("API URL can not be empty.", nameof(apiUrl)); - if (string.IsNullOrWhiteSpace(accessToken)) - throw new ArgumentException("Access token can not be empty.", nameof(accessToken)); - - ApiUrl = GetApiUrl(apiUrl); - AccessToken = accessToken; - CachetServiceProvider = () => new CachetService(ApiUrl, JsonSerializerSettings, - accessToken, AccessTokenHeader); - Headers = new Dictionary(); - DateTimeProvider = () => DateTime.UtcNow; - } - - protected CachetIntegrationConfiguration(string apiUrl, string username, string password) - { - if (string.IsNullOrEmpty(apiUrl)) - throw new ArgumentException("API URL can not be empty.", nameof(apiUrl)); - if (string.IsNullOrWhiteSpace(username)) - throw new ArgumentException("Username can not be empty.", nameof(username)); - if (string.IsNullOrWhiteSpace(password)) - throw new ArgumentException("Password can not be empty.", nameof(password)); - - ApiUrl = GetApiUrl(apiUrl); - Username = username; - Password = password; - CachetServiceProvider = () => new CachetService(ApiUrl, JsonSerializerSettings, - username: username, password: password); - Headers = new Dictionary(); - DateTimeProvider = () => DateTime.UtcNow; - } - - private static Uri GetApiUrl(string apiUrl) => apiUrl.EndsWith("/") - ? new Uri(apiUrl.Substring(0, apiUrl.Length - 1)) - : new Uri(apiUrl); - - /// - /// Fluent builder for the SlackIntegrationConfiguration. - /// - public class Builder - { - protected readonly CachetIntegrationConfiguration Configuration; - - /// - /// Constructor of fluent builder for the CachetIntegrationConfiguration. - /// - /// URL of the Cachet API. - /// Access token of the Cachet account. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder(string apiUrl, string accessToken) - { - Configuration = new CachetIntegrationConfiguration(apiUrl, accessToken); - } - - /// - /// Constructor of fluent builder for the CachetIntegrationConfiguration. - /// - /// URL of the Cachet API. - /// Username of the Cachet account. - /// Password of the Cachet account. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder(string apiUrl, string username, string password) - { - Configuration = new CachetIntegrationConfiguration(apiUrl, username, password); - } - - /// - /// Timeout of the HTTP request. - /// - /// Timeout. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder WithTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); - - Configuration.Timeout = timeout; - - return this; - } - - /// - /// Request headers of the HTTP request. - /// - /// Collection of the HTTP request headers. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder WithHeaders(IDictionary headers) - { - if (headers == null || !headers.Any()) - throw new ArgumentNullException(nameof(headers), "Request headers can not be empty."); - - Configuration.Headers = headers; - - return this; - } - - /// - /// Flag determining whether an exception should be thrown if HTTP request returns invalid reponse (false by default). - /// - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder FailFast() - { - Configuration.FailFast = true; - - return this; - } - - /// - /// Id of the group to which will be assigned the watchers (components) - 0 by default. - /// Overriden by the Watcher group mappings parameter if provided. - /// - /// Id of the component group (0 by default). - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder WithGroupId(int groupId) - { - Configuration.GroupId = groupId; - - return this; - } - - /// - /// Mappings between the Watcher group names and group ids used in Cachet to organize the similar components. - /// Overrides the global Watcher Group id parameter. - /// - /// Dictionary of watcher group names and component group ids. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder WithWatcherGroups(IDictionary watcherGroups) - { - if (watcherGroups == null) - { - throw new ArgumentNullException(nameof(watcherGroups), - "Watcher groups can not be null."); - } - - Configuration.WatcherGroups = watcherGroups; - - return this; - } - - /// - /// Sets the custom JSON serializer settings of the Newtonsoft.Json library. - /// - /// Custom JSON serializer settings of the Newtonsoft.Json library. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder WithJsonSerializerSettings(JsonSerializerSettings jsonSerializerSettings) - { - if (jsonSerializerSettings == null) - { - throw new ArgumentNullException(nameof(jsonSerializerSettings), - "JSON serializer settings can not be null."); - } - - - Configuration.JsonSerializerSettings = jsonSerializerSettings; - - return this; - } - - /// - /// Provider for the custom DateTime (UTC by default). - /// - /// Custom DateTime provider. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder WithDateTimeProvider(Func dateTimeProvider) - { - Configuration.DateTimeProvider = dateTimeProvider; - - return this; - } - - /// - /// Sets the custom provider for the ICachetService. - /// - /// Custom provider for the ICachetService. - /// Lambda expression returning an instance of the ICachetService. - /// Instance of fluent builder for the CachetIntegrationConfiguration. - public Builder WithCachetServiceProvider(Func cachetServiceProvider) - { - if (cachetServiceProvider == null) - { - throw new ArgumentNullException(nameof(cachetServiceProvider), - "Cachet service provider can not be null."); - } - - Configuration.CachetServiceProvider = cachetServiceProvider; - - return this; - } - - /// - /// Builds the CachetIntegrationConfiguration and return its instance. - /// - /// Instance of CachetIntegrationConfiguration. - public CachetIntegrationConfiguration Build() => Configuration; - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/Component.cs b/src/Integrations/Warden.Integrations.Cachet/Component.cs deleted file mode 100644 index dd58393..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/Component.cs +++ /dev/null @@ -1,125 +0,0 @@ -using System; -using Newtonsoft.Json; - -namespace Warden.Integrations.Cachet -{ - /// - /// Component object used by the Cachet. - /// - public class Component - { - /// - /// Id of the component. - /// - [JsonProperty] - public int Id { get; protected set; } - - /// - /// Name of the component. - /// - [JsonProperty] - public string Name { get; protected set; } - - /// - /// Status of the component (1-4). - /// - [JsonProperty] - public int Status { get; protected set; } - - /// - /// Description of the component. - /// - public string Description { get; protected set; } - - /// - /// A hyperlink to the component. - /// - [JsonProperty] - public string Link { get; protected set; } - - /// - /// Order of the component (0 by default). - /// - [JsonProperty] - public int Order { get; protected set; } - - /// - /// The group id that the component is within (0 by default). - /// - [JsonProperty("group_id")] - public int GroupId { get; protected set; } - - /// - /// Whether the component is enabled (true by default). - /// - [JsonProperty] - public bool Enabled { get; protected set; } - - /// - /// When the component was created. - /// - [JsonProperty("created_at")] - public DateTime CreatedAt { get; protected set; } - - /// - /// When the component was updated. - /// - [JsonProperty("updated_at")] - public DateTime? UpdatedAt { get; protected set; } - - /// - /// When the component was deleted. - /// - [JsonProperty("deleted_at")] - public DateTime? DeletedAt { get; protected set; } - - /// - /// A name of the status. - /// - [JsonProperty("status_name")] - public string StatusName { get; protected set; } - - /// - /// Tags of the component. - /// - [JsonProperty] - public string[] Tags { get; protected set; } - - protected Component() - { - } - - protected Component(string name, int status, string description, - string link, int order, int groupId, bool enabled) - { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Name of the component can not be empty.", nameof(name)); - if (status < 1 || status > 4) - throw new ArgumentException("Status of the component is invalid.", nameof(name)); - - Name = name; - Description = description; - Status = status; - Link = link; - Order = order; - GroupId = groupId; - Enabled = enabled; - } - - /// - /// Factory method for creating component details. - /// - /// Name of the incident. - /// Status of the component (1-4). - /// Description of the component. - /// A hyperlink to the component. - /// Order of the component (0 by default) - /// The group id that the component is within (0 by default). - /// Whether the component is enabled (true by default). - /// Instance of Component. - public static Component Create(string name, int status, string description = null, - string link = null, int order = 0, int groupId = 0, bool enabled = true) - => new Component(name, status, description, link, order, groupId, enabled); - } -} - diff --git a/src/Integrations/Warden.Integrations.Cachet/ComponentStatus.cs b/src/Integrations/Warden.Integrations.Cachet/ComponentStatus.cs deleted file mode 100644 index 2da52bf..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/ComponentStatus.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Warden.Integrations.Cachet -{ - //Status of the component - public static class ComponentStatus - { - public static int Operational => 1; - public static int PerformanceIssues => 2; - public static int PartialOutage => 3; - public static int MajorOutage => 4; - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/Envelope.cs b/src/Integrations/Warden.Integrations.Cachet/Envelope.cs deleted file mode 100644 index 2574302..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/Envelope.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Warden.Integrations.Cachet -{ - /// - /// Envelopes the data returned from the Cachet API. - /// - /// Type of an object. - public class Envelope - { - public T Data { get; set; } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/EnvelopeCollection.cs b/src/Integrations/Warden.Integrations.Cachet/EnvelopeCollection.cs deleted file mode 100644 index 7c2f7e2..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/EnvelopeCollection.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Collections.Generic; - -namespace Warden.Integrations.Cachet -{ - /// - /// Envelopes the collection data returned from the Cachet API. - /// - /// Type of an object. - public class EnvelopeCollection - { - public List Data { get; set; } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/Extensions.cs b/src/Integrations/Warden.Integrations.Cachet/Extensions.cs deleted file mode 100644 index 9c19392..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/Extensions.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System; -using Newtonsoft.Json; -using Warden.Core; - -namespace Warden.Integrations.Cachet -{ - /// - /// Custom extension methods for the Cachet (https://cachethq.io) integration. - /// - public static class Extensions - { - internal static string ToJson(this object data, JsonSerializerSettings serializerSettings) - { - return JsonConvert.SerializeObject(data, serializerSettings); - } - - /// - /// Extension method for adding the Cachet integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// URL of the Cachet API. - /// Access token of the Cachet account. - /// Optional lambda expression for configuring the CachetIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithCachet( - this WardenConfiguration.Builder builder, - string apiUrl, string accessToken, - Action configurator = null) - { - builder.AddIntegration(CachetIntegration.Create(apiUrl, accessToken, configurator)); - - return builder; - } - - /// - /// Extension method for adding the Cachet integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// URL of the Cachet API. - /// Username of the Cachet account. - /// Password of the Cachet account. - /// Optional lambda expression for configuring the CachetIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithCachet( - this WardenConfiguration.Builder builder, - string apiUrl, string username, string password, - Action configurator = null) - { - builder.AddIntegration(CachetIntegration.Create(apiUrl, username, password, configurator)); - - return builder; - } - - /// - /// Extension method for adding the Cachet integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Configuration of CachetIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithCachet( - this WardenConfiguration.Builder builder, - CachetIntegrationConfiguration configuration) - { - builder.AddIntegration(CachetIntegration.Create(configuration)); - - return builder; - } - - /// - /// Extension method for resolving the Cachet integration from the IIntegrator. - /// - /// Instance of the IIntegrator. - /// Instance of fluent builder for the WardenConfiguration. - public static CachetIntegration Cachet(this IIntegrator integrator) - => integrator.Resolve(); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/ICachetService.cs b/src/Integrations/Warden.Integrations.Cachet/ICachetService.cs deleted file mode 100644 index c335f27..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/ICachetService.cs +++ /dev/null @@ -1,373 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Threading.Tasks; -using System.Linq; -using System.Text; -using Newtonsoft.Json; - -namespace Warden.Integrations.Cachet -{ - /// - /// Custom Cachet client for executing HTTP requests to the API. - /// - public interface ICachetService - { - /// - /// Gets a component by id using the Cachet API. - /// - /// Id of the component. - /// Details of component if exists. - Task GetComponentAsync(int id); - - /// - /// Gets a component by name and group id using the Cachet API. - /// - /// Name of the component. - /// The group id that the component is within (0 by default). - /// Details of component if exists. - Task GetComponentAsync(string name, int groupId); - - /// - /// Gets a components by name using the Cachet API. - /// - /// Name of the component. - /// Details of components if exist. - Task> GetComponentsAsync(string name); - - /// - /// Creates a component using the Cachet API. - /// - /// Name of the component. - /// Status of the component (1-4). - /// Description of the component. - /// A hyperlink to the component. - /// Order of the component (0 by default) - /// The group id that the component is within (0 by default). - /// Whether the component is enabled (true by default). - /// Flag determining whether the component should be created even if there's already existing one for the given name. - /// Details of created component if operation has succeeded. - Task CreateComponentAsync(string name, int status, string description = null, - string link = null, int order = 0, int groupId = 0, bool enabled = true, - bool createEvenIfNameIsAlreadyInUse = false); - - /// - /// Updates a component using the Cachet API. - /// - /// Id of the component. - /// Name of the component. - /// Status of the component (1-4). - /// A hyperlink to the component. - /// Order of the component (0 by default) - /// The group id that the component is within (0 by default). - /// Whether the component is enabled (true by default). - /// Flag determining whether to update the component even if the previous status is the same (false by default). - /// Details of created component if operation has succeeded. - Task UpdateComponentAsync(int id, string name = null, int status = 1, - string link = null, int order = 0, int groupId = 0, bool enabled = true, - bool updateIfStatusIsTheSame = false); - - /// - /// Deletes a component using the Cachet API. - /// - /// Id of the component. - /// True if operation has succeeded, otherwise false. - Task DeleteComponentAsync(int id); - - /// - /// Gets incidents by component id using the Cachet API. - /// - /// Id of the component. - /// Details of incidents if exist. - Task> GetIncidentsAsync(int componentId); - - /// - /// Creates an incident using the Cachet API. - /// - /// Name of the incident. - /// A message (supporting Markdown) to explain more. - /// Status of the incident (1-4). - /// Whether the incident is publicly visible (1 = true by default). - /// Id of the component (0 by default). - /// The status to update the given component with (1-4). - /// Whether to notify subscribers (false by default). - /// When the incident was created. - /// The template slug to use. - /// The variables to pass to the template. - /// Details of created incident if operation has succeeded. - Task CreateIncidentAsync(string name, string message, int status, int visible = 1, - int componentId = 0, int componentStatus = 1, bool notify = false, - DateTime? createdAt = null, string template = null, params string[] vars); - - /// - /// Updates an incident using the Cachet API. - /// - /// Id of the incident. - /// Name of the incident. - /// A message (supporting Markdown) to explain more. - /// Status of the incident (1-4). - /// Whether the incident is publicly visible (1 = true by default). - /// Id of the component (0 by default). - /// The status to update the given component with (1-4). - /// Whether to notify subscribers (false by default). - /// Details of updated incident if operation has succeeded. - Task UpdateIncidentAsync(int id, string name = null, string message = null, - int status = 1, int visible = 1, int componentId = 0, int componentStatus = 1, - bool notify = false); - - /// - /// Deletes an incident using the Cachet API. - /// - /// Id of the incident. - /// True if operation has succeeded, otherwise false. - Task DeleteIncidentAsync(int id); - } - - /// - /// Default implementation of the ICachetService based on HttpClient. - /// - public class CachetService : ICachetService - { - private readonly JsonSerializerSettings _jsonSerializerSettings; - private readonly string _accessToken; - private readonly string _accessTokenHeader; - private readonly string _username; - private readonly string _password; - private readonly HttpClient _client = new HttpClient(); - private static readonly string ComponentsEndpoint = "components"; - private static readonly string IncidentsEndpoint = "incidents"; - private static readonly string AuthorizationHeader = "Authorization"; - - public CachetService(Uri apiUrl, JsonSerializerSettings jsonSerializerSettings, - string accessToken = null, string accessTokenHeader = null, - string username = null, string password = null) - { - _jsonSerializerSettings = jsonSerializerSettings; - _accessToken = accessToken; - _accessTokenHeader = accessTokenHeader; - _username = username; - _password = password; - _client.BaseAddress = apiUrl; - } - - public async Task GetComponentAsync(int id) - { - var response = await GetAsync($"{ComponentsEndpoint}/{id}"); - - return await ProcessResponseAsync(response); - } - - public async Task GetComponentAsync(string name, int groupId) - { - var components = await GetComponentsAsync(name); - - return components.FirstOrDefault(x => x.Name.Equals(name) && x.GroupId == groupId); - } - - public async Task> GetComponentsAsync(string name) - { - var response = await GetAsync($"{ComponentsEndpoint}?name={name}&sort=created_at&order=desc&per_page=1000"); - - return await ProcessCollectionResponseAsync(response); - } - - public async Task CreateComponentAsync(string name, int status, string description = null, - string link = null, int order = 0, int groupId = 0, bool enabled = true, - bool createEvenIfNameIsAlreadyInUse = false) - { - var component = await GetComponentAsync(name, groupId); - if (createEvenIfNameIsAlreadyInUse || component == null) - { - component = Component.Create(name, status, description, link, order, groupId, enabled); - var response = await PostAsync(ComponentsEndpoint, component); - - return await ProcessResponseAsync(response); - } - - return component; - } - - public async Task UpdateComponentAsync(int id, string name = null, int status = 1, - string link = null, int order = 0, int groupId = 0, bool enabled = true, - bool updateIfStatusIsTheSame = false) - { - var component = await GetComponentAsync(id); - if (component == null) - return null; - - if (!updateIfStatusIsTheSame && component.Status == status) - return null; - - component = Component.Create(name, status, string.Empty, link, order, groupId, enabled); - var response = await PutAsync($"{ComponentsEndpoint}/{id}", component); - - return await ProcessResponseAsync(response); - } - - public async Task DeleteComponentAsync(int id) - { - var response = await DeleteAsync($"{ComponentsEndpoint}/{id}"); - - return response.IsSuccessStatusCode; - } - - public async Task> GetIncidentsAsync(int componentId) - { - var response = await GetAsync($"{IncidentsEndpoint}?component_Id={componentId}&sort=created_at&order=desc&per_page=1000"); - - return await ProcessCollectionResponseAsync(response); - } - - public async Task CreateIncidentAsync(string name, string message, int status, int visible = 1, - int componentId = 0, int componentStatus = 1, bool notify = false, - DateTime? createdAt = null, string template = null, params string[] vars) - { - var incident = Incident.Create(name, message, status, visible, componentId, componentStatus, notify, - createdAt, template, vars); - var response = await PostAsync(IncidentsEndpoint, incident); - - return await ProcessResponseAsync(response); - } - - public async Task UpdateIncidentAsync(int id, string name = null, string message = null, - int status = 1, int visible = 1, int componentId = 0, int componentStatus = 1, - bool notify = false) - { - var incident = Incident.Create(name, message, status, visible, componentId, componentStatus, notify); - var response = await PutAsync($"{IncidentsEndpoint}/{id}", incident); - - return await ProcessResponseAsync(response); - } - - public async Task DeleteIncidentAsync(int id) - { - var response = await DeleteAsync($"{IncidentsEndpoint}/{id}"); - - return response.IsSuccessStatusCode; - } - - private static async Task ProcessResponseAsync(HttpResponseMessage response) - { - if (!response.IsSuccessStatusCode) - return default(T); - - var content = await response.Content.ReadAsStringAsync(); - - return JsonConvert.DeserializeObject>(content).Data; - } - - private static async Task> ProcessCollectionResponseAsync(HttpResponseMessage response) - { - if (!response.IsSuccessStatusCode) - return Enumerable.Empty(); - - var content = await response.Content.ReadAsStringAsync(); - - return JsonConvert.DeserializeObject>(content).Data; - } - - private async Task GetAsync(string endpoint, - IDictionary headers = null, TimeSpan? timeout = null, bool failFast = false) - => await ExecuteAsync(() => _client.GetAsync(GetFullUrl(endpoint)), - headers, timeout, failFast); - - private async Task PostAsync(string endpoint, object data, - IDictionary headers = null, TimeSpan? timeout = null, bool failFast = false) - => await ExecuteAsync(() => _client.PostAsync(GetFullUrl(endpoint), SerializeData(data)), - headers, timeout, failFast); - - private async Task PutAsync(string endpoint, object data, - IDictionary headers = null, TimeSpan? timeout = null, bool failFast = false) - => await ExecuteAsync(() => _client.PutAsync(GetFullUrl(endpoint), SerializeData(data)), - headers, timeout, failFast); - - private async Task DeleteAsync(string endpoint, - IDictionary headers = null, TimeSpan? timeout = null, bool failFast = false) - => await ExecuteAsync(() => _client.DeleteAsync(GetFullUrl(endpoint)), - headers, timeout, failFast); - - private StringContent SerializeData(object data) - => new StringContent(data?.ToJson(_jsonSerializerSettings), Encoding.UTF8, "application/json"); - - private async Task ExecuteAsync(Func> request, - IDictionary headers = null, TimeSpan? timeout = null, bool failFast = false) - { - SetRequestHeaders(headers); - SetTimeout(timeout); - try - { - var response = await request(); - if (response.IsSuccessStatusCode) - return response; - if (!failFast) - return response; - - throw new Exception("Received invalid HTTP response from Cachet API" + - $" with status code: {response.StatusCode}. " + - $"Reason phrase: {response.ReasonPhrase}"); - } - catch (Exception exception) - { - if (!failFast) - return null; - - throw new Exception("There was an error while executing the HTTP request to the Cachet API: " + - $"{exception}", exception); - } - } - - private string GetFullUrl(string endpoint) => $"{_client.BaseAddress}/{endpoint}"; - - private void SetTimeout(TimeSpan? timeout) - { - if (timeout > TimeSpan.Zero) - _client.Timeout = timeout.Value; - } - - private void SetRequestHeaders(IDictionary headers) - { - SetAccessTokenHeader(); - SetAuthHeader(); - - if (headers == null) - return; - - foreach (var header in headers) - { - var existingHeader = _client.DefaultRequestHeaders - .FirstOrDefault(x => string.Equals(x.Key, header.Key, StringComparison.CurrentCultureIgnoreCase)); - if (existingHeader.Key != null) - _client.DefaultRequestHeaders.Remove(existingHeader.Key); - - _client.DefaultRequestHeaders.Add(header.Key, header.Value); - } - } - - private void SetAccessTokenHeader() - { - if (_client.DefaultRequestHeaders.Any(x => x.Key == _accessTokenHeader)) - return; - if (string.IsNullOrWhiteSpace(_accessToken)) - return; - if (string.IsNullOrWhiteSpace(_accessTokenHeader)) - return; - - _client.DefaultRequestHeaders.Add(_accessTokenHeader, _accessToken); - } - - private void SetAuthHeader() - { - if (_client.DefaultRequestHeaders.Any(x => x.Key == AuthorizationHeader)) - return; - if (string.IsNullOrWhiteSpace(_username)) - return; - if (string.IsNullOrWhiteSpace(_password)) - return; - - var credentials = $"{_username}:{_password}"; - var credentialsBytes = Encoding.UTF8.GetBytes(credentials); - var headerValue = $"Basic: {Convert.ToBase64String(credentialsBytes)}"; - _client.DefaultRequestHeaders.Add(AuthorizationHeader, headerValue); - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/Incident.cs b/src/Integrations/Warden.Integrations.Cachet/Incident.cs deleted file mode 100644 index ab3d56b..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/Incident.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using Newtonsoft.Json; - -namespace Warden.Integrations.Cachet -{ - /// - /// Incident object used by the Cachet. - /// - public class Incident - { - /// - /// Id of the incident. - /// - [JsonProperty] - public int Id { get; protected set; } - - /// - /// Name of the incident. - /// - [JsonProperty] - public string Name { get; protected set; } - - /// - /// A message (supporting Markdown) to explain more. - /// - [JsonProperty] - public string Message { get; protected set; } - - /// - /// Status of the incident (1-4). - /// - [JsonProperty] - public int Status { get; protected set; } - - /// - /// Whether the incident is publicly visible (1 = true by default). - /// - [JsonProperty] - public int Visible { get; protected set; } - - /// - /// Id of the component; - /// - [JsonProperty("component_id")] - public int ComponentId { get; protected set; } - - /// - /// The status to update the given component (1-4). - /// - [JsonProperty("component_status")] - public int ComponentStatus { get; protected set; } - - /// - /// Whether to notify subscribers (false by default). - /// - [JsonProperty] - public bool Notify { get; protected set; } - - /// - /// When the incident was created. - /// - [JsonProperty("created_at")] - public DateTime? CreatedAt { get; protected set; } - - /// - /// When the incident was updated. - /// - [JsonProperty("updated_at")] - public DateTime? UpdatedAt { get; protected set; } - - /// - /// When the incident was deleted. - /// - [JsonProperty("deleted_at")] - public DateTime? DeletedAt { get; protected set; } - - /// - /// When the incident was scheduled. - /// - [JsonProperty("scheduled_at")] - public DateTime? ScheduledAt { get; protected set; } - - /// - /// A name of the status. - /// - [JsonProperty("human_status")] - public string HumanStatus { get; protected set; } - - /// - /// The template slug to use. - /// - [JsonProperty] - public string Template { get; protected set; } - - /// - /// The variables to pass to the template. - /// - [JsonProperty] - public string[] Vars { get; protected set; } - - protected Incident() - { - } - - protected Incident(string name, string message, int status, int visible, - int componentId, int componentStatus, bool notify, - DateTime? createdAt, string template, params string[] vars) - { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Name of the incident can not be empty.", nameof(name)); - if (string.IsNullOrWhiteSpace(message)) - throw new ArgumentException("Message of the incident can not be empty.", nameof(name)); - if (status < 1 || status > 4) - throw new ArgumentException("Status of the incident is invalid.", nameof(name)); - if (visible < 0 || visible > 1) - throw new ArgumentException("Visible flag of the incident is invalid.", nameof(name)); - if (componentStatus < 1 || componentStatus > 4) - throw new ArgumentException("Status of the component is invalid.", nameof(name)); - - Name = name; - Message = message; - Status = status; - Visible = visible; - ComponentId = componentId; - ComponentStatus = componentStatus; - Notify = notify; - CreatedAt = createdAt; - Template = template; - Vars = vars; - } - - /// - /// Factory method for creating incident details. - /// - /// Name of the incident. - /// A message (supporting Markdown) to explain more. - /// Status of the incident (1-4). - /// Whether the incident is publicly visible (1 = true by default). - /// Id of the component. (Required with component_status). - /// The status to update the given incident with (1-4). - /// Whether to notify subscribers (false by default). - /// When the incident was created. - /// The template slug to use. - /// The variables to pass to the template. - /// Instance of Incident. - public static Incident Create(string name, string message, int status, int visible = 1, - int componentId = 0, int componentStatus = 1, bool notify = false, - DateTime? createdAt = null, string template = null, params string[] vars) - => new Incident(name, message, status, visible, componentId, componentStatus, - notify, createdAt, template, vars); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/IncidentStatus.cs b/src/Integrations/Warden.Integrations.Cachet/IncidentStatus.cs deleted file mode 100644 index 272aa7a..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/IncidentStatus.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Warden.Integrations.Cachet -{ - //Status of the incident - public static class IncidentStatus - { - public static int Investigating => 1; - public static int Identified => 2; - public static int Watching => 3; - public static int Fixed => 4; - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Cachet/Properties/AssemblyInfo.cs b/src/Integrations/Warden.Integrations.Cachet/Properties/AssemblyInfo.cs deleted file mode 100644 index 968e0d8..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -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: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Integrations.Cachet")] -[assembly: AssemblyTrademark("")] - -// 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("59533599-205a-4878-813f-fe2044daa79d")] diff --git a/src/Integrations/Warden.Integrations.Cachet/Warden.Integrations.Cachet.csproj b/src/Integrations/Warden.Integrations.Cachet/Warden.Integrations.Cachet.csproj deleted file mode 100644 index 5ebec27..0000000 --- a/src/Integrations/Warden.Integrations.Cachet/Warden.Integrations.Cachet.csproj +++ /dev/null @@ -1,45 +0,0 @@ - - - - Warden integration with the Cachet (https://cachethq.io). - 1.3.1 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Integrations.Cachet - Warden.Integrations.Cachet - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Integrations/Warden.Integrations.HttpApi/Extensions.cs b/src/Integrations/Warden.Integrations.HttpApi/Extensions.cs deleted file mode 100644 index 9ae273c..0000000 --- a/src/Integrations/Warden.Integrations.HttpApi/Extensions.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using Warden.Core; - -namespace Warden.Integrations.HttpApi -{ - /// - /// Custom extension methods for the HTTP API integration. - /// - public static class Extensions - { - internal static string GetFullUrl(this string baseUrl, string endpoint) - { - if (string.IsNullOrWhiteSpace(endpoint)) - return baseUrl; - - if (baseUrl.EndsWith("/")) - return $"{baseUrl}{(endpoint.StartsWith("/") ? endpoint.Substring(1) : $"{endpoint}")}"; - - return $"{baseUrl}{(endpoint.StartsWith("/") ? endpoint : $"/{endpoint}")}"; - } - - internal static string ToJson(this object data, JsonSerializerSettings serializerSettings) - { - return JsonConvert.SerializeObject(data, serializerSettings); - } - - /// - /// Extension method for adding the HTTP API integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// URL of the HTTP API. - /// Optional lambda expression for configuring the HttpApiIntegration. - public static WardenConfiguration.Builder IntegrateWithHttpApi( - this WardenConfiguration.Builder builder, - string url, - Action configurator = null) - { - builder.AddIntegration(HttpApiIntegration.Create(url, configurator: configurator)); - - return builder; - } - - /// - /// Extension method for adding the HTTP API integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// URL of the HTTP API. - /// API key of the HTTP API passed inside the custom "X-Api-Key" header. - /// Optional lambda expression for configuring the HttpApiIntegration. - public static WardenConfiguration.Builder IntegrateWithHttpApi( - this WardenConfiguration.Builder builder, - string url, string apiKey, - Action configurator = null) - { - builder.AddIntegration(HttpApiIntegration.Create(url, apiKey, configurator: configurator)); - - return builder; - } - - /// - /// Extension method for adding the HTTP API integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// URL of the HTTP API. - /// API key of the HTTP API passed inside the custom "X-Api-Key" header. - /// Id of the organization that should be used in the Warden Web Panel. - /// Optional lambda expression for configuring the HttpApiIntegration. - public static WardenConfiguration.Builder IntegrateWithHttpApi( - this WardenConfiguration.Builder builder, - string url, string apiKey, string organizationId, - Action configurator = null) - { - builder.AddIntegration(HttpApiIntegration.Create(url, apiKey, organizationId, configurator: configurator)); - - return builder; - } - - /// - /// Extension method for adding the HTTP API integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// URL of the HTTP API. - /// API key of the HTTP API passed inside the custom "X-Api-Key" header. - /// Id of the organization that should be used in the Warden Web Panel. - /// Optional id of the warden that should be used in the new Warden Web Panel. - /// Optional lambda expression for configuring the HttpApiIntegration. - public static WardenConfiguration.Builder IntegrateWithHttpApi( - this WardenConfiguration.Builder builder, - string url, string apiKey, string organizationId, string wardenId, - Action configurator = null) - { - builder.AddIntegration(HttpApiIntegration.Create(url, apiKey, organizationId, wardenId, - configurator: configurator)); - - return builder; - } - - /// - /// Extension method for adding the HTTP API integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// URL of the HTTP API. - /// API key of the HTTP API passed inside the custom "X-Api-Key" header. - /// Request headers. - /// Optional lambda expression for configuring the HttpApiIntegration. - public static WardenConfiguration.Builder IntegrateWithHttpApi( - this WardenConfiguration.Builder builder, - string url, string apiKey, IDictionary headers, - Action configurator = null) - { - builder.AddIntegration(HttpApiIntegration.Create(url, apiKey, null, null, headers, configurator)); - - return builder; - } - - /// - /// Extension method for adding the HTTP API integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// URL of the HTTP API. - /// API key of the HTTP API passed inside the custom "X-Api-Key" header. - /// Id of the organization that should be used in the Warden Web Panel. - /// Request headers. - /// Optional lambda expression for configuring the HttpApiIntegration. - public static WardenConfiguration.Builder IntegrateWithHttpApi( - this WardenConfiguration.Builder builder, - string url, string apiKey, string organizationId, IDictionary headers, - Action configurator = null) - { - builder.AddIntegration(HttpApiIntegration.Create(url, apiKey, organizationId, null, headers, configurator)); - - return builder; - } - - /// - /// Extension method for adding the HTTP API integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// URL of the HTTP API. - /// API key of the HTTP API passed inside the custom "X-Api-Key" header. - /// Id of the organization that should be used in the Warden Web Panel. - /// Optional id of the warden that should be used in the new Warden Web Panel. - /// Request headers. - /// Optional lambda expression for configuring the HttpApiIntegration. - public static WardenConfiguration.Builder IntegrateWithHttpApi( - this WardenConfiguration.Builder builder, - string url, string apiKey, string organizationId, - string wardenId, IDictionary headers, - Action configurator = null) - { - builder.AddIntegration(HttpApiIntegration.Create(url, apiKey, organizationId, wardenId, headers, - configurator)); - - return builder; - } - - /// - /// Extension method for adding the HTTP API integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Configuration of HttpApiIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithHttpApi( - this WardenConfiguration.Builder builder, - HttpApiIntegrationConfiguration configuration) - { - builder.AddIntegration(HttpApiIntegration.Create(configuration)); - - return builder; - } - - /// - /// Extension method for resolving the HTTP API integration from the IIntegrator. - /// - /// Instance of the IIntegrator. - /// Instance of fluent builder for the WardenConfiguration. - public static HttpApiIntegration HttpApi(this IIntegrator integrator) - => integrator.Resolve(); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.HttpApi/HttpApiIntegration.cs b/src/Integrations/Warden.Integrations.HttpApi/HttpApiIntegration.cs deleted file mode 100644 index de5c35a..0000000 --- a/src/Integrations/Warden.Integrations.HttpApi/HttpApiIntegration.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Warden.Integrations.HttpApi -{ - /// - /// Integration with the HTTP API for sending information about performed checks. - /// - public class HttpApiIntegration : IIntegration - { - private readonly HttpApiIntegrationConfiguration _configuration; - - public HttpApiIntegration(HttpApiIntegrationConfiguration configuration) - { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "HTTP API Integration configuration has not been provided."); - } - - _configuration = configuration; - } - - /// - /// Sends a POST request to the base URL of the HTTP API. - /// - /// Request data that will be serialized to the JSON. - /// - public async Task PostAsync(object data) - { - await PostAsync(string.Empty, data); - } - - /// - /// Sends a POST request to the specified endpoint in the HTTP API. - /// - /// Endpoint of the HTTP operation (e.g. /iterations). - /// Request data that will be serialized to the JSON. - /// - public async Task PostAsync(string endpoint, object data) - { - var baseUrl = _configuration.Uri.ToString(); - var fullUrl = baseUrl.GetFullUrl(endpoint); - - await _configuration.HttpServiceProvider().PostAsync(fullUrl, - data.ToJson(_configuration.JsonSerializerSettings), _configuration.Headers, - _configuration.Timeout, _configuration.FailFast); - } - - /// - /// Sends a POST request to the Warden Panel API endpoint. - /// - /// Iteration object that will be serialized to the JSON. - /// - public async Task PostIterationToWardenPanelAsync(IWardenIteration iteration) - { - if (iteration == null) - throw new ArgumentNullException(nameof(iteration), "Warden iteration can not be null."); - if (string.IsNullOrWhiteSpace(iteration.WardenName)) - throw new ArgumentException("Warden name can not be empty.", nameof(iteration.WardenName)); - - var baseUrl = _configuration.Uri.ToString(); - var fixedWardenName = iteration.WardenName.Replace(" ", "%20"); - var endpoint = GetWardenApiIterationEndpoint(_configuration.OrganizationId, fixedWardenName); - var fullUrl = baseUrl.GetFullUrl(endpoint); - await _configuration.HttpServiceProvider().PostAsync(fullUrl, - iteration.ToJson(_configuration.JsonSerializerSettings), _configuration.Headers, - _configuration.Timeout, _configuration.FailFast); - } - - private static string GetWardenApiIterationEndpoint(string organizationId, string wardenName) - => $"organizations/{organizationId}/wardens/{wardenName}/iterations"; - - /// - /// Sends a POST request to the new Warden Panel API endpoint. - /// - /// Warden check result object that will be serialized to the JSON. - /// - public async Task PostCheckResultToWardenPanelAsync(IWardenCheckResult checkResult) - { - if (checkResult == null) - throw new ArgumentNullException(nameof(checkResult), "Warden check result can not be null."); - - if (string.IsNullOrWhiteSpace(checkResult.WatcherCheckResult.WatcherName)) - { - throw new ArgumentException("Watcher name can not be empty.", - nameof(checkResult.WatcherCheckResult.WatcherName)); - } - - var baseUrl = _configuration.Uri.ToString(); - var endpoint = GetWardenApiChecksEndpoint(_configuration.OrganizationId, _configuration.WardenId); - var fullUrl = baseUrl.GetFullUrl(endpoint); - var data = new {check = checkResult}; - await _configuration.HttpServiceProvider().PostAsync(fullUrl, - data.ToJson(_configuration.JsonSerializerSettings), - _configuration.Headers, _configuration.Timeout, _configuration.FailFast); - } - - private static string GetWardenApiChecksEndpoint(string organizationId, string wardenId) - => $"organizations/{organizationId}/wardens/{wardenId}/checks"; - - /// - /// Factory method for creating a new instance of HttpApiIntegration. - /// - /// URL of the HTTP API. - /// Optional API key of the HTTP API passed inside the custom "X-Api-Key" header. - /// Optional id of the organization that should be used in the Warden Web Panel. - /// Optional id of the warden that should be used in the new Warden Web Panel. - /// Optional request headers. - /// Lambda expression for configuring the HttpApiIntegration integration. - /// Instance of HttpApiIntegration. - public static HttpApiIntegration Create(string url, string apiKey = null, - string organizationId = null, string wardenId = null, IDictionary headers = null, - Action configurator = null) - { - var config = new HttpApiIntegrationConfiguration.Builder(url, apiKey, organizationId, wardenId, headers); - configurator?.Invoke(config); - - return Create(config.Build()); - } - - /// - /// Factory method for creating a new instance of HttpApiIntegration. - /// - /// Configuration of HTTP API integration. - /// Instance of HttpApiIntegration. - public static HttpApiIntegration Create(HttpApiIntegrationConfiguration configuration) - => new HttpApiIntegration(configuration); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.HttpApi/HttpApiIntegrationConfiguration.cs b/src/Integrations/Warden.Integrations.HttpApi/HttpApiIntegrationConfiguration.cs deleted file mode 100644 index c79f44f..0000000 --- a/src/Integrations/Warden.Integrations.HttpApi/HttpApiIntegrationConfiguration.cs +++ /dev/null @@ -1,214 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Warden.Integrations.HttpApi -{ - /// - /// Configuration of the HttpApiIntegration. - /// - public class HttpApiIntegrationConfiguration - { - public static readonly JsonSerializerSettings DefaultJsonSerializerSettings = new JsonSerializerSettings - { - ReferenceLoopHandling = ReferenceLoopHandling.Ignore, - ContractResolver = new CamelCasePropertyNamesContractResolver(), - DateFormatString = "yyyy-MM-dd H:mm:ss", - Formatting = Formatting.Indented, - DefaultValueHandling = DefaultValueHandling.Populate, - NullValueHandling = NullValueHandling.Include, - Error = (serializer, error) => { error.ErrorContext.Handled = true; }, - Converters = new List - { - new Newtonsoft.Json.Converters.StringEnumConverter - { - AllowIntegerValues = true, - CamelCaseText = true - } - } - }; - - /// - /// Default request header name of the API key. - /// - public const string ApiKeyHeader = "X-Api-Key"; - - /// - /// URI of the HTTP API. - /// - public Uri Uri { get; protected set; } - - /// - /// API key of the HTTP API passed inside the custom "X-Api-Key" header. - /// - public string ApiKey { get; protected set; } - - /// - /// Id of the organization that should be used in the Warden Web Panel. - /// - public string OrganizationId { get; protected set; } - - /// - /// Id of the warden that should be used in the Warden Web Panel. - /// - public string WardenId { get; protected set; } - - /// - /// Request headers. - /// - public IDictionary Headers { get; protected set; } - - /// - /// Optional timeout of the HTTP request. - /// - public TimeSpan? Timeout { get; protected set; } - - /// - /// Flag determining whether an exception should be thrown if PostAsync() returns invalid reponse (false by default). - /// - public bool FailFast { get; protected set; } - - /// - /// Custom JSON serializer settings of the Newtonsoft.Json library. - /// - public JsonSerializerSettings JsonSerializerSettings { get; protected set; } = DefaultJsonSerializerSettings; - - /// - /// Custom provider for the IHttpService. - /// - public Func HttpServiceProvider { get; protected set; } - - /// - /// Factory method for creating a new instance of fluent builder for the HttpApiIntegrationConfiguration. - /// - /// URL of the HTTP API. - /// Optional API key of the HTTP API passed inside the custom "X-Api-Key" header. - /// Optional id of the organization that should be used in the Warden Web Panel. - /// Optional id of the warden that should be used in the new Warden Web Panel. - /// Optional request headers. - /// Instance of fluent builder for the HttpApiIntegrationConfiguration. - public static Builder Create(string url, string apiKey = null, - string organizationId = null, string wardenId = null, - IDictionary headers = null) - => new Builder(url, apiKey, organizationId, wardenId, headers); - - protected HttpApiIntegrationConfiguration(string url, string apiKey = null, - string organizationId = null, string wardenId = null, - IDictionary headers = null) - { - if (string.IsNullOrEmpty(url)) - throw new ArgumentException("URL can not be empty.", nameof(url)); - - Uri = new Uri(url); - Headers = headers ?? new Dictionary(); - HttpServiceProvider = () => new HttpService(new HttpClient()); - if(string.IsNullOrWhiteSpace(apiKey)) - return; - - ApiKey = apiKey; - OrganizationId = organizationId; - WardenId = wardenId; - Headers.Add(ApiKeyHeader, ApiKey); - } - - /// - /// Fluent builder for the HttpApiIntegrationConfiguration. - /// - public class Builder - { - protected readonly HttpApiIntegrationConfiguration Configuration; - - public Builder(string url, string apiKey = null, string organizationId = null, - string wardenId = null, IDictionary headers = null) - { - Configuration = new HttpApiIntegrationConfiguration(url, apiKey, organizationId, wardenId, headers); - } - - /// - /// Timeout of the HTTP request. - /// - /// Timeout. - /// Instance of fluent builder for the HttpApiIntegrationConfiguration. - public Builder WithTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); - - Configuration.Timeout = timeout; - - return this; - } - - /// - /// Request headers of the HTTP request. - /// - /// Collection of the HTTP request headers. - /// Instance of fluent builder for the HttpApiIntegrationConfiguration. - public Builder WithHeaders(IDictionary headers) - { - if (headers == null || !headers.Any()) - throw new ArgumentNullException(nameof(headers), "Request headers can not be empty."); - - Configuration.Headers = headers; - - return this; - } - - /// - /// Sets the custom JSON serializer settings of the Newtonsoft.Json library. - /// - /// Custom JSON serializer settings of the Newtonsoft.Json library. - /// Instance of fluent builder for the HttpApiIntegrationConfiguration. - public Builder WithJsonSerializerSettings(JsonSerializerSettings jsonSerializerSettings) - { - if (jsonSerializerSettings == null) - throw new ArgumentNullException(nameof(jsonSerializerSettings), - "JSON serializer settings can not be null."); - - Configuration.JsonSerializerSettings = jsonSerializerSettings; - - return this; - } - - /// - /// Sets the custom provider for the IHttpService. - /// - /// Custom provider for the IHttpService. - /// Lambda expression returning an instance of the IHttpService. - /// Instance of fluent builder for the HttpApiIntegrationConfiguration. - public Builder WithHttpServiceProvider(Func httpServiceProvider) - { - if (httpServiceProvider == null) - throw new ArgumentNullException(nameof(httpServiceProvider), - "HTTP service provider can not be null."); - - Configuration.HttpServiceProvider = httpServiceProvider; - - return this; - } - - /// - /// Flag determining whether an exception should be thrown if PostAsync() returns invalid reponse (false by default). - /// - /// Instance of fluent builder for the HttpApiIntegrationConfiguration. - public Builder FailFast() - { - Configuration.FailFast = true; - - return this; - } - - /// - /// Builds the HttpApiIntegrationConfiguration and return its instance. - /// - /// Instance of HttpApiIntegrationConfiguration. - public HttpApiIntegrationConfiguration Build() => Configuration; - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.HttpApi/IHttpService.cs b/src/Integrations/Warden.Integrations.HttpApi/IHttpService.cs deleted file mode 100644 index a58224b..0000000 --- a/src/Integrations/Warden.Integrations.HttpApi/IHttpService.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; - -namespace Warden.Integrations.HttpApi -{ - /// - /// Custom HTTP client for executing the POST request. - /// - public interface IHttpService - { - /// - /// Executes the HTTP POST request. - /// - /// Full API URL (base + endpoint) of the request (e.g. http://www.my-api.com) - /// Request data in JSON format that will be sent. - /// Optional request headers. - /// Optional timeout for the request. - /// Flag determining whether an exception should be thrown if received reponse is invalid (false by default). - /// Instance of IHttpResponse. - Task PostAsync(string url, string data, IDictionary headers = null, - TimeSpan? timeout = null, bool failFast = false); - } - - /// - /// Default implementation of the IHttpService based on HttpService. - /// - public class HttpService : IHttpService - { - private readonly HttpClient _client; - - public HttpService(HttpClient client) - { - _client = client; - } - - public async Task PostAsync(string url, string data, IDictionary headers = null, - TimeSpan? timeout = null, bool failFast = false) - { - SetRequestHeaders(headers); - SetTimeout(timeout); - try - { - var response = await _client.PostAsync(url, new StringContent( - data, Encoding.UTF8, "application/json")); - - if (response.IsSuccessStatusCode) - return; - if (!failFast) - return; - - throw new Exception($"Received invalid HTTP response with status code: {response.StatusCode}. " + - $"Reason phrase: {response.ReasonPhrase}"); - } - catch (Exception exception) - { - if (!failFast) - return; - - throw new Exception($"There was an error while executing the PostAsync(): " + - $"{exception}", exception); - } - } - - private void SetTimeout(TimeSpan? timeout) - { - if (timeout > TimeSpan.Zero) - _client.Timeout = timeout.Value; - } - - private void SetRequestHeaders(IDictionary headers) - { - if (headers == null) - return; - - foreach (var header in headers) - { - var existingHeader = _client.DefaultRequestHeaders - .FirstOrDefault(x => string.Equals(x.Key, header.Key, StringComparison.CurrentCultureIgnoreCase)); - if (existingHeader.Key != null) - _client.DefaultRequestHeaders.Remove(existingHeader.Key); - - _client.DefaultRequestHeaders.Add(header.Key, header.Value); - } - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.HttpApi/Properties/AssemblyInfo.cs b/src/Integrations/Warden.Integrations.HttpApi/Properties/AssemblyInfo.cs deleted file mode 100644 index 8af5b35..0000000 --- a/src/Integrations/Warden.Integrations.HttpApi/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Integrations.Api")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Integrations.Api")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("6c99aef7-64bb-4b76-9f43-91e2942e1455")] diff --git a/src/Integrations/Warden.Integrations.HttpApi/Warden.Integrations.HttpApi.csproj b/src/Integrations/Warden.Integrations.HttpApi/Warden.Integrations.HttpApi.csproj deleted file mode 100644 index 2fc8bf0..0000000 --- a/src/Integrations/Warden.Integrations.HttpApi/Warden.Integrations.HttpApi.csproj +++ /dev/null @@ -1,48 +0,0 @@ - - - - Warden integration with HTTP API. - 1.3.1 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Integrations.HttpApi - Warden.Integrations.HttpApi - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Integrations/Warden.Integrations.MsSql/Extensions.cs b/src/Integrations/Warden.Integrations.MsSql/Extensions.cs deleted file mode 100644 index 9749826..0000000 --- a/src/Integrations/Warden.Integrations.MsSql/Extensions.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using Warden.Core; - -namespace Warden.Integrations.MsSql -{ - public static class Extensions - { - /// - /// Extension method for adding the MS SQL integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Connection string of the MS SQL server. - /// Optional lambda expression for configuring the MsSqlIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithMsSql( - this WardenConfiguration.Builder builder, - string connectionString, - Action configurator = null) - { - builder.AddIntegration(MsSqlIntegration.Create(connectionString, configurator)); - - return builder; - } - - /// - /// Extension method for adding the MS SQL integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Configuration of MsSqlIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithMsSql( - this WardenConfiguration.Builder builder, - MsSqlIntegrationConfiguration configuration) - { - builder.AddIntegration(MsSqlIntegration.Create(configuration)); - - return builder; - } - - /// - /// Extension method for resolving the MS SQL integration from the IIntegrator. - /// - /// Instance of the IIntegrator. - /// Instance of fluent builder for the WardenConfiguration. - public static MsSqlIntegration MsSql(this IIntegrator integrator) - => integrator.Resolve(); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.MsSql/IMsSqlService.cs b/src/Integrations/Warden.Integrations.MsSql/IMsSqlService.cs deleted file mode 100644 index 543acef..0000000 --- a/src/Integrations/Warden.Integrations.MsSql/IMsSqlService.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Threading.Tasks; -using Dapper; - -namespace Warden.Integrations.MsSql -{ - /// - /// Custom MS SQL database connector for executing the SQL queries. - /// - public interface IMsSqlService - { - /// - /// Executes the SQL query and returns a collection of the strongly typed results. - /// - /// Instance of IDbConnection. - /// SQL query. - /// SQL query parameters. - /// Optional timeout. - /// Collection of the strongly typed results. - Task> QueryAsync(IDbConnection connection, string query, - IDictionary parameters, TimeSpan? timeout = null); - - /// - /// Executes the SQL command and returns a scalar representing number of affected rows. - /// - /// Instance of IDbConnection. - /// SQL command. - /// SQL command parameters. - /// Optional timeout. - /// Scalar representing the number of affected rows. - Task ExecuteAsync(IDbConnection connection, string command, - IDictionary parameters, TimeSpan? timeout = null); - } - - /// - /// Default implementation of the IMsSqlService based on Dapper. - /// - public class DapperMsSqlService : IMsSqlService - { - public async Task> QueryAsync(IDbConnection connection, string query, - IDictionary parameters, TimeSpan? timeout = null) - { - var queryParameters = new DynamicParameters(); - if (parameters != null) - { - foreach (var parameter in parameters) - { - queryParameters.Add(parameter.Key, parameter.Value); - } - } - - return await connection.QueryAsync(query, queryParameters, - commandTimeout: (int?)timeout?.TotalSeconds); - } - - public async Task ExecuteAsync(IDbConnection connection, string command, - IDictionary parameters, TimeSpan? timeout = null) - { - var commandParameters = new DynamicParameters(); - if (parameters != null) - { - foreach (var parameter in parameters) - { - commandParameters.Add(parameter.Key, parameter.Value); - } - } - - return await connection.ExecuteAsync(command, parameters, - commandTimeout: (int?) timeout?.TotalSeconds); - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.MsSql/MsSqlIntegration.cs b/src/Integrations/Warden.Integrations.MsSql/MsSqlIntegration.cs deleted file mode 100644 index cee2f23..0000000 --- a/src/Integrations/Warden.Integrations.MsSql/MsSqlIntegration.cs +++ /dev/null @@ -1,210 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Linq; -using System.Threading.Tasks; -using Warden.Watchers; - -namespace Warden.Integrations.MsSql -{ - /// - /// Integration with the MS SQL. - /// - public class MsSqlIntegration : IIntegration - { - private readonly IMsSqlService _msSqlService; - private readonly MsSqlIntegrationConfiguration _configuration; - - public MsSqlIntegration(MsSqlIntegrationConfiguration configuration) - { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "MS SQL integration configuration has not been provided."); - } - - _configuration = configuration; - _msSqlService = _configuration.MsSqlServiceProvider(); - } - - - /// - /// Executes the SQL query and returns a collection of the strongly typed results. - /// - /// SQL query. - /// SQL query parameters. - /// Collection of the strongly typed results. - public async Task> QueryAsync(string query, IDictionary parameters = null) - { - try - { - using (var connection = _configuration.ConnectionProvider(_configuration.ConnectionString)) - { - connection.Open(); - var queryToExecute = string.IsNullOrWhiteSpace(query) ? _configuration.Query : query; - var queryParameters = parameters ?? _configuration.QueryParameters; - - return await _msSqlService.QueryAsync(connection, queryToExecute, - queryParameters, _configuration.QueryTimeout); - } - } - catch (SqlException exception) - { - throw new IntegrationException("There was a SQL error while trying to execute the query.", exception); - } - catch (Exception exception) - { - throw new IntegrationException("There was an error while trying to access the MS SQL database.", - exception); - } - } - - /// - /// Executes the SQL command and returns a scalar representing the number of affected rows. - /// - /// SQL command. - /// SQL command parameters. - /// Scalar representing the number of affected rows. - public async Task ExecuteAsync(string command, IDictionary parameters = null) - { - try - { - using (var connection = _configuration.ConnectionProvider(_configuration.ConnectionString)) - { - connection.Open(); - var commandToExecute = string.IsNullOrWhiteSpace(command) ? _configuration.Command : command; - var commandParameters = parameters ?? _configuration.CommandParameters; - - return await _msSqlService.ExecuteAsync(connection, commandToExecute, - commandParameters, _configuration.CommandTimeout); - } - } - catch (SqlException exception) - { - throw new IntegrationException("There was a SQL error while trying to execute the command.", exception); - } - catch (Exception exception) - { - throw new IntegrationException("There was an error while trying to access the MS SQL database.", - exception); - } - } - - /// - /// Inserts the IWardenIteration into the MS SQL database using tables based on the provided schema file. - /// - /// Iteration object that will be saved into the MS SQL database. - /// - public async Task SaveIterationAsync(IWardenIteration iteration) - { - var wardenIterationCommand = "insert into WardenIterations values" + - "(@wardenName, @ordinal, @startedAt, @completedAt, @executionTime, @isValid);" + - "select cast(scope_identity() as bigint)"; - var wardenIterationParameters = new Dictionary - { - ["wardenName"] = iteration.WardenName, - ["ordinal"] = iteration.Ordinal, - ["startedAt"] = iteration.StartedAt, - ["completedAt"] = iteration.CompletedAt, - ["executionTime"] = iteration.ExecutionTime, - ["isValid"] = iteration.IsValid, - }; - var iterationResultIds = await QueryAsync(wardenIterationCommand, wardenIterationParameters); - var iterationId = iterationResultIds.FirstOrDefault(); - if(iterationId <= 0) - return; - await SaveWardenCheckResultsAsync(iteration.Results, iterationId); - } - - private async Task SaveWardenCheckResultsAsync(IEnumerable results, long iterationId) - { - foreach (var result in results) - { - var wardenCheckResultCommand = "insert into WardenCheckResults values (@wardenIteration_Id, @isValid, " + - "@startedAt, @completedAt, @executionTime);select cast(scope_identity() as bigint)"; - var wardenCheckResultParameters = new Dictionary - { - ["wardenIteration_Id"] = iterationId, - ["isValid"] = result.IsValid, - ["startedAt"] = result.StartedAt, - ["completedAt"] = result.CompletedAt, - ["executionTime"] = result.ExecutionTime - }; - var wardenCheckResultIds = await QueryAsync(wardenCheckResultCommand, wardenCheckResultParameters); - var wardenCheckResultId = wardenCheckResultIds.FirstOrDefault(); - if(wardenCheckResultId <= 0) - return; - await SaveWatcherCheckResultAsync(result.WatcherCheckResult, wardenCheckResultId); - await SaveExceptionAsync(result.Exception, wardenCheckResultId); - } - } - - private async Task SaveWatcherCheckResultAsync(IWatcherCheckResult result, long wardenCheckResultId) - { - if (result == null) - return; - - var watcherCheckResultCommand = "insert into WatcherCheckResults values " + - "(@wardenCheckResult_Id, @watcherName, @watcherType, @description, @isValid)"; - var watcherCheckResultParameters = new Dictionary - { - ["wardenCheckResult_Id"] = wardenCheckResultId, - ["watcherName"] = result.WatcherName, - ["watcherType"] = result.WatcherType.ToString().Split('.').Last(), - ["description"] = result.Description, - ["isValid"] = result.IsValid - }; - await ExecuteAsync(watcherCheckResultCommand, watcherCheckResultParameters); - } - - private async Task SaveExceptionAsync(Exception exception, long wardenCheckResultId, long? parentExceptionId = null) - { - if (exception == null) - return null; - - var exceptionCommand = "insert into Exceptions values (@wardenCheckResult_Id, @parentException_Id, " + - "@message, @source, @stackTrace);select cast(scope_identity() as bigint)"; - var exceptionParameters = new Dictionary - { - ["wardenCheckResult_Id"] = wardenCheckResultId, - ["parentException_Id"] = parentExceptionId, - ["message"] = exception.Message, - ["source"] = exception.Source, - ["stackTrace"] = exception.StackTrace - }; - var exceptionIds = await QueryAsync(exceptionCommand, exceptionParameters); - var exceptionId = exceptionIds.FirstOrDefault(); - if (exceptionId <= 0) - return null; - if (exception.InnerException == null) - return exceptionId; - - await SaveExceptionAsync(exception.InnerException, wardenCheckResultId, exceptionId); - - return exceptionId; - } - - /// - /// Factory method for creating a new instance of MsSqlIntegration. - /// - /// Connection string of the MS SQL server. - /// Lambda expression for configuring MS SQL integration. - /// Instance of MsSqlIntegration. - public static MsSqlIntegration Create(string connectionString, - Action configurator) - { - var config = new MsSqlIntegrationConfiguration.Builder(connectionString); - configurator?.Invoke(config); - - return Create(config.Build()); - } - - /// - /// Factory method for creating a new instance of MsSqlIntegration. - /// - /// Configuration of MS SQL integration. - /// Instance of MsSqlIntegration. - public static MsSqlIntegration Create(MsSqlIntegrationConfiguration configuration) - => new MsSqlIntegration(configuration); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.MsSql/MsSqlIntegrationConfiguration.cs b/src/Integrations/Warden.Integrations.MsSql/MsSqlIntegrationConfiguration.cs deleted file mode 100644 index f16ad60..0000000 --- a/src/Integrations/Warden.Integrations.MsSql/MsSqlIntegrationConfiguration.cs +++ /dev/null @@ -1,223 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; - -namespace Warden.Integrations.MsSql -{ - /// - /// Configuration of the MsSqlIntegration. - /// - public class MsSqlIntegrationConfiguration - { - /// - /// Connection string of the MSSQL server. - /// - public string ConnectionString { get; protected set; } - - /// - /// Read-only name of the database. - /// - public string Database { get; protected set; } - - /// - /// SQL command. - /// - public string Command { get; protected set; } - - /// - /// Collection of SQL command parameters. - /// - public IDictionary CommandParameters { get; protected set; } - - /// - /// Optional timeout of the SQL command. - /// - public TimeSpan? CommandTimeout { get; protected set; } - - /// - /// SQL Query. - /// - public string Query { get; protected set; } - - /// - /// Collection of SQL query parameters. - /// - public IDictionary QueryParameters { get; protected set; } - - /// - /// Optional timeout of the SQL query. - /// - public TimeSpan? QueryTimeout { get; protected set; } - - /// - /// Custom provider for the IDbConnection. Input parameter is connection string. - /// - public Func ConnectionProvider { get; protected set; } - - /// - /// Custom provider for the IMsSqlService. - /// - public Func MsSqlServiceProvider { get; protected set; } - - protected internal MsSqlIntegrationConfiguration(string connectionString) - { - if (string.IsNullOrEmpty(connectionString)) - throw new ArgumentException("MS SQL connection string can not be empty.", nameof(connectionString)); - - try - { - var sqlConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString); - Database = sqlConnectionStringBuilder.InitialCatalog; - } - catch (Exception ex) - { - throw new ArgumentException("MS SQL connection string is invalid.", nameof(connectionString)); - } - - ConnectionString = connectionString; - ConnectionProvider = sqlConnectionString => new SqlConnection(sqlConnectionString); - MsSqlServiceProvider = () => new DapperMsSqlService(); - } - - /// - /// Factory method for creating a new instance of fluent builder for the MsSqlIntegrationConfiguration. - /// - /// Connection string of the MS SQL server. - /// Instance of fluent builder for the MsSqlIntegrationConfiguration. - public static Builder Create(string connectionString) => new Builder(connectionString); - - /// - /// Fluent builder for the MsSqlIntegrationConfiguration. - /// - public class Builder - { - protected readonly MsSqlIntegrationConfiguration Configuration; - - /// - /// Constructor of fluent builder for the MsSqlIntegrationConfiguration. - /// - /// Connection string of the MS SQL server. - /// Instance of fluent builder for the MsSqlIntegrationConfiguration. - public Builder(string connectionString) - { - Configuration = new MsSqlIntegrationConfiguration(connectionString); - } - - /// - /// Sets the SQL command and its parameters (optional). - /// - /// SQL command. - /// Optional SQL command parameters. - /// Instance of fluent builder for the MsSqlIntegrationConfiguration. - public Builder WithCommand(string command, IDictionary parameters = null) - { - if (string.IsNullOrEmpty(command)) - throw new ArgumentException("SQL command can not be empty.", nameof(command)); - - Configuration.Command = command; - Configuration.CommandParameters = parameters; - - return this; - } - - /// - /// Sets the timeout for the SQL command execution. - /// - /// Timeout of SQL command. - /// Instance of fluent builder for the MsSqlIntegrationConfiguration. - public Builder WithCommandTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "SQL command timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("SQL command timeout can not be equal to zero.", nameof(timeout)); - - Configuration.CommandTimeout = timeout; - - return this; - } - - /// - /// Sets the SQL query and its parameters (optional). - /// - /// SQL query. - /// Optional SQL query parameters. - /// Instance of fluent builder for the MsSqlIntegrationConfiguration. - public Builder WithQuery(string query, IDictionary parameters = null) - { - if (string.IsNullOrEmpty(query)) - throw new ArgumentException("SQL query can not be empty.", nameof(query)); - - Configuration.Query = query; - Configuration.QueryParameters = parameters; - - return this; - } - - /// - /// Sets the timeout for the SQL query execution. - /// - /// Timeout of SQL query. - /// Instance of fluent builder for the MsSqlIntegrationConfiguration. - public Builder WithQueryTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "SQL query timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("SQL query timeout can not be equal to zero.", nameof(timeout)); - - Configuration.QueryTimeout = timeout; - - return this; - } - - /// - /// Sets the custom provider for the IDbConnection. - /// - /// Custom provider for the IDbConnection. - /// Lambda expression taking as an input connection string - /// and returning an instance of the IDbConnection. - /// Instance of fluent builder for the MsSqlIntegrationConfiguration. - public Builder WithConnectionProvider(Func connectionProvider) - { - if (connectionProvider == null) - { - throw new ArgumentNullException(nameof(connectionProvider), - "SQL connection provider can not be null."); - } - - Configuration.ConnectionProvider = connectionProvider; - - return this; - } - - /// - /// Sets the custom provider for the IMsSqlService. - /// - /// Custom provider for the IMsSqlService. - /// Lambda expression returning an instance of the IMsSqlService. - /// Instance of fluent builder for the MsSqlIntegrationConfiguration. - public Builder WithMsSqlServiceProvider(Func msSqlServiceProvider) - { - if (msSqlServiceProvider == null) - { - throw new ArgumentNullException(nameof(msSqlServiceProvider), - "MS SQL service provider can not be null."); - } - - Configuration.MsSqlServiceProvider = msSqlServiceProvider; - - return this; - } - - /// - /// Builds the MsSqlIntegrationConfiguration and return its instance. - /// - /// Instance of MsSqlIntegrationConfiguration. - public MsSqlIntegrationConfiguration Build() => Configuration; - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.MsSql/Properties/AssemblyInfo.cs b/src/Integrations/Warden.Integrations.MsSql/Properties/AssemblyInfo.cs deleted file mode 100644 index 37ff4fb..0000000 --- a/src/Integrations/Warden.Integrations.MsSql/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -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: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Integrations.MsSql")] -[assembly: AssemblyTrademark("")] - -// 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("bf9764b1-bcee-4379-8e13-661e64784cd4")] diff --git a/src/Integrations/Warden.Integrations.MsSql/Schema.sql b/src/Integrations/Warden.Integrations.MsSql/Schema.sql deleted file mode 100644 index f401c37..0000000 --- a/src/Integrations/Warden.Integrations.MsSql/Schema.sql +++ /dev/null @@ -1,44 +0,0 @@ -CREATE TABLE WardenIterations -( - Id bigint primary key identity not null, - WardenName nvarchar(MAX) not null, - Ordinal bigint not null, - StartedAt datetime not null, - CompletedAt datetime not null, - ExecutionTime time not null, - IsValid bit not null -) - -CREATE TABLE WardenCheckResults -( - Id bigint primary key identity not null, - WardenIteration_Id bigint not null, - IsValid bit not null, - StartedAt datetime not null, - CompletedAt datetime not null, - ExecutionTime time not null, - foreign key (WardenIteration_Id) references WardenIterations(Id) -) - -CREATE TABLE WatcherCheckResults -( - Id bigint primary key identity not null, - WardenCheckResult_Id bigint not null, - WatcherName nvarchar(MAX) not null, - WatcherType nvarchar(MAX) not null, - Description nvarchar(MAX) not null, - IsValid bit not null, - foreign key (WardenCheckResult_Id) references WardenCheckResults(Id) -) - -CREATE TABLE Exceptions -( - Id bigint primary key identity not null, - WardenCheckResult_Id bigint not null, - ParentException_Id bigint null, - Message nvarchar(MAX) null, - Source nvarchar(MAX) null, - StackTrace nvarchar(MAX) null, - foreign key (WardenCheckResult_Id) references WardenCheckResults(Id), - foreign key (ParentException_Id) references Exceptions(Id) -) \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.MsSql/Warden.Integrations.MsSql.csproj b/src/Integrations/Warden.Integrations.MsSql/Warden.Integrations.MsSql.csproj deleted file mode 100644 index e2c4e16..0000000 --- a/src/Integrations/Warden.Integrations.MsSql/Warden.Integrations.MsSql.csproj +++ /dev/null @@ -1,45 +0,0 @@ - - - - Warden integration with MS SQL. - 1.3.1 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Integrations.MsSql - Warden.Integrations.MsSql - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Integrations/Warden.Integrations.SendGrid/EmailTemplateParameter.cs b/src/Integrations/Warden.Integrations.SendGrid/EmailTemplateParameter.cs deleted file mode 100644 index 30ceff0..0000000 --- a/src/Integrations/Warden.Integrations.SendGrid/EmailTemplateParameter.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Warden.Integrations.SendGrid -{ - //Template parameter for SendGrid transactional template - public class EmailTemplateParameter - { - public string ReplacementTag { get; } - public IEnumerable Values { get; } - - public EmailTemplateParameter(string replacementTag, IEnumerable values) - { - if (string.IsNullOrWhiteSpace(replacementTag)) - throw new ArgumentException("Replacement tag can not be empty", nameof(replacementTag)); - if (values?.Any() == false) - throw new ArgumentException("Replacement tag values can not be empty", nameof(replacementTag)); - - ReplacementTag = replacementTag; - Values = values; - } - - /// - /// Factory method for creating a new instance of EmailTemplateParameter. - /// - /// Name of the replacement tag. - /// Replacement tag values. - /// Instance of EmailTemplateParameter. - public static EmailTemplateParameter Create(string replacementTag, IEnumerable values) - => new EmailTemplateParameter(replacementTag, values); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.SendGrid/Extensions.cs b/src/Integrations/Warden.Integrations.SendGrid/Extensions.cs deleted file mode 100644 index 0597149..0000000 --- a/src/Integrations/Warden.Integrations.SendGrid/Extensions.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using Warden.Core; - -namespace Warden.Integrations.SendGrid -{ - /// - /// Custom extension methods for the SendGrid integration. - /// - public static class Extensions - { - private static readonly Regex EmailRegex = - new Regex( - @"^(?("")("".+?(? - /// Extension method for adding the SendGrid integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// API key of the SendGrid account. - /// Email address of the message sender. - /// Optional lambda expression for configuring the SendGridIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithSendGrid( - this WardenConfiguration.Builder builder, - string apiKey, string sender, - Action configurator = null) - { - builder.AddIntegration(SendGridIntegration.Create(apiKey, sender, configurator)); - - return builder; - } - - /// - /// Extension method for adding the SendGrid integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Configuration of SendGridIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithSendGrid( - this WardenConfiguration.Builder builder, - SendGridIntegrationConfiguration configuration) - { - builder.AddIntegration(SendGridIntegration.Create(configuration)); - - return builder; - } - - /// - /// Extension method for resolving the SendGrid integration from the IIntegrator. - /// - /// Instance of the IIntegrator. - /// Instance of fluent builder for the WardenConfiguration. - public static SendGridIntegration SendGrid(this IIntegrator integrator) - => integrator.Resolve(); - - internal static string Or(this string value, string target) - => string.IsNullOrWhiteSpace(value) ? target : value; - - internal static bool IsEmail(this string value) => EmailRegex.IsMatch(value); - - internal static IEnumerable GetInvalidEmails(this IEnumerable values) - => values.Where(x => !EmailRegex.IsMatch(x)); - - internal static void ValidateEmails(this IEnumerable values, string parameterName) - { - if (values?.Any() == false) - return; - - var invalidEmailReceivers = values.GetInvalidEmails(); - if (invalidEmailReceivers.Any()) - { - throw new ArgumentException($"Invalid email(s): {string.Join(", ", invalidEmailReceivers)}.", - nameof(parameterName)); - } - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.SendGrid/IEmailSender.cs b/src/Integrations/Warden.Integrations.SendGrid/IEmailSender.cs deleted file mode 100644 index b46de25..0000000 --- a/src/Integrations/Warden.Integrations.SendGrid/IEmailSender.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace Warden.Integrations.SendGrid -{ - /// - /// Custom SendGrid email sender. - /// - public interface IEmailSender - { - /// - /// Sends the SendGrid message with usage of the API key. - /// - /// API key of the SendGrid account. - /// SendGrid message. - /// - Task SendMessageAsync(string apiKey, SendGridEmailMessage message); - } - - /// - /// Default implementation of the IEmailSender based on HttpClient. - /// - public class EmailSender : IEmailSender - { - private readonly HttpClient _httpClient = new HttpClient - { - BaseAddress = new Uri("https://api.sendgrid.com/v3/") - }; - - public async Task SendMessageAsync(string apiKey, SendGridEmailMessage message) - { - _httpClient.DefaultRequestHeaders.Remove("Authorization"); - _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); - - var payload = JsonConvert.SerializeObject(message); - var content = new StringContent(payload, Encoding.UTF8, "application/json"); - await _httpClient.PostAsync("mail/send", content); - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.SendGrid/Properties/AssemblyInfo.cs b/src/Integrations/Warden.Integrations.SendGrid/Properties/AssemblyInfo.cs deleted file mode 100644 index af5a40f..0000000 --- a/src/Integrations/Warden.Integrations.SendGrid/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Integrations.SendGrid")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Integrations.SendGrid")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("0acc2e25-f24d-4196-a69c-6cafef93e32c")] diff --git a/src/Integrations/Warden.Integrations.SendGrid/SendGridEmailMessage.cs b/src/Integrations/Warden.Integrations.SendGrid/SendGridEmailMessage.cs deleted file mode 100644 index 880af66..0000000 --- a/src/Integrations/Warden.Integrations.SendGrid/SendGridEmailMessage.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Collections.Generic; -using Newtonsoft.Json; - -namespace Warden.Integrations.SendGrid -{ - //Custom SendGrid message class - hopefully, a temporary solution. - public class SendGridEmailMessage - { - public List Personalizations { get; set; } = new List(); - public Person From { get; set; } = new Person(); - public string Subject { get; set; } - public List Content { get; set; } - - [JsonProperty("template_id")] - public string TemplateId { get; set; } - - public class Person - { - public string Email { get; set; } - } - - public class Personalization - { - public List To { get; set; } - public Dictionary> Substitutions { get; set; } - } - - public class MessageContent - { - public string Type { get; set; } = "text/plain"; - public string Value { get; set; } - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.SendGrid/SendGridIntegration.cs b/src/Integrations/Warden.Integrations.SendGrid/SendGridIntegration.cs deleted file mode 100644 index e8382b8..0000000 --- a/src/Integrations/Warden.Integrations.SendGrid/SendGridIntegration.cs +++ /dev/null @@ -1,244 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Warden.Integrations.SendGrid -{ - /// - /// Integration with the SendGrid - email delivery & transactional service. - /// - public class SendGridIntegration : IIntegration - { - private readonly SendGridIntegrationConfiguration _configuration; - - public SendGridIntegration(SendGridIntegrationConfiguration configuration) - { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "SendGrid Integration configuration has not been provided."); - } - - _configuration = configuration; - } - - /// - /// Sends email message. - /// - /// - public async Task SendEmailAsync() - { - await SendEmailAsync(Enumerable.Empty().ToArray()); - } - - /// - /// Sends email message. - /// - /// Receiver(s) email address(es). If default receivers have been set, it will merge these 2 lists. - /// - public async Task SendEmailAsync(params string[] receivers) - { - await SendEmailAsync(null, null, receivers); - } - - /// - /// Sends email message. - /// - /// Body of the email message. If default message has been set, it will override its value. - /// Receiver(s) email address(es). If default receivers have been set, it will merge these 2 lists. - /// - public async Task SendEmailAsync(string message, params string[] receivers) - { - await SendEmailAsync(null, message, receivers); - } - - /// - /// Sends email message. - /// - /// Subject of the email message. If default subject has been set, it will override its value. - /// Body of the email message. If default message has been set, it will override its value. - /// Receiver(s) email address(es). If default receivers have been set, it will merge these 2 lists. - /// - public async Task SendEmailAsync(string subject = null, - string message = null, params string[] receivers) - { - var emailMessage = CreateMessage(subject, receivers); - var body = _configuration.DefaultMessage + message; - var content = new SendGridEmailMessage.MessageContent - { - Value = body, - Type = _configuration.UseHtmlBody ? "text/plain" : "text/html" - }; - emailMessage.Content = new List - { - content - }; - - await SendMessageAsync(emailMessage); - } - - /// - /// Sends templated email message using transactional template. - /// - /// - public async Task SendTemplatedEmailAsync() - { - await SendTemplatedEmailAsync(Enumerable.Empty().ToArray()); - } - - /// - /// Sends templated email message using transactional template. - /// Receiver(s) email address(es). If default receivers have been set, it will merge these 2 lists. - /// - /// - public async Task SendTemplatedEmailAsync(params string[] receivers) - { - await SendTemplatedEmailAsync(null, null, null, receivers); - } - - /// - /// Sends templated email message using transactional template. - /// - /// Id of the transactional template. If default template id has been set, it will override its value. - /// - public async Task SendTemplatedEmailAsync(string templateId) - { - await SendTemplatedEmailAsync(null, templateId, null, Enumerable.Empty().ToArray()); - } - - /// - /// Sends templated email message using transactional template. - /// - /// Parameters of the transactional template. If default parameters have been set, it will merge these 2 lists. - /// - public async Task SendTemplatedEmailAsync(IEnumerable parameters) - { - await SendTemplatedEmailAsync(null, null, parameters); - } - - /// - /// Sends templated email message using transactional template. - /// - /// Id of the transactional template. If default template id has been set, it will override its value. - /// Parameters of the transactional template. If default parameters have been set, it will merge these 2 lists. - /// - public async Task SendTemplatedEmailAsync(string templateId, IEnumerable parameters) - { - await SendTemplatedEmailAsync(null, templateId, parameters, Enumerable.Empty().ToArray()); - } - - /// - /// Sends templated email message using transactional template. - /// - /// Id of the transactional template. If default template id has been set, it will override its value. - /// Receiver(s) email address(es). If default receivers have been set, it will merge these 2 lists. - /// - public async Task SendTemplatedEmailAsync(string templateId, params string[] receivers) - { - await SendTemplatedEmailAsync(null, templateId, null, receivers); - } - - /// - /// Sends templated email message using transactional template. - /// - /// Id of the transactional template. If default template id has been set, it will override its value. - /// Parameters of the transactional template. If default parameters have been set, it will merge these 2 lists. - /// Receiver(s) email address(es). If default receivers have been set, it will merge these 2 lists. - /// - public async Task SendTemplatedEmailAsync(string templateId, IEnumerable parameters, - params string[] receivers) - { - await SendTemplatedEmailAsync(null, templateId, parameters, receivers); - } - - /// - /// Sends templated email message using transactional template. - /// - /// Subject of the email message. If default subject has been set, it will override its value. - /// Id of the transactional template. If default template id has been set, it will override its value. - /// Parameters of the transactional template. If default parameters have been set, it will merge these 2 lists. - /// Receiver(s) email address(es). If default receivers have been set, it will merge these 2 lists. - /// - public async Task SendTemplatedEmailAsync(string subject = null, - string templateId = null, IEnumerable parameters = null, - params string[] receivers) - { - var emailMessage = CreateMessage(subject, receivers); - var emailTemplateId = templateId.Or(_configuration.DefaultTemplateId); - emailMessage.TemplateId = emailTemplateId; - emailMessage.Personalizations.First().Substitutions = new Dictionary>(); - var customParameters = parameters ?? Enumerable.Empty(); - var templateParameters = (_configuration.DefaultTemplateParameters.Any() - ? _configuration.DefaultTemplateParameters.Union(customParameters) - : customParameters).ToList(); - - foreach (var parameter in templateParameters) - { - emailMessage.Personalizations.First().Substitutions[parameter.ReplacementTag] = parameter.Values.ToList(); - } - - await SendMessageAsync(emailMessage); - } - - private SendGridEmailMessage CreateMessage(string subject = null, params string[] receivers) - { - var customReceivers = receivers ?? Enumerable.Empty(); - var emailReceivers = (_configuration.DefaultReceivers.Any() - ? _configuration.DefaultReceivers.Union(customReceivers) - : customReceivers).ToList(); - if (!emailReceivers.Any()) - throw new ArgumentException("Email message receivers have not been defined.", nameof(emailReceivers)); - - var emailSubject = string.IsNullOrWhiteSpace(subject) ? _configuration.DefaultSubject : subject; - emailReceivers.ValidateEmails(nameof(receivers)); - var emailMessage = new SendGridEmailMessage - { - Subject = emailSubject, - From = new SendGridEmailMessage.Person - { - Email = _configuration.Sender - } - }; - emailMessage.Personalizations.Add(new SendGridEmailMessage.Personalization - { - To = emailReceivers.Select(x => new SendGridEmailMessage.Person - { - Email = x - }).ToList() - }); - - return emailMessage; - } - - private async Task SendMessageAsync(SendGridEmailMessage message) - { - var emailSender = _configuration.EmailSenderProvider(); - await emailSender.SendMessageAsync(_configuration.ApiKey, message); - } - - /// - /// Factory method for creating a new instance of SendGridIntegration. - /// - /// API key of the SendGrid account. - /// Email address of the message sender. - /// Lambda expression for configuring the SendGrid integration. - /// Instance of SendGridIntegration. - public static SendGridIntegration Create(string apiKey, string sender, - Action configurator = null) - { - var config = new SendGridIntegrationConfiguration.Builder(apiKey, sender); - configurator?.Invoke(config); - - return Create(config.Build()); - } - - /// - /// Factory method for creating a new instance of SendGridIntegration. - /// - /// Configuration of SendGrid integration. - /// Instance of SendGridIntegration. - public static SendGridIntegration Create(SendGridIntegrationConfiguration configuration) - => new SendGridIntegration(configuration); - } -} diff --git a/src/Integrations/Warden.Integrations.SendGrid/SendGridIntegrationConfiguration.cs b/src/Integrations/Warden.Integrations.SendGrid/SendGridIntegrationConfiguration.cs deleted file mode 100644 index fe585ff..0000000 --- a/src/Integrations/Warden.Integrations.SendGrid/SendGridIntegrationConfiguration.cs +++ /dev/null @@ -1,211 +0,0 @@ -using System; -using System.Linq; - -namespace Warden.Integrations.SendGrid -{ - /// - /// Configuration of the SendGridIntegration. - /// - public class SendGridIntegrationConfiguration - { - /// - /// API key of the SendGrid account. - /// - public string ApiKey { get; protected set; } - - /// - /// Sender email address. - /// - public string Sender { get; protected set; } - - /// - /// Default receiver(s) email address(es). - /// - public string[] DefaultReceivers { get; protected set; } - - /// - /// Default subject of the email message. - /// - public string DefaultSubject { get; protected set; } - - /// - /// Default body of the email message. - /// - public string DefaultMessage { get; protected set; } - - /// - /// Default template id of the transactional template. - /// - public string DefaultTemplateId { get; protected set; } - - /// - /// Default parameters of the transactional template. - /// - public EmailTemplateParameter[] DefaultTemplateParameters { get; protected set; } - - /// - /// Flag determining whether the message body should be of HTML type. - /// - public bool UseHtmlBody { get; protected set; } - - /// - /// Custom provider for the IEmailSender. - /// - public Func EmailSenderProvider { get; protected set; } - - /// - /// Factory method for creating a new instance of fluent builder for the SendGridIntegrationConfiguration. - /// - /// API key of the SendGrid account. - /// Email address of the message sender. - /// Instance of fluent builder for the SendGridIntegrationConfiguration. - public static Builder Create(string apiKey, string sender) => new Builder(apiKey, sender); - - protected SendGridIntegrationConfiguration(string apiKey, string sender) - { - if (string.IsNullOrWhiteSpace(apiKey)) - throw new ArgumentException("API key can not be empty.", nameof(apiKey)); - - ValidateAndSetDefaultParameters(sender); - ApiKey = apiKey; - } - - private void ValidateAndSetDefaultParameters(string sender) - { - if (string.IsNullOrWhiteSpace(sender)) - throw new ArgumentException("Email message sender can not be empty.", nameof(sender)); - if (!sender.IsEmail()) - throw new ArgumentException("Invalid email of the message sender.", nameof(sender)); - - Sender = sender; - EmailSenderProvider = () => new EmailSender(); - DefaultReceivers = Enumerable.Empty().ToArray(); - DefaultTemplateParameters = Enumerable.Empty().ToArray(); - } - - /// - /// Fluent builder for the SendGridIntegrationConfiguration. - /// - public class Builder - { - protected readonly SendGridIntegrationConfiguration Configuration; - - public Builder(string apiKey, string sender) - { - Configuration = new SendGridIntegrationConfiguration(apiKey, sender); - } - - /// - /// Sets the default subject of the email message. - /// - /// Default subject of the email message. - /// Instance of fluent builder for the SendGridIntegrationConfiguration. - public Builder WithDefaultSubject(string subject) - { - if (string.IsNullOrWhiteSpace(subject)) - throw new ArgumentException("Default subject can not be empty", nameof(subject)); - - Configuration.DefaultSubject = subject; - - return this; - } - - /// - /// Sets the default body of the email message. - /// - /// Default body of the email message. - /// Instance of fluent builder for the SendGridIntegrationConfiguration. - public Builder WithDefaultMessage(string message) - { - if (string.IsNullOrWhiteSpace(message)) - throw new ArgumentException("Default message can not be empty.", nameof(message)); - - Configuration.DefaultMessage = message; - - return this; - } - - /// - /// Sets the default receiver(s) email address(es). - /// - /// Default receiver(s) email address(es). - /// Instance of fluent builder for the SendGridIntegrationConfiguration. - public Builder WithDefaultReceivers(params string[] receivers) - { - if (receivers?.Any() == false) - throw new ArgumentException("Default receivers can not be empty.", nameof(receivers)); - - receivers.ValidateEmails(nameof(receivers)); - Configuration.DefaultReceivers = receivers; - - return this; - } - - /// - /// Sets the default template id of the transactional template. - /// - /// Default template id of the transactional template. - /// Instance of fluent builder for the SendGridIntegrationConfiguration. - public Builder WithDefaultTemplateId(string templateId) - { - if (string.IsNullOrWhiteSpace(templateId)) - throw new ArgumentException("Default template id can not be empty.", nameof(templateId)); - - Configuration.DefaultTemplateId = templateId; - - return this; - } - - /// - /// Sets the default parameters of the transactional template. - /// - /// Default parameters of the transactional template. - /// Instance of fluent builder for the SendGridIntegrationConfiguration. - public Builder WithDefaultTemplateParameters(params EmailTemplateParameter[] parameters) - { - if (parameters?.Any() == false) - throw new ArgumentException("Default template parameters can not be empty.", nameof(parameters)); - - Configuration.DefaultTemplateParameters = parameters; - - return this; - } - - /// - /// Sets the flag determining whether the message body should be of HTML type. - /// - /// Instance of fluent builder for the SendGridIntegrationConfiguration. - public Builder WithHtmlBody() - { - Configuration.UseHtmlBody = true; - - return this; - } - - /// - /// Sets the custom provider for the IEmailSender. - /// - /// Custom provider for the IEmailSender. - /// Lambda expression returning an instance of the IEmailSender. - /// Instance of fluent builder for the SendGridIntegrationConfiguration. - public Builder WithEmailSenderProvider(Func emailSenderProvider) - { - if (emailSenderProvider == null) - { - throw new ArgumentNullException(nameof(emailSenderProvider), - "Email sender provider can not be null."); - } - - Configuration.EmailSenderProvider = emailSenderProvider; - - return this; - } - - /// - /// Builds the SendGridIntegrationConfiguration and return its instance. - /// - /// Instance of SendGridIntegrationConfiguration. - public SendGridIntegrationConfiguration Build() => Configuration; - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.SendGrid/Warden.Integrations.SendGrid.csproj b/src/Integrations/Warden.Integrations.SendGrid/Warden.Integrations.SendGrid.csproj deleted file mode 100644 index 01d55e3..0000000 --- a/src/Integrations/Warden.Integrations.SendGrid/Warden.Integrations.SendGrid.csproj +++ /dev/null @@ -1,40 +0,0 @@ - - - - Warden integration with SendGrid. - 1.3.1 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Integrations.SendGrid - Warden.Integrations.SendGrid - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Integrations/Warden.Integrations.Slack/Extensions.cs b/src/Integrations/Warden.Integrations.Slack/Extensions.cs deleted file mode 100644 index f4c6a7e..0000000 --- a/src/Integrations/Warden.Integrations.Slack/Extensions.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using Warden.Core; - -namespace Warden.Integrations.Slack -{ - /// - /// Custom extension methods for the Slack integration. - /// - public static class Extensions - { - /// - /// Extension method for adding the Slack integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Full URL of the Slack webhook integration. - /// Optional lambda expression for configuring the SlackIntegration. - public static WardenConfiguration.Builder IntegrateWithSlack( - this WardenConfiguration.Builder builder, - string webhookUrl, - Action configurator = null) - { - builder.AddIntegration(SlackIntegration.Create(webhookUrl, configurator)); - - return builder; - } - - /// - /// Extension method for adding the Slack integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Configuration of SlackIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithSlack( - this WardenConfiguration.Builder builder, - SlackIntegrationConfiguration configuration) - { - builder.AddIntegration(SlackIntegration.Create(configuration)); - - return builder; - } - - /// - /// Extension method for resolving the Slack integration from the IIntegrator. - /// - /// Instance of the IIntegrator. - /// Instance of fluent builder for the WardenConfiguration. - public static SlackIntegration Slack(this IIntegrator integrator) - => integrator.Resolve(); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Slack/ISlackService.cs b/src/Integrations/Warden.Integrations.Slack/ISlackService.cs deleted file mode 100644 index 8511ef2..0000000 --- a/src/Integrations/Warden.Integrations.Slack/ISlackService.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace Warden.Integrations.Slack -{ - /// - /// Custom Slack client for integrating with the Webhook. - /// - public interface ISlackService - { - /// - /// Executes the HTTP POST request. - /// - /// Message text. - /// Optional name of channel to which the message will be sent. - /// Optional username that will send the message. - /// Optional icon url that will be used as Slack user icon. - /// Optional timeout for the request. - /// Optional flag determining whether an exception should be thrown if received reponse is invalid (false by default). - /// - Task SendMessageAsync(string message, string channel = null, string username = null, string iconUrl = null, - TimeSpan? timeout = null, bool failFast = false); - - /// - /// Executes the HTTP POST request. - /// - /// Message text. - /// Indicates if the message should display a positive or negative color - /// Optional name of channel to which the message will be sent. - /// Optional username that will send the message. - /// Optional icon url that will be used as Slack user icon. - /// Optional timeout for the request. - /// Optional flag determining whether an exception should be thrown if received reponse is invalid (false by default). - Task SendColoredMessageAsync(string message, bool valid, string channel = null, string username = null, string iconUrl = null, - TimeSpan? timeout = null, bool failFast = false); - } - - /// - /// Default implementation of the ISlackService based on the HttpClient. - /// - public class SlackService : ISlackService - { - private readonly Uri _webhookUrl; - private readonly HttpClient _httpClient = new HttpClient(); - - public SlackService(Uri webhookUrl) - { - _webhookUrl = webhookUrl; - } - - public async Task SendMessageAsync(string message, string channel = null, string username = null, string iconUrl = null, - TimeSpan? timeout = null, bool failFast = false) - { - SetTimeout(timeout); - try - { - var payload = new - { - icon_url = iconUrl, - text = message, - channel, - username, - }; - var serializedPayload = JsonConvert.SerializeObject(payload); - var response = await _httpClient.PostAsync(_webhookUrl, new StringContent( - serializedPayload, Encoding.UTF8, "application/json")); - - if (response.IsSuccessStatusCode) - return; - if (!failFast) - return; - - throw new IntegrationException("Received invalid HTTP response from Slack API " + - $"with status code: {response.StatusCode}. Reason phrase: {response.ReasonPhrase}"); - } - catch (Exception exception) - { - if (!failFast) - return; - - throw new IntegrationException("There was an error while executing the SendMessageAsync(): " + - $"{exception}", exception); - } - } - - public async Task SendColoredMessageAsync(string message, bool valid, string channel = null, string username = null, string iconUrl = null, - TimeSpan? timeout = null, bool failFast = false) - { - SetTimeout(timeout); - try - { - var attachment = new - { - fallback = message, - color = valid ? "good" : "danger", - fields = new [] { new { value = message } } - }; - var payload = new - { - icon_url = iconUrl, - channel, - username, - attachments = new[] {attachment} - }; - - var serializedPayload = JsonConvert.SerializeObject(payload); - var response = await _httpClient.PostAsync(_webhookUrl, new StringContent( - serializedPayload, Encoding.UTF8, "application/json")); - - if (response.IsSuccessStatusCode) - return; - if (!failFast) - return; - - throw new IntegrationException("Received invalid HTTP response from Slack API " + - $"with status code: {response.StatusCode}. Reason phrase: {response.ReasonPhrase}"); - } - catch (Exception exception) - { - if (!failFast) - return; - - throw new IntegrationException("There was an error while executing the SendMessageAsync(): " + - $"{exception}", exception); - } - } - - private void SetTimeout(TimeSpan? timeout) - { - if (timeout > TimeSpan.Zero) - _httpClient.Timeout = timeout.Value; - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Slack/Properties/AssemblyInfo.cs b/src/Integrations/Warden.Integrations.Slack/Properties/AssemblyInfo.cs deleted file mode 100644 index 912249b..0000000 --- a/src/Integrations/Warden.Integrations.Slack/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -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: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Integrations.Slack")] -[assembly: AssemblyTrademark("")] - -// 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("42f2e9a8-81bd-485a-b099-dd6a92df22e5")] diff --git a/src/Integrations/Warden.Integrations.Slack/SlackIntegration.cs b/src/Integrations/Warden.Integrations.Slack/SlackIntegration.cs deleted file mode 100644 index fa6c6e3..0000000 --- a/src/Integrations/Warden.Integrations.Slack/SlackIntegration.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Warden.Integrations.Slack -{ - /// - /// Integration with the Slack. - /// - public class SlackIntegration : IIntegration - { - private readonly SlackIntegrationConfiguration _configuration; - private readonly ISlackService _slackService; - - public SlackIntegration(SlackIntegrationConfiguration configuration) - { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Slack Integration configuration has not been provided."); - } - - _configuration = configuration; - _slackService = _configuration.SlackServiceProvider(); - } - - /// - /// Sends a default message to the default channel, using a default username. - /// - /// - public async Task SendMessageAsync() - { - await SendMessageAsync(_configuration.DefaultMessage, _configuration.DefaultChannel, _configuration.DefaultUsername); - } - - /// - /// Sends a message to the default channel, using a default username. - /// - /// Message text. If default message has been set, it will override its value. - /// - public async Task SendMessageAsync(string message) - { - await SendMessageAsync(message, _configuration.DefaultChannel, _configuration.DefaultUsername); - } - - /// - /// Sends a message to the selected channel, using a default username. - /// - /// Message text. If default message has been set, it will override its value. - /// Channel name. If default channel has been set, it will override its value. - /// - public async Task SendMessageAsync(string message, string channel) - { - await SendMessageAsync(message, channel, _configuration.DefaultUsername); - } - - /// - /// Sends a message to the selected channel, using a given username. - /// - /// Message text. If default message has been set, it will override its value. - /// Channel name. If default channel has been set, it will override its value. - /// Custom username. If default username has been set, it will override its value. - /// - public async Task SendMessageAsync(string message, string channel, string username) - { - await _slackService.SendMessageAsync(message, channel, username); - } - - /// - /// Sends a message to the selected channel, using a given username. - /// - /// Message text. If default message has been set, it will override its value. - /// Channel name. If default channel has been set, it will override its value. - /// Custom username. If default username has been set, it will override its value. - /// Icon url that will be used as Slack user icon. - /// - public async Task SendMessageAsync(string message, string channel, string username, string iconUrl) - { - await _slackService.SendMessageAsync(message, channel, username, iconUrl); - } - - - /// - /// Sends a message to the default channel, using a default username. - /// - /// Message text. If default message has been set, it will override its value. - /// Make the message have a good or bad identifier in Slack - /// - public async Task SendColoredMessageAsync(string message, bool isValid) - { - await SendColoredMessageAsync(message, isValid, _configuration.DefaultChannel, _configuration.DefaultUsername); - } - - /// - /// Sends a message to the selected channel, using a default username. - /// - /// Message text. If default message has been set, it will override its value. - /// Make the message have a good or bad identifier in Slack - /// Channel name. If default channel has been set, it will override its value. - /// - public async Task SendColoredMessageAsync(string message, bool isValid, string channel) - { - await SendColoredMessageAsync(message, isValid, channel, _configuration.DefaultUsername); - } - - /// - /// Sends a message to the selected channel, using a given username. - /// - /// Message text. If default message has been set, it will override its value. - /// Make the message have a good or bad identifier in Slack - /// Channel name. If default channel has been set, it will override its value. - /// Custom username. If default username has been set, it will override its value. - /// - public async Task SendColoredMessageAsync(string message, bool isValid, string channel, string username) - { - await _slackService.SendColoredMessageAsync(message, isValid, channel, username); - } - - /// - /// Sends a message to the selected channel, using a given username. - /// - /// Message text. If default message has been set, it will override its value. - /// Make the message have a good or bad identifier in Slack - /// Channel name. If default channel has been set, it will override its value. - /// Custom username. If default username has been set, it will override its value. - /// Icon url that will be used as Slack user icon. - /// - public async Task SendColoredMessageAsync(string message, bool isValid, string channel, string username, string iconUrl) - { - await _slackService.SendColoredMessageAsync(message, isValid, channel, username, iconUrl); - } - - /// - /// Factory method for creating a new instance of SlackIntegration. - /// - /// Full URL of the Slack webhook integration. - /// Lambda expression for configuring the SlackIntegration integration. - /// Instance of SlackIntegration. - public static SlackIntegration Create(string webhookUrl, - Action configurator = null) - { - var config = new SlackIntegrationConfiguration.Builder(webhookUrl); - configurator?.Invoke(config); - - return Create(config.Build()); - } - - /// - /// Factory method for creating a new instance of SlackIntegration. - /// - /// Configuration of Slack integration. - /// Instance of SlackIntegration. - public static SlackIntegration Create(SlackIntegrationConfiguration configuration) - => new SlackIntegration(configuration); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Slack/SlackIntegrationConfiguration.cs b/src/Integrations/Warden.Integrations.Slack/SlackIntegrationConfiguration.cs deleted file mode 100644 index c2f2b73..0000000 --- a/src/Integrations/Warden.Integrations.Slack/SlackIntegrationConfiguration.cs +++ /dev/null @@ -1,178 +0,0 @@ -using System; - -namespace Warden.Integrations.Slack -{ - /// - /// Configuration of the SlackIntegration. - /// - public class SlackIntegrationConfiguration - { - /// - /// Full URL of the Slack webhook integration. - /// - public Uri WebhookUrl { get; protected set; } - - /// - /// Default message text. - /// - public string DefaultMessage { get; protected set; } - - /// - /// Default name of channel to which the message will be sent. - /// - public string DefaultChannel { get; protected set; } - - /// - /// Default username that will send the message. - /// - public string DefaultUsername { get; protected set; } - - /// - /// Optional timeout of the HTTP request to the Slack API. - /// - public TimeSpan? Timeout { get; protected set; } - - /// - /// Flag determining whether an exception should be thrown if SendMessageAsync() returns invalid reponse (false by default). - /// - public bool FailFast { get; protected set; } - - /// - /// Custom provider for the ISlackService. - /// - public Func SlackServiceProvider { get; protected set; } - - /// - /// Factory method for creating a new instance of fluent builder for the SlackIntegrationConfiguration. - /// - /// Full URL of the Slack webhook integration. - /// Instance of fluent builder for the SlackIntegrationConfiguration. - public static Builder Create(string webhookUrl) => new Builder(webhookUrl); - - protected SlackIntegrationConfiguration(string webhookUrl) - { - if (string.IsNullOrWhiteSpace(webhookUrl)) - throw new ArgumentException("Webhook URL can not be empty.", nameof(webhookUrl)); - - WebhookUrl = new Uri(webhookUrl); - SlackServiceProvider = () => new SlackService(WebhookUrl); - } - - /// - /// Fluent builder for the SlackIntegrationConfiguration. - /// - public class Builder - { - protected readonly SlackIntegrationConfiguration Configuration; - - /// - /// Constructor of fluent builder for the SlackIntegrationConfiguration. - /// - /// Full URL of the Slack webhook integration. - /// Instance of fluent builder for the SlackIntegrationConfiguration. - public Builder(string webhookUrl) - { - Configuration = new SlackIntegrationConfiguration(webhookUrl); - } - - /// - /// Sets the default message text. - /// - /// Default message text. - /// Instance of fluent builder for the SlackIntegrationConfiguration. - public Builder WithDefaultMessage(string message) - { - if (string.IsNullOrWhiteSpace(message)) - throw new ArgumentException("Default message can not be empty.", nameof(message)); - - Configuration.DefaultMessage = message; - - return this; - } - - /// - /// Sets the default channel to which the message will be sent. - /// - /// Default name of channel to which the message will be sent. - /// Instance of fluent builder for the SlackIntegrationConfiguration. - public Builder WithDefaultChannel(string channel) - { - if (string.IsNullOrWhiteSpace(channel)) - throw new ArgumentException("Default channel can not be empty.", nameof(channel)); - - Configuration.DefaultChannel = channel; - - return this; - } - - /// - /// Sets the default username that will send the message. - /// - /// Default username that will send the message. - /// Instance of fluent builder for the SlackIntegrationConfiguration. - public Builder WithDefaultUsername(string username) - { - if (string.IsNullOrWhiteSpace(username)) - throw new ArgumentException("Default username can not be empty.", nameof(username)); - - Configuration.DefaultUsername = username; - - return this; - } - - /// - /// Timeout of the HTTP request to the Slack API. - /// - /// Timeout. - /// Instance of fluent builder for the SlackIntegrationConfiguration. - public Builder WithTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); - - Configuration.Timeout = timeout; - - return this; - } - - /// - /// Flag determining whether an exception should be thrown if SendMessageAsync() returns invalid reponse (false by default). - /// - /// Instance of fluent builder for the SlackIntegrationConfiguration. - public Builder FailFast() - { - Configuration.FailFast = true; - - return this; - } - - /// - /// Sets the custom provider for the ISlackService. - /// - /// Custom provider for the ISlackService. - /// Lambda expression returning an instance of the ISlackService. - /// Instance of fluent builder for the SlackIntegrationConfiguration. - public Builder WithSlackServiceProvider(Func slackServiceProvider) - { - if (slackServiceProvider == null) - { - throw new ArgumentNullException(nameof(slackServiceProvider), - "Slack service provider can not be null."); - } - - Configuration.SlackServiceProvider = slackServiceProvider; - - return this; - } - - /// - /// Builds the SlackIntegrationConfiguration and return its instance. - /// - /// Instance of SlackIntegrationConfiguration. - public SlackIntegrationConfiguration Build() => Configuration; - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Slack/Warden.Integrations.Slack.csproj b/src/Integrations/Warden.Integrations.Slack/Warden.Integrations.Slack.csproj deleted file mode 100644 index c4d4825..0000000 --- a/src/Integrations/Warden.Integrations.Slack/Warden.Integrations.Slack.csproj +++ /dev/null @@ -1,45 +0,0 @@ - - - - Warden integration with Slack. - 1.3.1 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Integrations.Slack - Warden.Integrations.Slack - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Integrations/Warden.Integrations.Smtp/Extensions.cs b/src/Integrations/Warden.Integrations.Smtp/Extensions.cs deleted file mode 100644 index 7424381..0000000 --- a/src/Integrations/Warden.Integrations.Smtp/Extensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using Warden.Core; -using Warden.Integrations; - -namespace Warden.Integrations.Smtp -{ - - public static class Extensions - { - - public static WardenConfiguration.Builder IntegrateWithSmtp( - this WardenConfiguration.Builder builder, - string host, - int port, - bool enableSsl, - Action configurator = null) - { - builder.AddIntegration(SmtpIntegration.Create(host, port, enableSsl, configurator)); - - return builder; - } - - - public static WardenConfiguration.Builder IntegrateWithSmtp( - this WardenConfiguration.Builder builder, - SmtpIntegrationConfiguration configuration) - { - builder.AddIntegration(SmtpIntegration.Create(configuration)); - - return builder; - } - - public static SmtpIntegration Smtp(this IIntegrator integrator) - => integrator.Resolve(); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Smtp/ISmtpService.cs b/src/Integrations/Warden.Integrations.Smtp/ISmtpService.cs deleted file mode 100644 index 5558233..0000000 --- a/src/Integrations/Warden.Integrations.Smtp/ISmtpService.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using System.Threading.Tasks; -using System.Collections.Generic; -using System.Linq; -using MailKit.Net.Smtp; -using MimeKit; -using MailKit.Security; - - -namespace Warden.Integrations.Smtp -{ - public interface ISmtpService - { - Task SendEmailAsync( - string to, - string from, - string subject, - string body, - IEnumerable cc = null, - bool isBodyHtml = false, - - string username = null, - string password = null, - TimeSpan? timeout = null); - } - - - public class SmtpService : ISmtpService - { - private readonly string _host; - private readonly int _port; - private readonly bool _enableSsl; - - public SmtpService(string host, int port, bool enableSsl) - { - _host = host; - _port = port; - _enableSsl = enableSsl; - } - - public async Task SendEmailAsync( - string to, - string from, - string subject, - string body, - IEnumerable cc = null, - bool isBodyHtml = false, - - string username = null, - string password = null, - TimeSpan? timeout = null) - { - try - { - using (var _client = new SmtpClient()) - { - await _client.ConnectAsync(_host - , _port - , _enableSsl ? SecureSocketOptions.StartTlsWhenAvailable : SecureSocketOptions.None); - - _client.AuthenticationMechanisms.Remove("XOAUTH2"); - - - if (!string.IsNullOrWhiteSpace(username) && - !string.IsNullOrWhiteSpace(password)) - { - await _client.AuthenticateAsync(username, password); - } - - if (timeout.HasValue) - { - _client.Timeout = (int)timeout.Value.TotalMilliseconds; - } - - var message = PrepareMessage(from, to, subject, body, cc, isBodyHtml); - - await _client.SendAsync(message); - - await _client.DisconnectAsync(true); - } - } - catch (Exception exception) - { - throw new IntegrationException("There was an error while executing the SendEmailAsync(): " + - $"{exception}", exception); - } - } - - private MimeMessage PrepareMessage(string from, string to, string subject, string body, - IEnumerable cc, bool isBodyHtml) - { - var message = new MimeMessage(); - - message.From.Add(new MailboxAddress(from)); - - message.To.Add(new MailboxAddress(to)); - - message.Subject = subject; - - message.Body = new TextPart(isBodyHtml ? "html" : "plain") - { - Text = body - }; - - if (cc != null && cc.Any()) - { - foreach (var address in cc) - { - message.Cc.Add(new MailboxAddress(address)); - } - } - - return message; - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Smtp/Properties/AssemblyInfo.cs b/src/Integrations/Warden.Integrations.Smtp/Properties/AssemblyInfo.cs deleted file mode 100644 index e4b1d6b..0000000 --- a/src/Integrations/Warden.Integrations.Smtp/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -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: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Integrations.Smtp")] -[assembly: AssemblyTrademark("")] - -// 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("b300174e-d096-4ef4-81cd-ad7448a6a642")] diff --git a/src/Integrations/Warden.Integrations.Smtp/SmtpIntegration.cs b/src/Integrations/Warden.Integrations.Smtp/SmtpIntegration.cs deleted file mode 100644 index afd5fb1..0000000 --- a/src/Integrations/Warden.Integrations.Smtp/SmtpIntegration.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace Warden.Integrations.Smtp -{ - public class SmtpIntegration : IIntegration - { - private readonly SmtpIntegrationConfiguration _configuration; - private readonly ISmtpService _smtpService; - - public SmtpIntegration(SmtpIntegrationConfiguration configuration) - { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Smtp Integration configuration has not been provided."); - } - - _configuration = configuration; - _smtpService = _configuration.SmtpServiceProvider(); - } - - public async Task SendEmailAsync(string body) - { - await _smtpService.SendEmailAsync( - _configuration.DefaultToAddress, - _configuration.DefaultFromAddress, - _configuration.DefaultSubject, - body, - _configuration.DefaultCCAddresses, - _configuration.DefaultIsBodyHtml, - _configuration.Username, - _configuration.Password, - _configuration.Timeout); - } - - public async Task SendEmailAsync(string subject, string body) - { - await _smtpService.SendEmailAsync( - _configuration.DefaultToAddress, - _configuration.DefaultFromAddress, - subject, - body, - _configuration.DefaultCCAddresses, - _configuration.DefaultIsBodyHtml, - _configuration.Username, - _configuration.Password, - _configuration.Timeout); - } - - public async Task SendEmailAsync(string to, string from, string subject, string body) - { - await _smtpService.SendEmailAsync( - to, - from, - subject, - body, - _configuration.DefaultCCAddresses, - _configuration.DefaultIsBodyHtml, - _configuration.Username, - _configuration.Password, - _configuration.Timeout); - } - - public async Task SendEmailAsync(string to, string from, string subject, string body, - string username, string password) - { - await _smtpService.SendEmailAsync( - to, - from, - subject, - body, - _configuration.DefaultCCAddresses, - _configuration.DefaultIsBodyHtml, - username, - password, - _configuration.Timeout); - } - - public async Task SendEmailAsync( - string to, - string from, - string subject, - string body, - IEnumerable cc = null, - bool isBodyHtml = false, - string username = null, - string password = null, - TimeSpan? timeout = null) - { - await _smtpService.SendEmailAsync(to, from, subject, body, cc, isBodyHtml, - username, password, timeout); - } - - public static SmtpIntegration Create(string host, - int port, - bool enableSsl, - Action configurator = null) - { - var config = new SmtpIntegrationConfiguration.Builder(host, port, enableSsl); - configurator?.Invoke(config); - - return Create(config.Build()); - } - - public static SmtpIntegration Create(SmtpIntegrationConfiguration configuration) - => new SmtpIntegration(configuration); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Smtp/SmtpIntegrationConfiguration.cs b/src/Integrations/Warden.Integrations.Smtp/SmtpIntegrationConfiguration.cs deleted file mode 100644 index 9fc0a56..0000000 --- a/src/Integrations/Warden.Integrations.Smtp/SmtpIntegrationConfiguration.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Warden.Integrations.Smtp -{ - public class SmtpIntegrationConfiguration - { - //All Parameters - - public string Host { get; protected set; } - - public int Port { get; protected set; } - - public bool EnableSsl { get; protected set; } - - public string Username { get; protected set; } - - public string Password { get; protected set; } - - public TimeSpan? Timeout { get; protected set; } - - public string DefaultToAddress { get; protected set; } - - public string DefaultFromAddress { get; protected set; } - - public string DefaultSubject { get; protected set; } - - public string DefaultBody { get; protected set; } - - public bool DefaultIsBodyHtml { get; protected set; } - - public IEnumerable DefaultCCAddresses { get; protected set; } - - public Func SmtpServiceProvider { get; protected set; } - - public static Builder Create(string host, int port, bool enableSsl) => new Builder(host, port, enableSsl); - - protected SmtpIntegrationConfiguration(string host, int port, bool enableSsl) - { - Host = host; - Port = port; - EnableSsl = enableSsl; - - SmtpServiceProvider = () => new SmtpService(Host, Port, EnableSsl); - } - - public class Builder - { - protected readonly SmtpIntegrationConfiguration Configuration; - - public Builder(string host, int port, bool enableSsl) - { - Configuration = new SmtpIntegrationConfiguration(host, port, enableSsl); - } - - public Builder WithDefaultCredentials() - { - Configuration.Username = null; - Configuration.Password = null; - return this; - } - - public Builder WithCredentials(string username, string password) - { - if (string.IsNullOrWhiteSpace(username)) - throw new ArgumentException("Username can not be empty.", nameof(username)); - - if (string.IsNullOrWhiteSpace(password)) - throw new ArgumentException("Password can not be empty.", nameof(password)); - - Configuration.Username = username; - Configuration.Password = password; - return this; - } - - public Builder WithDefaultTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); - - Configuration.Timeout = timeout; - - return this; - } - - public Builder WithDefaultToAddress(string toAddress) - { - if (string.IsNullOrWhiteSpace(toAddress)) - throw new ArgumentException("To Address can not be empty.", nameof(toAddress)); - - Configuration.DefaultToAddress = toAddress; - - return this; - } - - public Builder WithDefaultFromAddress(string fromAddress) - { - if (string.IsNullOrWhiteSpace(fromAddress)) - throw new ArgumentException("From Address can not be empty.", nameof(fromAddress)); - - Configuration.DefaultFromAddress = fromAddress; - - return this; - } - - public Builder WithDefaultSubject(string subject) - { - if (string.IsNullOrWhiteSpace(subject)) - throw new ArgumentException("Subject can not be empty.", nameof(subject)); - - Configuration.DefaultSubject = subject; - - return this; - } - - public Builder WithDefaultBody(string body) - { - if (string.IsNullOrWhiteSpace(body)) - throw new ArgumentException("Body can not be empty.", nameof(body)); - - Configuration.DefaultBody = body; - - return this; - } - - public Builder WithDefaultIsBodyHtml(bool isBodyHtml) - { - Configuration.DefaultIsBodyHtml = isBodyHtml; - - return this; - } - - public Builder WithDefaultCCAddress(IEnumerable ccAddresses) - { - if (ccAddresses == null) - throw new ArgumentNullException(nameof(ccAddresses), "CC Addresses can not be null."); - - if (!ccAddresses.Any()) - throw new ArgumentException("CC Addresses must contain at least one address.", nameof(ccAddresses)); - - - List defaultAddresses = new List(); - - foreach (var address in ccAddresses) - { - if (!string.IsNullOrWhiteSpace(address)) - { - defaultAddresses.Add(address); - } - } - - if (!defaultAddresses.Any()) - throw new ArgumentException("CC Addresses can not be empty/blank.", nameof(ccAddresses)); - - Configuration.DefaultCCAddresses = defaultAddresses; - - return this; - } - - public Builder WithSmtpServiceProvider(Func smtpServiceProvider) - { - if (smtpServiceProvider == null) - { - throw new ArgumentNullException(nameof(smtpServiceProvider), - "Smtp service provider can not be null."); - } - - Configuration.SmtpServiceProvider = smtpServiceProvider; - - return this; - } - - public SmtpIntegrationConfiguration Build() => Configuration; - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Smtp/Warden.Integrations.Smtp.csproj b/src/Integrations/Warden.Integrations.Smtp/Warden.Integrations.Smtp.csproj deleted file mode 100644 index 3110f62..0000000 --- a/src/Integrations/Warden.Integrations.Smtp/Warden.Integrations.Smtp.csproj +++ /dev/null @@ -1,47 +0,0 @@ - - - - Warden integration with MS SQL. - 1.3.1 - Piotr Gankiewicz, Eoin Campbell - net461;netstandard1.6 - Warden.Integrations.Smtp - Warden.Integrations.Smtp - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Integrations/Warden.Integrations.Twilio/Extensions.cs b/src/Integrations/Warden.Integrations.Twilio/Extensions.cs deleted file mode 100644 index df6f135..0000000 --- a/src/Integrations/Warden.Integrations.Twilio/Extensions.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using Warden.Core; - -namespace Warden.Integrations.Twilio -{ - public static class Extensions - { - /// - /// Extension method for adding the Twilio integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// SID of the Twilio account. - /// Authentication token of the Twilio account. - /// Phone number of the SMS sender. - /// Optional lambda expression for configuring the TwilioIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithTwilio( - this WardenConfiguration.Builder builder, - string accountSid, string authToken, string sender, - Action configurator = null) - { - builder.AddIntegration(TwilioIntegration.Create(accountSid, authToken, sender, configurator)); - - return builder; - } - - /// - /// Extension method for adding the Twilio integration to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Configuration of TwilioIntegration. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder IntegrateWithTwilio( - this WardenConfiguration.Builder builder, - TwilioIntegrationConfiguration configuration) - { - builder.AddIntegration(TwilioIntegration.Create(configuration)); - - return builder; - } - - /// - /// Extension method for resolving the Twilio integration from the IIntegrator. - /// - /// Instance of the IIntegrator. - /// Instance of fluent builder for the WardenConfiguration. - public static TwilioIntegration Twilio(this IIntegrator integrator) - => integrator.Resolve(); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Twilio/ITwilioService.cs b/src/Integrations/Warden.Integrations.Twilio/ITwilioService.cs deleted file mode 100644 index db29ac9..0000000 --- a/src/Integrations/Warden.Integrations.Twilio/ITwilioService.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Threading.Tasks; -using Twilio; - -namespace Warden.Integrations.Twilio -{ - /// - /// Custom Twilio SMS service. - /// - public interface ITwilioService - { - /// - /// Sends SMS. - /// - /// Sender phone number. - /// Receiver phone number. - /// Body of the SMS. - /// - Task SendSmsAsync(string sender, string receiver, string message); - } - - - /// - /// Default implementation of the ITwilioService based on Twilio library. - /// - public class TwilioService : ITwilioService - { - private readonly TwilioRestClient _twilioRestClient; - - public TwilioService(string accountSid, string authToken) - { - _twilioRestClient = new TwilioRestClient(accountSid, authToken); - } - - public async Task SendSmsAsync(string sender, string receiver, string message) - { - await Task.FromResult(_twilioRestClient.SendMessage(sender, receiver, message)); - } - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Twilio/Properties/AssemblyInfo.cs b/src/Integrations/Warden.Integrations.Twilio/Properties/AssemblyInfo.cs deleted file mode 100644 index 616d773..0000000 --- a/src/Integrations/Warden.Integrations.Twilio/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Integrations.Twilio")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Integrations.Twilio")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("75173643-6fa8-4dca-b1bf-3360cc58ac35")] diff --git a/src/Integrations/Warden.Integrations.Twilio/TwilioIntegration.cs b/src/Integrations/Warden.Integrations.Twilio/TwilioIntegration.cs deleted file mode 100644 index 6c30b03..0000000 --- a/src/Integrations/Warden.Integrations.Twilio/TwilioIntegration.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; - -namespace Warden.Integrations.Twilio -{ - /// - /// Integration with the Twilio - SMS service. - /// - public class TwilioIntegration : IIntegration - { - private readonly TwilioIntegrationConfiguration _configuration; - - public TwilioIntegration(TwilioIntegrationConfiguration configuration) - { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Twilio Integration configuration has not been provided."); - } - - _configuration = configuration; - } - - /// - /// Sends SMS to the default receiver(s) number(s), using a default message body. - /// - /// - public async Task SendSmsAsync() - { - await SendSmsAsync(null); - } - - /// - /// Sends SMS to the default receiver(s) number(s). - /// - /// Body of the SMS. If default message has been set, it will override its value. - /// - public async Task SendSmsAsync(string message) - { - await SendSmsAsync(message, null); - } - - /// - /// Sends SMS. - /// - /// Body of the SMS. If default message has been set, it will override its value. - /// Receiver(s) phone number(s) of the SMS. If default receivers have been set, it will merge these 2 lists. - /// - public async Task SendSmsAsync(string message, params string[] receivers) - { - var smsBody = string.IsNullOrWhiteSpace(message) ? _configuration.DefaultMessage : message; - if (string.IsNullOrWhiteSpace(smsBody)) - throw new ArgumentException("SMS body has not been defined.", nameof(smsBody)); - - var customReceivers = receivers?.Where(x => !string.IsNullOrWhiteSpace(x)) ?? Enumerable.Empty(); - var smsReceivers = (_configuration.DefaultReceivers.Any() - ? _configuration.DefaultReceivers.Union(customReceivers) - : customReceivers).ToList(); - if (!smsReceivers.Any()) - throw new ArgumentException("SMS receiver(s) have not been defined.", nameof(smsReceivers)); - - var twilioService = _configuration.TwilioServiceProvider(); - var sendSmsTasks = smsReceivers.Select(receiver => - twilioService.SendSmsAsync(_configuration.Sender, receiver, smsBody)); - await Task.WhenAll(sendSmsTasks); - } - - /// - /// Factory method for creating a new instance of TwilioIntegration. - /// - /// SID of the Twilio account. - /// Authentication token of the Twilio account. - /// Phone number of the SMS sender. - /// Lambda expression for configuring Twilio integration. - /// Instance of TwilioIntegration. - public static TwilioIntegration Create(string accountSid, string authToken, string sender, - Action configurator) - { - var config = new TwilioIntegrationConfiguration.Builder(accountSid, authToken, sender); - configurator?.Invoke(config); - - return Create(config.Build()); - } - - /// - /// Factory method for creating a new instance of TwilioIntegration. - /// - /// Configuration of Twilio integration. - /// Instance of TwilioIntegration. - public static TwilioIntegration Create(TwilioIntegrationConfiguration configuration) - => new TwilioIntegration(configuration); - } -} \ No newline at end of file diff --git a/src/Integrations/Warden.Integrations.Twilio/TwilioIntegrationConfiguration.cs b/src/Integrations/Warden.Integrations.Twilio/TwilioIntegrationConfiguration.cs deleted file mode 100644 index cf8f0bf..0000000 --- a/src/Integrations/Warden.Integrations.Twilio/TwilioIntegrationConfiguration.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using System.Linq; - -namespace Warden.Integrations.Twilio -{ - /// - /// Configuration of the TwilioIntegration. - /// - public class TwilioIntegrationConfiguration - { - /// - /// SID of the Twilio account. - /// - public string AccountSid { get; protected set; } - - /// - /// Authentication token of the Twilio account. - /// - public string AuthToken { get; protected set; } - - /// - /// Phone number of the SMS sender. - /// - public string Sender { get; protected set; } - - /// - /// Default receiver(s) number(s) of the SMS. - /// - public string[] DefaultReceivers { get; protected set; } - - /// - /// Default body of the SMS. - /// - public string DefaultMessage { get; protected set; } - - /// - /// Custom provider for the ITwilioService. - /// - public Func TwilioServiceProvider { get; protected set; } - - /// - /// Factory method for creating a new instance of fluent builder for the TwilioIntegrationConfiguration. - /// - /// SID of the Twilio account. - /// Authentication token of the Twilio account. - /// Phone number of the SMS sender. - /// Instance of fluent builder for the TwilioIntegrationConfiguration. - public static Builder Create(string accountSid, string authToken, string sender) => new Builder(accountSid, authToken, sender); - - protected TwilioIntegrationConfiguration(string accountSid, string authToken, string sender) - { - if (string.IsNullOrWhiteSpace(accountSid)) - throw new ArgumentException("Account SID can not be empty.", nameof(accountSid)); - if (string.IsNullOrWhiteSpace(authToken)) - throw new ArgumentException("Authentication token can not be empty.", nameof(authToken)); - if (string.IsNullOrWhiteSpace(sender)) - throw new ArgumentException("SMS sender can not be empty.", nameof(sender)); - - AccountSid = accountSid; - AuthToken = authToken; - Sender = sender; - DefaultReceivers = Enumerable.Empty().ToArray(); - } - - /// - /// Fluent builder for the TwilioIntegrationConfiguration. - /// - public class Builder - { - protected readonly TwilioIntegrationConfiguration Configuration; - - /// - /// Constructor of fluent builder for the TwilioIntegrationConfiguration. - /// - /// SID of the Twilio account. - /// Authentication token of the Twilio account. - /// Phone number of the SMS sender. - /// Instance of fluent builder for the TwilioIntegrationConfiguration. - public Builder(string accountSid, string authToken, string sender) - { - Configuration = new TwilioIntegrationConfiguration(accountSid, authToken, sender); - } - - /// - /// Sets the default body of the SMS. - /// - /// Default body of the SMS. - /// Instance of fluent builder for the TwilioIntegrationConfiguration. - public Builder WithDefaultMessage(string message) - { - if (string.IsNullOrWhiteSpace(message)) - throw new ArgumentException("Default message can not be empty.", nameof(message)); - - Configuration.DefaultMessage = message; - - return this; - } - - /// - /// Sets the default receiver(s) number(s). - /// - /// Default receiver(s) number(s). - /// Instance of fluent builder for the TwilioIntegrationConfiguration. - public Builder WithDefaultReceivers(params string[] receivers) - { - if (receivers == null || !receivers.Any()) - throw new ArgumentException("Default receivers can not be empty.", nameof(receivers)); - if (receivers.Any(string.IsNullOrWhiteSpace)) - throw new ArgumentException("Receiver(s) can not have empty number(s).", nameof(receivers)); - - Configuration.DefaultReceivers = receivers; - - return this; - } - - /// - /// Sets the custom provider for the ITwilioService. - /// - /// Custom provider for the ITwilioService. - /// Lambda expression returning an instance of the ITwilioService. - /// Instance of fluent builder for the TwilioIntegrationConfiguration. - public Builder WithTwilioServiceProvider(Func twilioServiceProvider) - { - if (twilioServiceProvider == null) - { - throw new ArgumentNullException(nameof(twilioServiceProvider), - "Twilio service provider can not be null."); - } - - Configuration.TwilioServiceProvider = twilioServiceProvider; - - return this; - } - - /// - /// Builds the TwilioIntegrationConfiguration and return its instance. - /// - /// Instance of TwilioIntegrationConfiguration. - public TwilioIntegrationConfiguration Build() => Configuration; - } - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests.EndToEnd/Properties/AssemblyInfo.cs b/src/Tests/Warden.Tests.EndToEnd/Properties/AssemblyInfo.cs deleted file mode 100644 index 48db48b..0000000 --- a/src/Tests/Warden.Tests.EndToEnd/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Tests.EndToEnd")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Tests.EndToEnd")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("273f698a-09d5-4a4c-b7cd-d7a9509aa53e")] diff --git a/src/Tests/Warden.Tests.EndToEnd/Warden.Tests.EndToEnd.csproj b/src/Tests/Warden.Tests.EndToEnd/Warden.Tests.EndToEnd.csproj deleted file mode 100644 index 19289ec..0000000 --- a/src/Tests/Warden.Tests.EndToEnd/Warden.Tests.EndToEnd.csproj +++ /dev/null @@ -1,56 +0,0 @@ - - - - Warden End-to-End tests. - 1.3.1 - Piotr Gankiewicz - net461 - Warden.Tests.EndToEnd - Warden.Tests.EndToEnd - true - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Tests/Warden.Tests.EndToEnd/Watchers/Web/WebWatcherTests.cs b/src/Tests/Warden.Tests.EndToEnd/Watchers/Web/WebWatcherTests.cs deleted file mode 100644 index fa937d1..0000000 --- a/src/Tests/Warden.Tests.EndToEnd/Watchers/Web/WebWatcherTests.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using Warden.Core; -using Warden.Watchers; -using Warden.Watchers.Web; -using FluentAssertions; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.EndToEnd.Watchers.Web -{ - public class WebWatcherSpecs - { - protected static WebWatcher Watcher { get; set; } - protected static WebWatcherConfiguration Configuration { get; set; } - protected static IWatcherCheckResult CheckResult { get; set; } - protected static WebWatcherCheckResult WebCheckResult { get; set; } - protected static Exception Exception { get; set; } - } - - [Subject("Web watcher execution")] - public class when_trying_to_access_invalid_url : WebWatcherSpecs - { - Establish context = () => - { - Configuration = WebWatcherConfiguration. - Create("http://www.testwebsitethatdoesnotexist.com") - .Build(); - Watcher = WebWatcher.Create("Invalid web watcher", Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Watcher.ExecuteAsync().Await()); - - It should_fail = () => Exception.Should().BeOfType(); - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("There was an error while trying to access the Web endpoint"); - } - - [Subject("Web watcher execution")] - public class when_website_returns_invalid_status_code : WebWatcherSpecs - { - Establish context = () => - { - Configuration = WebWatcherConfiguration - .Create("http://httpstat.us/400") - .Build(); - Watcher = WebWatcher.Create("Valid web watcher", Configuration); - }; - - Because of = async () => CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - } - - [Subject("Web watcher execution")] - public class when_website_returns_valid_status_code : WebWatcherSpecs - { - Establish context = () => - { - Configuration = WebWatcherConfiguration - .Create("http://httpstat.us/200") - .Build(); - Watcher = WebWatcher.Create("Valid web watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - WebCheckResult = CheckResult as WebWatcherCheckResult; - }; - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_web = () => CheckResult.Should().BeAssignableTo(); - It should_have_check_result_with_valid_uri = () => WebCheckResult.Uri.Should().NotBeNull(); - It should_have_check_result_with_request_headers = () => WebCheckResult.Response.Headers.Should().NotBeNull(); - It should_have_check_result_with_response = () => WebCheckResult.Response.Should().NotBeNull(); - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Integrations/Cachet/CachetIntegration_specs.cs b/src/Tests/Warden.Tests/Integrations/Cachet/CachetIntegration_specs.cs deleted file mode 100644 index f8d9483..0000000 --- a/src/Tests/Warden.Tests/Integrations/Cachet/CachetIntegration_specs.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -using System.Collections.Generic; -using FluentAssertions; -using Moq; -using Warden.Integrations.Cachet; -using Warden.Watchers; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Integrations.Cachet -{ - public class CachetIntegration_specs - { - protected static CachetIntegration Integration { get; set; } - protected static CachetIntegrationConfiguration Configuration { get; set; } - protected static Exception Exception { get; set; } - protected static string ApiUrl = "http://localhost/api/v1"; - protected static string AccessToken = "token"; - protected static string Username = "user"; - protected static string Password = "password"; - } - - [Subject("Cachet integration initialization")] - public class when_initializing_without_configuration : CachetIntegration_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception(() => Integration = CachetIntegration.Create(Configuration)); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("Cachet Integration configuration has not been provided."); - } - - [Subject("Cachet integration initialization")] - public class when_initializing_with_invalid_api_url_and_access_token : CachetIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = CachetIntegrationConfiguration - .Create(string.Empty, string.Empty) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("API URL can not be empty."); - } - - [Subject("Cachet integration initialization")] - public class when_initializing_with_invalid_api_url_and_username_and_password : CachetIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = CachetIntegrationConfiguration - .Create(string.Empty, string.Empty, string.Empty) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("API URL can not be empty."); - } - - - [Subject("Cachet integration initialization")] - public class when_initializing_with_valid_api_url_and_invalid_access_token : CachetIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = CachetIntegrationConfiguration - .Create(ApiUrl, string.Empty) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Access token can not be empty."); - } - - [Subject("Cachet integration initialization")] - public class when_initializing_with_valid_api_url_and_invalid_username : CachetIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = CachetIntegrationConfiguration - .Create(ApiUrl, string.Empty, Password) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Username can not be empty."); - } - - [Subject("Cachet integration initialization")] - public class when_initializing_with_valid_api_url_and_invalid_password : CachetIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = CachetIntegrationConfiguration - .Create(ApiUrl, Username, string.Empty) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Password can not be empty."); - } - - [Subject("Cachet integration initialization")] - public class when_initializing_with_valid_api_url_and_access_token : CachetIntegration_specs - { - Establish context = () => Configuration = CachetIntegrationConfiguration - .Create(ApiUrl, AccessToken) - .Build(); - - Because of = () => Integration = CachetIntegration.Create(Configuration); - - It should_initialize_cachet_integration = () => Integration.Should().NotBeNull(); - } - - [Subject("Cachet integration initialization")] - public class when_initializing_with_valid_api_url_and_username_and_password : CachetIntegration_specs - { - Establish context = () => Configuration = CachetIntegrationConfiguration - .Create(ApiUrl, Username, Password) - .Build(); - - Because of = () => Integration = CachetIntegration.Create(Configuration); - - It should_initialize_cachet_integration = () => Integration.Should().NotBeNull(); - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Integrations/HttpApi/HttpApiIntegration_specs.cs b/src/Tests/Warden.Tests/Integrations/HttpApi/HttpApiIntegration_specs.cs deleted file mode 100644 index 6a1fe7a..0000000 --- a/src/Tests/Warden.Tests/Integrations/HttpApi/HttpApiIntegration_specs.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System; -using System.Collections.Generic; -using FluentAssertions; -using Moq; -using Warden.Core; -using Warden.Integrations.HttpApi; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Integrations.HttpApi -{ - public class HttpApiIntegration_specs - { - protected static HttpApiIntegration Integration { get; set; } - protected static HttpApiIntegrationConfiguration Configuration { get; set; } - protected static Exception Exception { get; set; } - protected static string ApiUrl = "http://my-api.com"; - protected static string Endpoint = "/endpoint"; - protected static string ApiKey = "api-key"; - protected static string OrganizationId = Guid.NewGuid().ToString(); - } - - [Subject("HttpApi integration initialization")] - public class when_initializing_without_configuration : HttpApiIntegration_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception(() => Integration = HttpApiIntegration.Create(Configuration)); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("HTTP API Integration configuration has not been provided."); - } - - [Subject("HttpApi integration initialization")] - public class when_initializing_with_invalid_url : HttpApiIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = HttpApiIntegrationConfiguration - .Create("Invalid") - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("HttpApi integration execution")] - public class when_invoking_post_async_method_with_valid_configuration : HttpApiIntegration_specs - { - static Mock HttpServiceMock; - - Establish context = () => - { - HttpServiceMock = new Mock(); - Configuration = HttpApiIntegrationConfiguration - .Create(ApiUrl) - .WithHttpServiceProvider(() => HttpServiceMock.Object) - .Build(); - Integration = HttpApiIntegration.Create(Configuration); - }; - - Because of = async () => await Integration.PostAsync(new {}).Await().AsTask; - - It should_invoke_post_async_method_only_once = () => HttpServiceMock.Verify(x => - x.PostAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny>(), - Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - } - - [Subject("HttpApi integration execution")] - public class when_invoking_post_iteration_to_warden_panel_async_method_with_null_iteration : - HttpApiIntegration_specs - { - static Mock HttpServiceMock; - - Establish context = () => - { - HttpServiceMock = new Mock(); - Configuration = HttpApiIntegrationConfiguration - .Create(ApiUrl) - .WithHttpServiceProvider(() => HttpServiceMock.Object) - .Build(); - Integration = HttpApiIntegration.Create(Configuration); - }; - - Because of = () => Exception = - Catch.Exception(() => Integration.PostIterationToWardenPanelAsync(null).Await().AsTask); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Warden iteration can not be null."); - } - - [Subject("HttpApi integration execution")] - public class when_invoking_post_iteration_to_warden_panel_async_method_with_empty_warden_name : - HttpApiIntegration_specs - { - static Mock HttpServiceMock; - static Mock WardenIterationMock; - - Establish context = () => - { - WardenIterationMock = new Mock(); - HttpServiceMock = new Mock(); - Configuration = HttpApiIntegrationConfiguration - .Create(ApiUrl) - .WithHttpServiceProvider(() => HttpServiceMock.Object) - .Build(); - Integration = HttpApiIntegration.Create(Configuration); - }; - - Because of = () => Exception = - Catch.Exception(() => Integration.PostIterationToWardenPanelAsync(WardenIterationMock.Object).Await().AsTask); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Warden name can not be empty."); - } - - [Subject("HttpApi integration execution")] - public class when_invoking_post_iteration_to_warden_panel_async_method_with_valid_iteration : - HttpApiIntegration_specs - { - static Mock WardenIterationMock; - static Mock HttpServiceMock; - - Establish context = () => - { - WardenIterationMock = new Mock(); - WardenIterationMock.Setup(x => x.WardenName).Returns("Warden"); - HttpServiceMock = new Mock(); - Configuration = HttpApiIntegrationConfiguration - .Create(ApiUrl) - .WithHttpServiceProvider(() => HttpServiceMock.Object) - .Build(); - Integration = HttpApiIntegration.Create(Configuration); - }; - - Because of = async () => - { - await Integration.PostIterationToWardenPanelAsync(WardenIterationMock.Object).Await().AsTask; - }; - - It should_invoke_post_async_method_only_once = () => HttpServiceMock.Verify(x => - x.PostAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny>(), - Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Integrations/MsSql/MsSqlIntegration_specs.cs b/src/Tests/Warden.Tests/Integrations/MsSql/MsSqlIntegration_specs.cs deleted file mode 100644 index a8c7981..0000000 --- a/src/Tests/Warden.Tests/Integrations/MsSql/MsSqlIntegration_specs.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Threading.Tasks; -using FluentAssertions; -using Moq; -using Warden.Integrations; -using Warden.Integrations.MsSql; -using Warden.Watchers; -using Warden.Watchers.MsSql; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Integrations.MsSql -{ - public class MsSqlIntegration_specs - { - protected static MsSqlIntegration Integration { get; set; } - protected static MsSqlIntegrationConfiguration Configuration { get; set; } - protected static Exception Exception { get; set; } - - protected static string ConnectionString = - @"Data Source=.\sqlexpress;Initial Catalog=MyDatabase;Integrated Security=True"; - } - - [Subject("MS SQL integration initialization")] - public class when_initializing_without_configuration : MsSqlIntegration_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception((Action) (() => Integration = MsSqlIntegration.Create(Configuration))); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("MS SQL integration configuration has not been provided."); - } - - [Subject("MS SQL integration initialization")] - public class when_initializing_with_invalid_connection_string : MsSqlIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = MsSqlIntegrationConfiguration - .Create("invalid") - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("MS SQL connection string is invalid."); - } - - [Subject("MS SQL integration execution")] - public class when_invoking_open_connection_that_fails : MsSqlIntegration_specs - { - static Mock MsSqlServiceMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlServiceMock = new Mock(); - DbConnectionMock = new Mock(); - DbConnectionMock.Setup(x => x.Open()).Throws(new Exception("Error")); - Configuration = MsSqlIntegrationConfiguration - .Create(ConnectionString) - .WithQuery("select * from users") - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlServiceProvider(() => MsSqlServiceMock.Object) - .Build(); - Integration = MsSqlIntegration.Create(Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Integration.ExecuteAsync(Moq.It.IsAny()).Await()); - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("MS SQL integration execution")] - public class when_invoking_query_async_that_fails : MsSqlIntegration_specs - { - static Mock MsSqlServiceMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlServiceMock = new Mock(); - DbConnectionMock = new Mock(); - MsSqlServiceMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny())) - .ThrowsAsync(new Exception("Error")); - Configuration = MsSqlIntegrationConfiguration - .Create(ConnectionString) - .WithQuery("select * from users") - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlServiceProvider(() => MsSqlServiceMock.Object) - .Build(); - Integration = MsSqlIntegration.Create(Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Integration.QueryAsync(Moq.It.IsAny()).Await()); - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("MS SQL integration execution")] - public class when_invoking_execute_async_that_fails : MsSqlIntegration_specs - { - static Mock MsSqlServiceMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlServiceMock = new Mock(); - DbConnectionMock = new Mock(); - MsSqlServiceMock.Setup(x => x.ExecuteAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny())) - .ThrowsAsync(new Exception("Error")); - Configuration = MsSqlIntegrationConfiguration - .Create(ConnectionString) - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlServiceProvider(() => MsSqlServiceMock.Object) - .Build(); - Integration = MsSqlIntegration.Create(Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Integration.ExecuteAsync(Moq.It.IsAny()).Await()); - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - It should_fail = () => Exception.Should().BeOfType(); - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Integrations/SendGrid/SendGridIntegration_specs.cs b/src/Tests/Warden.Tests/Integrations/SendGrid/SendGridIntegration_specs.cs deleted file mode 100644 index 57d5af2..0000000 --- a/src/Tests/Warden.Tests/Integrations/SendGrid/SendGridIntegration_specs.cs +++ /dev/null @@ -1,183 +0,0 @@ -using System; -using FluentAssertions; -using Moq; -using Warden.Integrations.SendGrid; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Integrations.SendGrid -{ - public class SendGridIntegration_specs - { - protected static SendGridIntegration Integration { get; set; } - protected static SendGridIntegrationConfiguration Configuration { get; set; } - protected static Exception Exception { get; set; } - protected static string Sender = "noreply@email.com"; - protected static string ApiKey = "api-key"; - protected static string[] Receivers = { "test1@email.com", "test2@email.com" }; - } - - [Subject("SendGrid integration initialization")] - public class when_initializing_without_configuration : SendGridIntegration_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception(() => Integration = SendGridIntegration.Create(Configuration)); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("SendGrid Integration configuration has not been provided."); - } - - [Subject("SendGrid integration initialization")] - public class when_initializing_with_empty_api_key : SendGridIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = SendGridIntegrationConfiguration - .Create(string.Empty, Sender) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("API key can not be empty."); - } - - [Subject("SendGrid integration initialization")] - public class when_initializing_with_invalid_sender : SendGridIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = SendGridIntegrationConfiguration - .Create(ApiKey, "invalid") - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("Invalid email of the message sender."); - } - - [Subject("SendGrid integration initialization")] - public class when_initializing_with_invalid_receiver : SendGridIntegration_specs - { - static string InvalidReceiver = "invalid"; - - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = SendGridIntegrationConfiguration - .Create(ApiKey, Sender) - .WithDefaultReceivers(InvalidReceiver) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain($"Invalid email(s): {InvalidReceiver}."); - } - - [Subject("SendGrid integration execution")] - public class when_invoking_send_email_method_with_valid_configuration_for_api_key : SendGridIntegration_specs - { - static Mock EmailSenderMock; - - Establish context = () => - { - EmailSenderMock = new Mock(); - Configuration = SendGridIntegrationConfiguration - .Create(ApiKey, Sender) - .WithDefaultReceivers(Receivers) - .WithEmailSenderProvider(() => EmailSenderMock.Object) - .Build(); - Integration = SendGridIntegration.Create(Configuration); - }; - - Because of = async () => - { - await Integration.SendEmailAsync().Await().AsTask; - }; - - It should_invoke_send_message_async_method_only_once = () => EmailSenderMock.Verify(x => - x.SendMessageAsync(ApiKey, Moq.It.IsAny()), Times.Once); - } - - [Subject("SendGrid integration execution")] - public class when_invoking_send_email_method_with_valid_configuration_for_credentials : SendGridIntegration_specs - { - static Mock EmailSenderMock; - - Establish context = () => - { - EmailSenderMock = new Mock(); - Configuration = SendGridIntegrationConfiguration - .Create(ApiKey, Sender) - .WithDefaultReceivers(Receivers) - .WithEmailSenderProvider(() => EmailSenderMock.Object) - .Build(); - Integration = SendGridIntegration.Create(Configuration); - }; - - Because of = async () => - { - await Integration.SendEmailAsync().Await().AsTask; - }; - - It should_invoke_send_message_async_method_only_once = () => EmailSenderMock.Verify(x => - x.SendMessageAsync(ApiKey, Moq.It.IsAny()), Times.Once); - } - - [Subject("SendGrid integration execution")] - public class when_invoking_send_email_method_with_valid_configuration_for_api_key_but_without_receivers : SendGridIntegration_specs - { - static Mock EmailSenderMock; - - Establish context = () => - { - EmailSenderMock = new Mock(); - Configuration = SendGridIntegrationConfiguration - .Create(ApiKey, Sender) - .WithEmailSenderProvider(() => EmailSenderMock.Object) - .Build(); - Integration = SendGridIntegration.Create(Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Integration.SendEmailAsync().Await().AsTask); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("Email message receivers have not been defined."); - - It should_not_invoke_send_message_async_method = () => EmailSenderMock.Verify(x => - x.SendMessageAsync(ApiKey, Moq.It.IsAny()), Times.Never); - } - - [Subject("SendGrid integration execution")] - public class when_invoking_send_email_method_with_valid_configuration_for_credentials_without_receivers : - SendGridIntegration_specs - { - static Mock EmailSenderMock; - - Establish context = () => - { - EmailSenderMock = new Mock(); - Configuration = SendGridIntegrationConfiguration - .Create(ApiKey, Sender) - .WithEmailSenderProvider(() => EmailSenderMock.Object) - .Build(); - Integration = SendGridIntegration.Create(Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Integration.SendEmailAsync().Await().AsTask); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("Email message receivers have not been defined."); - - It should_not_invoke_send_message_async_method = () => EmailSenderMock.Verify(x => - x.SendMessageAsync(ApiKey, Moq.It.IsAny()), Times.Never); - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Integrations/Slack/SlackIntegration_specs.cs b/src/Tests/Warden.Tests/Integrations/Slack/SlackIntegration_specs.cs deleted file mode 100644 index e319538..0000000 --- a/src/Tests/Warden.Tests/Integrations/Slack/SlackIntegration_specs.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using FluentAssertions; -using Moq; -using Warden.Integrations.Slack; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Integrations.Slack -{ - public class SlackIntegration_specs - { - protected static SlackIntegration Integration { get; set; } - protected static SlackIntegrationConfiguration Configuration { get; set; } - protected static Exception Exception { get; set; } - protected static string WebhookUrl = "https://slack.com"; - } - - [Subject("Slack integration initialization")] - public class when_initializing_without_configuration : SlackIntegration_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception(() => Integration = SlackIntegration.Create(Configuration)); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("Slack Integration configuration has not been provided."); - } - - [Subject("Slack integration initialization")] - public class when_initializing_with_invalid_webhook_url : SlackIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = SlackIntegrationConfiguration - .Create("Invalid") - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("Slack integration execution")] - public class when_invoking_send_message_async_method_with_valid_configuration : SlackIntegration_specs - { - static Mock SlackServiceMock; - - Establish context = () => - { - SlackServiceMock = new Mock(); - Configuration = SlackIntegrationConfiguration - .Create(WebhookUrl) - .WithSlackServiceProvider(() => SlackServiceMock.Object) - .Build(); - Integration = SlackIntegration.Create(Configuration); - }; - - Because of = async () => await Integration.SendMessageAsync().Await().AsTask; - - It should_invoke_send_message_async_method_only_once = () => SlackServiceMock.Verify(x => - x.SendMessageAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Integrations/Twilio/TwilioIntegrationTests.cs b/src/Tests/Warden.Tests/Integrations/Twilio/TwilioIntegrationTests.cs deleted file mode 100644 index 529b33b..0000000 --- a/src/Tests/Warden.Tests/Integrations/Twilio/TwilioIntegrationTests.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using FluentAssertions; -using Moq; -using Warden.Integrations.Twilio; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Integrations.Twilio -{ - public class TwilioIntegration_specs - { - protected static TwilioIntegration Integration { get; set; } - protected static TwilioIntegrationConfiguration Configuration { get; set; } - protected static Exception Exception { get; set; } - protected static string AccountSid = "sid"; - protected static string AuthToken = "token"; - protected static string Sender = "+1123456789"; - protected static string[] Receivers = {"+1123456780", "+1123456781"}; - } - - [Subject("Twilio integration initialization")] - public class when_initializing_without_configuration : TwilioIntegration_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception(() => Integration = TwilioIntegration.Create(Configuration)); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("Twilio Integration configuration has not been provided."); - } - - [Subject("Twilio integration initialization")] - public class when_initializing_with_empty_account_sid : TwilioIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = TwilioIntegrationConfiguration - .Create(string.Empty, AuthToken, Sender) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("Account SID can not be empty."); - } - - [Subject("Twilio integration initialization")] - public class when_initializing_with_empty_auth_token : TwilioIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = TwilioIntegrationConfiguration - .Create(AccountSid, string.Empty, Sender) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("Authentication token can not be empty."); - } - - [Subject("Twilio integration initialization")] - public class when_initializing_with_empty_sender : TwilioIntegration_specs - { - Establish context = () => { }; - - Because of = () => Exception = Catch.Exception(() => Configuration = TwilioIntegrationConfiguration - .Create(AccountSid, AuthToken, string.Empty) - .Build()); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("SMS sender can not be empty."); - } - - [Subject("Twilio integration execution")] - public class when_invoking_send_sms_method_with_empty_body : TwilioIntegration_specs - { - Establish context = () => - { - Configuration = TwilioIntegrationConfiguration - .Create(AccountSid, AuthToken, Sender) - .WithDefaultMessage("Test") - .Build(); - Integration = TwilioIntegration.Create(Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Integration.SendSmsAsync().Await().AsTask); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("SMS receiver(s) have not been defined."); - } - - [Subject("Twilio integration execution")] - public class when_invoking_send_sms_method_without_receivers : TwilioIntegration_specs - { - Establish context = () => - { - Configuration = TwilioIntegrationConfiguration - .Create(AccountSid, AuthToken, Sender) - .Build(); - Integration = TwilioIntegration.Create(Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Integration.SendSmsAsync().Await().AsTask); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("SMS body has not been defined."); - } - - [Subject("Twilio integration execution")] - public class when_invoking_send_sms_method_with_valid_configuration : TwilioIntegration_specs - { - static Mock TwilioServiceMock; - - Establish context = () => - { - TwilioServiceMock = new Mock(); - Configuration = TwilioIntegrationConfiguration - .Create(AccountSid, AuthToken, Sender) - .WithDefaultMessage("Test") - .WithDefaultReceivers(Receivers) - .WithTwilioServiceProvider(() => TwilioServiceMock.Object) - .Build(); - Integration = TwilioIntegration.Create(Configuration); - }; - - Because of = async () => - { - await Integration.SendSmsAsync().Await().AsTask; - }; - - It should_invoke_send_message_async_method_twice = () => TwilioServiceMock.Verify(x => - x.SendSmsAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny()), Times.Exactly(Receivers.Length)); - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Properties/launchSettings.json b/src/Tests/Warden.Tests/Properties/launchSettings.json deleted file mode 100644 index 65f00ea..0000000 --- a/src/Tests/Warden.Tests/Properties/launchSettings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "profiles": { - "test": { - "commandName": "test", - "commandLineArgs": "--wait" - } - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Warden.Tests.csproj b/src/Tests/Warden.Tests/Warden.Tests.csproj deleted file mode 100644 index 8f5e3f2..0000000 --- a/src/Tests/Warden.Tests/Warden.Tests.csproj +++ /dev/null @@ -1,56 +0,0 @@ - - - - Warden tests. - 1.3.1 - Piotr Gankiewicz - net461 - Warden.Tests - Warden.Tests - true - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Tests/Warden.Tests/Watchers/Disk/PerformanceWatcherTests.cs b/src/Tests/Warden.Tests/Watchers/Disk/PerformanceWatcherTests.cs deleted file mode 100644 index a898311..0000000 --- a/src/Tests/Warden.Tests/Watchers/Disk/PerformanceWatcherTests.cs +++ /dev/null @@ -1,270 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using FluentAssertions; -using Moq; -using Warden.Watchers; -using Warden.Watchers.Disk; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Watchers.Disk -{ - public class DiskWatcher_specs - { - protected static DiskWatcher Watcher { get; set; } - protected static DiskWatcherConfiguration Configuration { get; set; } - protected static IWatcherCheckResult CheckResult { get; set; } - protected static DiskWatcherCheckResult DiskCheckResult { get; set; } - protected static Exception Exception { get; set; } - protected static int FreeSpace { get; set; } = 10000; - protected static int UsedSpace { get; set; } = 1000; - } - - [Subject("Disk watcher initialization")] - public class when_initializing_without_configuration : DiskWatcher_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception(() => Watcher = DiskWatcher.Create("test", Configuration)); - - It should_fail = () => Exception.Should().BeOfType(); - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Disk Watcher configuration has not been provided."); - } - - [Subject("Disk watcher execution")] - public class when_invoking_execute_async_method_with_valid_configuration : DiskWatcher_specs - { - static Mock DiskCheckerMock; - static DiskCheck DiskCheck; - - private Establish context = () => - { - DiskCheckerMock = new Mock(); - DiskCheck = DiskCheck.Create(FreeSpace, UsedSpace, Moq.It.IsAny>(), - Moq.It.IsAny>(), Moq.It.IsAny>()); - DiskCheckerMock.Setup(x => - x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>())) - .ReturnsAsync(DiskCheck); - - Configuration = DiskWatcherConfiguration - .Create() - .WithDiskCheckerProvider(() => DiskCheckerMock.Object) - .Build(); - Watcher = DiskWatcher.Create("Disk watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - DiskCheckResult = CheckResult as DiskWatcherCheckResult; - }; - - It should_invoke_disk_check_async_method_only_once = () => - DiskCheckerMock.Verify(x => x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_disk = () => DiskCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_disk_check_result = () => - { - DiskCheckResult.WatcherName.Should().NotBeEmpty(); - DiskCheckResult.WatcherType.Should().NotBeNull(); - DiskCheckResult.DiskCheck.Should().NotBeNull(); - DiskCheckResult.DiskCheck.FreeSpace.ShouldBeEquivalentTo(FreeSpace); - DiskCheckResult.DiskCheck.UsedSpace.ShouldBeEquivalentTo(UsedSpace); - }; - } - - [Subject("Disk watcher execution")] - public class when_invoking_ensure_predicate_that_is_valid : DiskWatcher_specs - { - static Mock DiskCheckerMock; - static DiskCheck DiskCheck; - - Establish context = () => - { - DiskCheckerMock = new Mock(); - DiskCheck = DiskCheck.Create(FreeSpace, UsedSpace, Moq.It.IsAny>(), - Moq.It.IsAny>(), Moq.It.IsAny>()); - DiskCheckerMock.Setup(x => - x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>())) - .ReturnsAsync(DiskCheck); - - Configuration = DiskWatcherConfiguration - .Create() - .EnsureThatAsync(usage => Task.Factory.StartNew(() => usage.FreeSpace == FreeSpace && usage.UsedSpace == UsedSpace)) - .WithDiskCheckerProvider(() => DiskCheckerMock.Object) - .Build(); - Watcher = DiskWatcher.Create("Disk watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - DiskCheckResult = CheckResult as DiskWatcherCheckResult; - }; - - It should_invoke_disk_check_async_method_only_once = () => - DiskCheckerMock.Verify(x => x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_disk = () => DiskCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_disk_check_result = () => - { - DiskCheckResult.WatcherName.Should().NotBeEmpty(); - DiskCheckResult.WatcherType.Should().NotBeNull(); - DiskCheckResult.DiskCheck.Should().NotBeNull(); - DiskCheckResult.DiskCheck.FreeSpace.ShouldBeEquivalentTo(FreeSpace); - DiskCheckResult.DiskCheck.UsedSpace.ShouldBeEquivalentTo(UsedSpace); - }; - } - - [Subject("Disk watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_valid : DiskWatcher_specs - { - static Mock DiskCheckerMock; - static DiskCheck DiskCheck; - - Establish context = () => - { - DiskCheckerMock = new Mock(); - DiskCheck = DiskCheck.Create(FreeSpace, UsedSpace, Moq.It.IsAny>(), - Moq.It.IsAny>(), Moq.It.IsAny>()); - DiskCheckerMock.Setup(x => - x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>())) - .ReturnsAsync(DiskCheck); - - Configuration = DiskWatcherConfiguration - .Create() - .EnsureThatAsync(usage => Task.Factory.StartNew(() => usage.FreeSpace == FreeSpace && usage.UsedSpace == UsedSpace)) - .WithDiskCheckerProvider(() => DiskCheckerMock.Object) - .Build(); - Watcher = DiskWatcher.Create("Disk watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - DiskCheckResult = CheckResult as DiskWatcherCheckResult; - }; - - It should_invoke_disk_check_async_method_only_once = () => - DiskCheckerMock.Verify(x => x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_disk = () => DiskCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_disk_check_result = () => - { - DiskCheckResult.WatcherName.Should().NotBeEmpty(); - DiskCheckResult.WatcherType.Should().NotBeNull(); - DiskCheckResult.DiskCheck.Should().NotBeNull(); - DiskCheckResult.DiskCheck.FreeSpace.ShouldBeEquivalentTo(FreeSpace); - DiskCheckResult.DiskCheck.UsedSpace.ShouldBeEquivalentTo(UsedSpace); - }; - } - - [Subject("Disk watcher execution")] - public class when_invoking_ensure_predicate_that_is_invalid : DiskWatcher_specs - { - static Mock DiskCheckerMock; - static DiskCheck DiskCheck; - - Establish context = () => - { - DiskCheckerMock = new Mock(); - DiskCheck = DiskCheck.Create(FreeSpace, UsedSpace, Moq.It.IsAny>(), - Moq.It.IsAny>(), Moq.It.IsAny>()); - DiskCheckerMock.Setup(x => - x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>())) - .ReturnsAsync(DiskCheck); - - Configuration = DiskWatcherConfiguration - .Create() - .EnsureThat(usage => usage.FreeSpace != FreeSpace && usage.UsedSpace != UsedSpace) - .WithDiskCheckerProvider(() => DiskCheckerMock.Object) - .Build(); - Watcher = DiskWatcher.Create("Disk watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - DiskCheckResult = CheckResult as DiskWatcherCheckResult; - }; - - It should_invoke_disk_check_async_method_only_once = () => - DiskCheckerMock.Verify(x => x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_disk = () => DiskCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_disk_check_result = () => - { - DiskCheckResult.WatcherName.Should().NotBeEmpty(); - DiskCheckResult.WatcherType.Should().NotBeNull(); - DiskCheckResult.DiskCheck.Should().NotBeNull(); - DiskCheckResult.DiskCheck.FreeSpace.ShouldBeEquivalentTo(FreeSpace); - DiskCheckResult.DiskCheck.UsedSpace.ShouldBeEquivalentTo(UsedSpace); - }; - } - - [Subject("Disk watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_invalid : DiskWatcher_specs - { - static Mock DiskCheckerMock; - static DiskCheck DiskCheck; - - Establish context = () => - { - DiskCheckerMock = new Mock(); - DiskCheck = DiskCheck.Create(FreeSpace, UsedSpace, Moq.It.IsAny>(), - Moq.It.IsAny>(), Moq.It.IsAny>()); - DiskCheckerMock.Setup(x => - x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>())) - .ReturnsAsync(DiskCheck); - - Configuration = DiskWatcherConfiguration - .Create() - .EnsureThatAsync( - usage => Task.Factory.StartNew(() => usage.FreeSpace != FreeSpace && usage.UsedSpace != UsedSpace)) - .WithDiskCheckerProvider(() => DiskCheckerMock.Object) - .Build(); - Watcher = DiskWatcher.Create("Disk watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - DiskCheckResult = CheckResult as DiskWatcherCheckResult; - }; - - It should_invoke_disk_check_async_method_only_once = () => - DiskCheckerMock.Verify( - x => x.CheckAsync(Moq.It.IsAny>(), Moq.It.IsAny>(), - Moq.It.IsAny>()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_disk = () => DiskCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_disk_check_result = () => - { - DiskCheckResult.WatcherName.Should().NotBeEmpty(); - DiskCheckResult.WatcherType.Should().NotBeNull(); - DiskCheckResult.DiskCheck.Should().NotBeNull(); - DiskCheckResult.DiskCheck.FreeSpace.ShouldBeEquivalentTo(FreeSpace); - DiskCheckResult.DiskCheck.UsedSpace.ShouldBeEquivalentTo(UsedSpace); - }; - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Watchers/MongoDb/MongoDbWatcherTests.cs b/src/Tests/Warden.Tests/Watchers/MongoDb/MongoDbWatcherTests.cs deleted file mode 100644 index e359940..0000000 --- a/src/Tests/Warden.Tests/Watchers/MongoDb/MongoDbWatcherTests.cs +++ /dev/null @@ -1,300 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Moq; -using Warden.Watchers; -using Warden.Watchers.MongoDb; -using Machine.Specifications; -using It = Machine.Specifications.It; -using FluentAssertions; - -namespace Warden.Tests.Watchers.MongoDb -{ - public class MongoDbWatcher_specs - { - protected static string ConnectionString = "mongodb://localhost:27017"; - protected static string Database = "TestDb"; - protected static MongoDbWatcher Watcher { get; set; } - protected static MongoDbWatcherConfiguration Configuration { get; set; } - protected static IWatcherCheckResult CheckResult { get; set; } - protected static MongoDbWatcherCheckResult MongoDbCheckResult { get; set; } - protected static Exception Exception { get; set; } - - protected static IEnumerable QueryResult = new List - { - new {id = 1, name = "admin", role = "admin"}, - new {id = 2, name = "user", role = "user"} - }; - } - - [Subject("MongoDB watcher initialization")] - public class when_initializing_without_configuration : MongoDbWatcher_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception((() => Watcher = MongoDbWatcher.Create("test", Configuration))); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("MongoDB Watcher configuration has not been provided."); - } - - [Subject("MongoDB watcher execution")] - public class when_invoking_execute_async_with_configuration : MongoDbWatcher_specs - { - static Mock MongoDbConnectionMock; - - Establish context = () => - { - MongoDbConnectionMock = new Mock(); - Configuration = MongoDbWatcherConfiguration - .Create(Database, ConnectionString) - .WithConnectionProvider(connectionString => MongoDbConnectionMock.Object) - .Build(); - Watcher = MongoDbWatcher.Create("MongoDB watcher", Configuration); - }; - - Because of = async () => await Watcher.ExecuteAsync().Await().AsTask; - - It should_invoke_get_database_async_method_only_once = - () => MongoDbConnectionMock.Verify(x => x.GetDatabaseAsync(), Times.Once); - } - - [Subject("MongoDB watcher execution")] - public class when_invoking_execute_async_with_query : MongoDbWatcher_specs - { - static Mock MongoDbConnectionMock; - static Mock MongoDbMock; - - Establish context = () => - { - MongoDbConnectionMock = new Mock(); - MongoDbMock = new Mock(); - MongoDbMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - MongoDbConnectionMock.Setup(x => x.GetDatabaseAsync()).ReturnsAsync(MongoDbMock.Object); - Configuration = MongoDbWatcherConfiguration - .Create(Database, ConnectionString) - .WithQuery("Users", "{\"name\": \"admin\"}") - .WithConnectionProvider(connectionString => MongoDbConnectionMock.Object) - .Build(); - Watcher = MongoDbWatcher.Create("MongoDB watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MongoDbCheckResult = CheckResult as MongoDbWatcherCheckResult; - }; - - It should_invoke_get_database_async_method_only_once = - () => MongoDbConnectionMock.Verify(x => x.GetDatabaseAsync(), Times.Once); - - It should_invoke_query_async_method_only_once = - () => MongoDbMock.Verify(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_mongodb = () => MongoDbCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mongodb_check_result = () => - { - MongoDbCheckResult.WatcherName.Should().NotBeEmpty(); - MongoDbCheckResult.WatcherType.Should().NotBeNull(); - MongoDbCheckResult.ConnectionString.Should().NotBeEmpty(); - MongoDbCheckResult.Query.Should().NotBeEmpty(); - MongoDbCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("MongoDB watcher execution")] - public class when_invoking_ensure_predicate_that_is_valid : MongoDbWatcher_specs - { - static Mock MongoDbConnectionMock; - static Mock MongoDbMock; - - Establish context = () => - { - MongoDbConnectionMock = new Mock(); - MongoDbMock = new Mock(); - MongoDbMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - MongoDbConnectionMock.Setup(x => x.GetDatabaseAsync()).ReturnsAsync(MongoDbMock.Object); - Configuration = MongoDbWatcherConfiguration - .Create(Database, ConnectionString) - .WithQuery("Users", "{\"name\": \"admin\"}") - .EnsureThat(users => users.Any(user => user.id == 1)) - .WithConnectionProvider(connectionString => MongoDbConnectionMock.Object) - .Build(); - Watcher = MongoDbWatcher.Create("MongoDB watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MongoDbCheckResult = CheckResult as MongoDbWatcherCheckResult; - }; - - - It should_invoke_get_database_async_method_only_once = - () => MongoDbConnectionMock.Verify(x => x.GetDatabaseAsync(), Times.Once); - - It should_invoke_query_async_method_only_once = - () => MongoDbMock.Verify(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_mongodb = () => MongoDbCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mongodb_check_result = () => - { - MongoDbCheckResult.WatcherName.Should().NotBeEmpty(); - MongoDbCheckResult.WatcherType.Should().NotBeNull(); - MongoDbCheckResult.ConnectionString.Should().NotBeEmpty(); - MongoDbCheckResult.Query.Should().NotBeEmpty(); - MongoDbCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("MongoDB watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_valid : MongoDbWatcher_specs - { - static Mock MongoDbConnectionMock; - static Mock MongoDbMock; - - Establish context = () => - { - MongoDbConnectionMock = new Mock(); - MongoDbMock = new Mock(); - MongoDbMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - MongoDbConnectionMock.Setup(x => x.GetDatabaseAsync()).ReturnsAsync(MongoDbMock.Object); - Configuration = MongoDbWatcherConfiguration - .Create(Database, ConnectionString) - .WithQuery("Users", "{\"name\": \"admin\"}") - .EnsureThatAsync(users => Task.Factory.StartNew(() => users.Any(user => user.id == 1))) - .WithConnectionProvider(connectionString => MongoDbConnectionMock.Object) - .Build(); - Watcher = MongoDbWatcher.Create("MongoDB watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MongoDbCheckResult = CheckResult as MongoDbWatcherCheckResult; - }; - - It should_invoke_get_database_async_method_only_once = - () => MongoDbConnectionMock.Verify(x => x.GetDatabaseAsync(), Times.Once); - - It should_invoke_query_async_method_only_once = - () => MongoDbMock.Verify(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_mongodb = () => MongoDbCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mongodb_check_result = () => - { - MongoDbCheckResult.WatcherName.Should().NotBeEmpty(); - MongoDbCheckResult.WatcherType.Should().NotBeNull(); - MongoDbCheckResult.ConnectionString.Should().NotBeEmpty(); - MongoDbCheckResult.Query.Should().NotBeEmpty(); - MongoDbCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("MongoDB watcher execution")] - public class when_invoking_ensure_predicate_that_is_invalid : MongoDbWatcher_specs - { - static Mock MongoDbConnectionMock; - static Mock MongoDbMock; - - Establish context = () => - { - MongoDbConnectionMock = new Mock(); - MongoDbMock = new Mock(); - MongoDbMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - MongoDbConnectionMock.Setup(x => x.GetDatabaseAsync()).ReturnsAsync(MongoDbMock.Object); - Configuration = MongoDbWatcherConfiguration - .Create(Database, ConnectionString) - .WithQuery("Users", "{\"name\": \"admin\"}") - .EnsureThat(users => users.Any(user => user.id == 3)) - .WithConnectionProvider(connectionString => MongoDbConnectionMock.Object) - .Build(); - Watcher = MongoDbWatcher.Create("MongoDB watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MongoDbCheckResult = CheckResult as MongoDbWatcherCheckResult; - }; - - - It should_invoke_get_database_async_method_only_once = - () => MongoDbConnectionMock.Verify(x => x.GetDatabaseAsync(), Times.Once); - - It should_invoke_query_async_method_only_once = - () => MongoDbMock.Verify(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_mongodb = () => MongoDbCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mongodb_check_result = () => - { - MongoDbCheckResult.WatcherName.Should().NotBeEmpty(); - MongoDbCheckResult.WatcherType.Should().NotBeNull(); - MongoDbCheckResult.ConnectionString.Should().NotBeEmpty(); - MongoDbCheckResult.Query.Should().NotBeEmpty(); - MongoDbCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("MongoDB watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_invalid : MongoDbWatcher_specs - { - static Mock MongoDbConnectionMock; - static Mock MongoDbMock; - - Establish context = () => - { - MongoDbConnectionMock = new Mock(); - MongoDbMock = new Mock(); - MongoDbMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - MongoDbConnectionMock.Setup(x => x.GetDatabaseAsync()).ReturnsAsync(MongoDbMock.Object); - Configuration = MongoDbWatcherConfiguration - .Create(Database, ConnectionString) - .WithQuery("Users", "{\"name\": \"admin\"}") - .EnsureThatAsync(users => Task.Factory.StartNew(() => users.Any(user => user.id == 3))) - .WithConnectionProvider(connectionString => MongoDbConnectionMock.Object) - .Build(); - Watcher = MongoDbWatcher.Create("MongoDB watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MongoDbCheckResult = CheckResult as MongoDbWatcherCheckResult; - }; - - It should_invoke_get_database_async_method_only_once = - () => MongoDbConnectionMock.Verify(x => x.GetDatabaseAsync(), Times.Once); - - It should_invoke_query_async_method_only_once = - () => MongoDbMock.Verify(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_mongodb = () => MongoDbCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mongodb_check_result = () => - { - MongoDbCheckResult.WatcherName.Should().NotBeEmpty(); - MongoDbCheckResult.WatcherType.Should().NotBeNull(); - MongoDbCheckResult.ConnectionString.Should().NotBeEmpty(); - MongoDbCheckResult.Query.Should().NotBeEmpty(); - MongoDbCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Watchers/MsSql/MsSqlWatcherTests.cs b/src/Tests/Warden.Tests/Watchers/MsSql/MsSqlWatcherTests.cs deleted file mode 100644 index 3e6d488..0000000 --- a/src/Tests/Warden.Tests/Watchers/MsSql/MsSqlWatcherTests.cs +++ /dev/null @@ -1,383 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Threading.Tasks; -using FluentAssertions; -using Moq; -using Warden.Core; -using Warden.Watchers; -using Warden.Watchers.MsSql; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Watchers.MsSql -{ - public class MsSqlWatcher_specs - { - protected static string ConnectionString = - @"Data Source=.\sqlexpress;Initial Catalog=MyDatabase;Integrated Security=True"; - - protected static MsSqlWatcher Watcher { get; set; } - protected static MsSqlWatcherConfiguration Configuration { get; set; } - protected static IWatcherCheckResult CheckResult { get; set; } - protected static MsSqlWatcherCheckResult MsSqlCheckResult { get; set; } - protected static Exception Exception { get; set; } - - protected static IEnumerable QueryResult = new List - { - new {id = 1, name = "admin", role = "admin"}, - new {id = 2, name = "user", role = "user"} - }; - } - - [Subject("MSSQL watcher initialization")] - public class when_initializing_without_configuration : MsSqlWatcher_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception((() => Watcher = MsSqlWatcher.Create("test", Configuration))); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = - () => Exception.Message.Should().Contain("MSSQL Watcher configuration has not been provided."); - } - - [Subject("MSSQL watcher execution")] - public class when_invoking_execute_async_without_query : MsSqlWatcher_specs - { - static Mock MsSqlMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlMock = new Mock(); - DbConnectionMock = new Mock(); - Configuration = MsSqlWatcherConfiguration - .Create(ConnectionString) - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlProvider(() => MsSqlMock.Object) - .Build(); - Watcher = MsSqlWatcher.Create("MSSQL watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MsSqlCheckResult = CheckResult as MsSqlWatcherCheckResult; - }; - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - - It should_not_invoke_query_async_method = () => MsSqlMock.Verify( - x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny()), Times.Never); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_mssql = () => MsSqlCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mssl_check_result = () => - { - MsSqlCheckResult.WatcherName.Should().NotBeEmpty(); - MsSqlCheckResult.WatcherType.Should().NotBeNull(); - MsSqlCheckResult.ConnectionString.Should().NotBeEmpty(); - MsSqlCheckResult.Query.Should().BeEmpty(); - MsSqlCheckResult.QueryResult.Should().BeEmpty(); - }; - } - - [Subject("MSSQL watcher execution")] - public class when_invoking_execute_async_with_query : MsSqlWatcher_specs - { - static Mock MsSqlMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlMock = new Mock(); - DbConnectionMock = new Mock(); - MsSqlMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - Configuration = MsSqlWatcherConfiguration - .Create(ConnectionString) - .WithQuery("select * from users") - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlProvider(() => MsSqlMock.Object) - .Build(); - Watcher = MsSqlWatcher.Create("MSSQL watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MsSqlCheckResult = CheckResult as MsSqlWatcherCheckResult; - }; - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - - It should_invoke_query_async_method_only_once = () => MsSqlMock.Verify( - x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_mssql = () => MsSqlCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mssl_check_result = () => - { - MsSqlCheckResult.WatcherName.Should().NotBeEmpty(); - MsSqlCheckResult.WatcherType.Should().NotBeNull(); - MsSqlCheckResult.ConnectionString.Should().NotBeEmpty(); - MsSqlCheckResult.Query.Should().NotBeEmpty(); - MsSqlCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("MSSQL watcher execution")] - public class when_invoking_open_connection_that_fails : MsSqlWatcher_specs - { - static Mock MsSqlMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlMock = new Mock(); - DbConnectionMock = new Mock(); - DbConnectionMock.Setup(x => x.Open()).Throws(new Exception("Error")); - Configuration = MsSqlWatcherConfiguration - .Create(ConnectionString) - .WithQuery("select * from users") - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlProvider(() => MsSqlMock.Object) - .Build(); - Watcher = MsSqlWatcher.Create("MSSQL watcher", Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Watcher.ExecuteAsync().Await()); - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("MSSQL watcher execution")] - public class when_invoking_query_async_that_fails : MsSqlWatcher_specs - { - static Mock MsSqlMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlMock = new Mock(); - DbConnectionMock = new Mock(); - MsSqlMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny())) - .ThrowsAsync(new Exception("Error")); - Configuration = MsSqlWatcherConfiguration - .Create(ConnectionString) - .WithQuery("select * from users") - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlProvider(() => MsSqlMock.Object) - .Build(); - Watcher = MsSqlWatcher.Create("MSSQL watcher", Configuration); - }; - - Because of = () => Exception = Catch.Exception(() => Watcher.ExecuteAsync().Await()); - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("MSSQL watcher execution")] - public class when_invoking_ensure_predicate_that_is_valid : MsSqlWatcher_specs - { - static Mock MsSqlMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlMock = new Mock(); - DbConnectionMock = new Mock(); - MsSqlMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - Configuration = MsSqlWatcherConfiguration - .Create(ConnectionString) - .WithQuery("select * from users") - .EnsureThat(users => users.Any(user => user.id == 1)) - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlProvider(() => MsSqlMock.Object) - .Build(); - Watcher = MsSqlWatcher.Create("MSSQL watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MsSqlCheckResult = CheckResult as MsSqlWatcherCheckResult; - }; - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - - It should_invoke_query_async_method_only_once = () => MsSqlMock.Verify( - x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_mssql = () => MsSqlCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mssl_check_result = () => - { - MsSqlCheckResult.WatcherName.Should().NotBeEmpty(); - MsSqlCheckResult.WatcherType.Should().NotBeNull(); - MsSqlCheckResult.ConnectionString.Should().NotBeEmpty(); - MsSqlCheckResult.Query.Should().NotBeEmpty(); - MsSqlCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("MSSQL watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_valid : MsSqlWatcher_specs - { - static Mock MsSqlMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlMock = new Mock(); - DbConnectionMock = new Mock(); - MsSqlMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - Configuration = MsSqlWatcherConfiguration - .Create(ConnectionString) - .WithQuery("select * from users") - .EnsureThatAsync(users => Task.Factory.StartNew(() => users.Any(user => user.id == 1))) - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlProvider(() => MsSqlMock.Object) - .Build(); - Watcher = MsSqlWatcher.Create("MSSQL watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MsSqlCheckResult = CheckResult as MsSqlWatcherCheckResult; - }; - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - - It should_invoke_query_async_method_only_once = () => MsSqlMock.Verify( - x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_mssql = () => MsSqlCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mssl_check_result = () => - { - MsSqlCheckResult.WatcherName.Should().NotBeEmpty(); - MsSqlCheckResult.WatcherType.Should().NotBeNull(); - MsSqlCheckResult.ConnectionString.Should().NotBeEmpty(); - MsSqlCheckResult.Query.Should().NotBeEmpty(); - MsSqlCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - - [Subject("MSSQL watcher execution")] - public class when_invoking_ensure_predicate_that_is_invalid : MsSqlWatcher_specs - { - static Mock MsSqlMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlMock = new Mock(); - DbConnectionMock = new Mock(); - MsSqlMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - Configuration = MsSqlWatcherConfiguration - .Create(ConnectionString) - .WithQuery("select * from users") - .EnsureThat(users => users.Any(user => user.id == 100)) - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlProvider(() => MsSqlMock.Object) - .Build(); - Watcher = MsSqlWatcher.Create("MSSQL watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MsSqlCheckResult = CheckResult as MsSqlWatcherCheckResult; - }; - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - - It should_invoke_query_async_method_only_once = () => MsSqlMock.Verify( - x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_mssql = () => MsSqlCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mssl_check_result = () => - { - MsSqlCheckResult.WatcherName.Should().NotBeEmpty(); - MsSqlCheckResult.WatcherType.Should().NotBeNull(); - MsSqlCheckResult.ConnectionString.Should().NotBeEmpty(); - MsSqlCheckResult.Query.Should().NotBeEmpty(); - MsSqlCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("MSSQL watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_invalid : MsSqlWatcher_specs - { - static Mock MsSqlMock; - static Mock DbConnectionMock; - - Establish context = () => - { - MsSqlMock = new Mock(); - DbConnectionMock = new Mock(); - MsSqlMock.Setup(x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - Configuration = MsSqlWatcherConfiguration - .Create(ConnectionString) - .WithQuery("select * from users") - .EnsureThatAsync(users => Task.Factory.StartNew(() => users.Any(user => user.id == 100))) - .WithConnectionProvider(connectionString => DbConnectionMock.Object) - .WithMsSqlProvider(() => MsSqlMock.Object) - .Build(); - Watcher = MsSqlWatcher.Create("MSSQL watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - MsSqlCheckResult = CheckResult as MsSqlWatcherCheckResult; - }; - - It should_invoke_open_method_only_once = () => DbConnectionMock.Verify(x => x.Open(), Times.Once); - - It should_invoke_query_async_method_only_once = () => MsSqlMock.Verify( - x => x.QueryAsync(Moq.It.IsAny(), Moq.It.IsAny(), - Moq.It.IsAny>(), Moq.It.IsAny()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_mssql = () => MsSqlCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_mssl_check_result = () => - { - MsSqlCheckResult.WatcherName.Should().NotBeEmpty(); - MsSqlCheckResult.WatcherType.Should().NotBeNull(); - MsSqlCheckResult.ConnectionString.Should().NotBeEmpty(); - MsSqlCheckResult.Query.Should().NotBeEmpty(); - MsSqlCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Watchers/Performance/PerformanceWatcherTests.cs b/src/Tests/Warden.Tests/Watchers/Performance/PerformanceWatcherTests.cs deleted file mode 100644 index 9c2dcdb..0000000 --- a/src/Tests/Warden.Tests/Watchers/Performance/PerformanceWatcherTests.cs +++ /dev/null @@ -1,250 +0,0 @@ -using System; -using System.Threading.Tasks; -using FluentAssertions; -using Moq; -using Warden.Watchers; -using Warden.Watchers.Performance; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Watchers.Performance -{ - public class PerformanceWatcher_specs - { - protected static PerformanceWatcher Watcher { get; set; } - protected static PerformanceWatcherConfiguration Configuration { get; set; } - protected static IWatcherCheckResult CheckResult { get; set; } - protected static PerformanceWatcherCheckResult PerformanceCheckResult { get; set; } - protected static Exception Exception { get; set; } - protected static int CpuUsage { get; set; } = 10; - protected static int RamUsage { get; set; } = 1000; - } - - [Subject("Performance watcher initialization")] - public class when_initializing_without_configuration : PerformanceWatcher_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception((() => Watcher = PerformanceWatcher.Create("test", Configuration))); - - It should_fail = () => Exception.Should().BeOfType(); - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Performance Watcher configuration has not been provided."); - } - - [Subject("Performance watcher execution")] - public class when_invoking_execute_async_method_with_valid_configuration : PerformanceWatcher_specs - { - static Mock PerformanceMock; - static ResourceUsage ResourceUsage; - - Establish context = () => - { - PerformanceMock = new Mock(); - ResourceUsage = ResourceUsage.Create(CpuUsage, RamUsage); - PerformanceMock.Setup(x => - x.GetResourceUsageAsync()) - .ReturnsAsync(ResourceUsage); - - Configuration = PerformanceWatcherConfiguration - .Create() - .WithPerformanceProvider(() => PerformanceMock.Object) - .Build(); - Watcher = PerformanceWatcher.Create("Performance watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - PerformanceCheckResult = CheckResult as PerformanceWatcherCheckResult; - }; - - It should_invoke_performance_get_resource_usage_async_method_only_once = () => - PerformanceMock.Verify(x => x.GetResourceUsageAsync(), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_performance = () => PerformanceCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_performance_check_result = () => - { - PerformanceCheckResult.WatcherName.Should().NotBeEmpty(); - PerformanceCheckResult.WatcherType.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Cpu.ShouldBeEquivalentTo(CpuUsage); - PerformanceCheckResult.ResourceUsage.Ram.ShouldBeEquivalentTo(RamUsage); - }; - } - - [Subject("Performance watcher execution")] - public class when_invoking_ensure_predicate_that_is_valid : PerformanceWatcher_specs - { - static Mock PerformanceMock; - static ResourceUsage ResourceUsage; - - Establish context = () => - { - PerformanceMock = new Mock(); - ResourceUsage = ResourceUsage.Create(CpuUsage, RamUsage); - PerformanceMock.Setup(x => - x.GetResourceUsageAsync()) - .ReturnsAsync(ResourceUsage); - - Configuration = PerformanceWatcherConfiguration - .Create() - .EnsureThat(usage => usage.Cpu == CpuUsage && usage.Ram == RamUsage ) - .WithPerformanceProvider(() => PerformanceMock.Object) - .Build(); - Watcher = PerformanceWatcher.Create("Performance watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - PerformanceCheckResult = CheckResult as PerformanceWatcherCheckResult; - }; - - It should_invoke_performance_get_resource_usage_async_method_only_once = () => - PerformanceMock.Verify(x => x.GetResourceUsageAsync(), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_performance = () => PerformanceCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_performance_check_result = () => - { - PerformanceCheckResult.WatcherName.Should().NotBeEmpty(); - PerformanceCheckResult.WatcherType.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Cpu.ShouldBeEquivalentTo(CpuUsage); - PerformanceCheckResult.ResourceUsage.Ram.ShouldBeEquivalentTo(RamUsage); - }; - } - - [Subject("Performance watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_valid : PerformanceWatcher_specs - { - static Mock PerformanceMock; - static ResourceUsage ResourceUsage; - - Establish context = () => - { - PerformanceMock = new Mock(); - ResourceUsage = ResourceUsage.Create(CpuUsage, RamUsage); - PerformanceMock.Setup(x => - x.GetResourceUsageAsync()) - .ReturnsAsync(ResourceUsage); - - Configuration = PerformanceWatcherConfiguration - .Create() - .EnsureThatAsync(usage => Task.Factory.StartNew(() => usage.Cpu == CpuUsage && usage.Ram == RamUsage)) - .WithPerformanceProvider(() => PerformanceMock.Object) - .Build(); - Watcher = PerformanceWatcher.Create("Performance watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - PerformanceCheckResult = CheckResult as PerformanceWatcherCheckResult; - }; - - It should_invoke_performance_get_resource_usage_async_method_only_once = () => - PerformanceMock.Verify(x => x.GetResourceUsageAsync(), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_performance = () => PerformanceCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_performance_check_result = () => - { - PerformanceCheckResult.WatcherName.Should().NotBeEmpty(); - PerformanceCheckResult.WatcherType.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Cpu.ShouldBeEquivalentTo(CpuUsage); - PerformanceCheckResult.ResourceUsage.Ram.ShouldBeEquivalentTo(RamUsage); - }; - } - - [Subject("Performance watcher execution")] - public class when_invoking_ensure_predicate_that_is_invalid : PerformanceWatcher_specs - { - static Mock PerformanceMock; - static ResourceUsage ResourceUsage; - - Establish context = () => - { - PerformanceMock = new Mock(); - ResourceUsage = ResourceUsage.Create(CpuUsage, RamUsage); - PerformanceMock.Setup(x => - x.GetResourceUsageAsync()) - .ReturnsAsync(ResourceUsage); - Configuration = PerformanceWatcherConfiguration - .Create() - .EnsureThat(usage => usage.Cpu != CpuUsage && usage.Ram != RamUsage) - .WithPerformanceProvider(() => PerformanceMock.Object) - .Build(); - Watcher = PerformanceWatcher.Create("Performance watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - PerformanceCheckResult = CheckResult as PerformanceWatcherCheckResult; - }; - - It should_invoke_performance_get_resource_usage_async_method_only_once = () => - PerformanceMock.Verify(x => x.GetResourceUsageAsync(), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_performance = () => PerformanceCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_performance_check_result = () => - { - PerformanceCheckResult.WatcherName.Should().NotBeEmpty(); - PerformanceCheckResult.WatcherType.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Cpu.ShouldBeEquivalentTo(CpuUsage); - PerformanceCheckResult.ResourceUsage.Ram.ShouldBeEquivalentTo(RamUsage); - }; - } - - [Subject("Performance watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_invalid : PerformanceWatcher_specs - { - static Mock PerformanceMock; - static ResourceUsage ResourceUsage; - - Establish context = () => - { - PerformanceMock = new Mock(); - ResourceUsage = ResourceUsage.Create(CpuUsage, RamUsage); - PerformanceMock.Setup(x => - x.GetResourceUsageAsync()) - .ReturnsAsync(ResourceUsage); - Configuration = PerformanceWatcherConfiguration - .Create() - .EnsureThatAsync(usage => Task.Factory.StartNew(() => usage.Cpu != CpuUsage && usage.Ram != RamUsage)) - .WithPerformanceProvider(() => PerformanceMock.Object) - .Build(); - Watcher = PerformanceWatcher.Create("Performance watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - PerformanceCheckResult = CheckResult as PerformanceWatcherCheckResult; - }; - - It should_invoke_performance_get_resource_usage_async_method_only_once = () => - PerformanceMock.Verify(x => x.GetResourceUsageAsync(), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_performance = () => PerformanceCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_performance_check_result = () => - { - PerformanceCheckResult.WatcherName.Should().NotBeEmpty(); - PerformanceCheckResult.WatcherType.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Should().NotBeNull(); - PerformanceCheckResult.ResourceUsage.Cpu.ShouldBeEquivalentTo(CpuUsage); - PerformanceCheckResult.ResourceUsage.Ram.ShouldBeEquivalentTo(RamUsage); - }; - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Watchers/Process/PerformanceWatcherTests.cs b/src/Tests/Warden.Tests/Watchers/Process/PerformanceWatcherTests.cs deleted file mode 100644 index 244f98d..0000000 --- a/src/Tests/Warden.Tests/Watchers/Process/PerformanceWatcherTests.cs +++ /dev/null @@ -1,320 +0,0 @@ -using System; -using System.Threading.Tasks; -using FluentAssertions; -using Moq; -using Warden.Watchers; -using Warden.Watchers.Process; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Watchers.Process -{ - public class ProcessWatcher_specs - { - protected static ProcessWatcher Watcher { get; set; } - protected static ProcessWatcherConfiguration Configuration { get; set; } - protected static IWatcherCheckResult CheckResult { get; set; } - protected static ProcessWatcherCheckResult ProcessCheckResult { get; set; } - protected static Exception Exception { get; set; } - protected static int ProcessId { get; set; } = 1; - protected static string ProcessName { get; set; } = "Process"; - protected static bool ProcessResponding { get; set; } = true; - protected static bool ProcessExists { get; set; } = true; - } - - [Subject("Process watcher initialization")] - public class when_initializing_without_configuration : ProcessWatcher_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception((() => Watcher = ProcessWatcher.Create("test", Configuration))); - - It should_fail = () => Exception.Should().BeOfType(); - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Process Watcher configuration has not been provided."); - } - - [Subject("Process watcher execution")] - public class when_invoking_execute_async_method_with_valid_configuration : ProcessWatcher_specs - { - static Mock ProcessMock; - static ProcessInfo ProcessInfo; - - Establish context = () => - { - ProcessMock = new Mock(); - ProcessInfo = ProcessInfo.Create(ProcessId, ProcessName, null, ProcessExists, ProcessResponding); - ProcessMock.Setup(x => - x.GetProcessInfoAsync(Moq.It.IsAny(), null)) - .ReturnsAsync(ProcessInfo); - - Configuration = ProcessWatcherConfiguration - .Create(ProcessName) - .WithProcessServiceProvider(() => ProcessMock.Object) - .Build(); - Watcher = ProcessWatcher.Create("Process watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - ProcessCheckResult = CheckResult as ProcessWatcherCheckResult; - }; - - It should_invoke_process_get_process_info_async_method_only_once = () => - ProcessMock.Verify(x => x.GetProcessInfoAsync(Moq.It.IsAny(), null), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_process = () => ProcessCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_process_check_result = () => - { - ProcessCheckResult.WatcherName.Should().NotBeEmpty(); - ProcessCheckResult.WatcherType.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Id.ShouldBeEquivalentTo(ProcessId); - ProcessCheckResult.ProcessInfo.Name.ShouldBeEquivalentTo(ProcessName); - ProcessCheckResult.ProcessInfo.Exists.ShouldBeEquivalentTo(ProcessExists); - ProcessCheckResult.ProcessInfo.Responding.ShouldBeEquivalentTo(ProcessResponding); - }; - } - - [Subject("Process watcher execution")] - public class when_invoking_execute_async_method_with_skip_Responding_validation_enabled : ProcessWatcher_specs - { - static Mock ProcessMock; - static ProcessInfo ProcessInfo; - - Establish context = () => - { - ProcessMock = new Mock(); - ProcessInfo = ProcessInfo.Create(ProcessId, ProcessName, null, ProcessExists, ProcessResponding); - ProcessMock.Setup(x => - x.GetProcessInfoAsync(Moq.It.IsAny(), null)) - .ReturnsAsync(ProcessInfo); - - Configuration = ProcessWatcherConfiguration - .Create(ProcessName) - .DoesNotHaveToBeResponding() - .WithProcessServiceProvider(() => ProcessMock.Object) - .Build(); - Watcher = ProcessWatcher.Create("Process watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - ProcessCheckResult = CheckResult as ProcessWatcherCheckResult; - }; - - It should_invoke_process_get_process_info_async_method_only_once = () => - ProcessMock.Verify(x => x.GetProcessInfoAsync(Moq.It.IsAny(), null), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_process = () => ProcessCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_process_check_result = () => - { - ProcessCheckResult.WatcherName.Should().NotBeEmpty(); - ProcessCheckResult.WatcherType.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Id.ShouldBeEquivalentTo(ProcessId); - ProcessCheckResult.ProcessInfo.Name.ShouldBeEquivalentTo(ProcessName); - ProcessCheckResult.ProcessInfo.Exists.ShouldBeEquivalentTo(ProcessExists); - ProcessCheckResult.ProcessInfo.Responding.ShouldBeEquivalentTo(ProcessResponding); - }; - } - - [Subject("Process watcher execution")] - public class when_invoking_ensure_predicate_that_is_valid : ProcessWatcher_specs - { - static Mock ProcessMock; - static ProcessInfo ProcessInfo; - - Establish context = () => - { - ProcessMock = new Mock(); - ProcessInfo = ProcessInfo.Create(ProcessId, ProcessName, null, ProcessExists, ProcessResponding); - ProcessMock.Setup(x => - x.GetProcessInfoAsync(Moq.It.IsAny(), null)) - .ReturnsAsync(ProcessInfo); - - Configuration = ProcessWatcherConfiguration - .Create(ProcessName) - .EnsureThat(info => info.Id == ProcessId - && info.Name == ProcessName && - info.Exists == ProcessExists && - info.Responding == ProcessResponding) - .WithProcessServiceProvider(() => ProcessMock.Object) - .Build(); - Watcher = ProcessWatcher.Create("Process watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - ProcessCheckResult = CheckResult as ProcessWatcherCheckResult; - }; - - It should_invoke_process_get_process_info_async_method_only_once = () => - ProcessMock.Verify(x => x.GetProcessInfoAsync(Moq.It.IsAny(), null), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_process = () => ProcessCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_process_check_result = () => - { - ProcessCheckResult.WatcherName.Should().NotBeEmpty(); - ProcessCheckResult.WatcherType.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Id.ShouldBeEquivalentTo(ProcessId); - ProcessCheckResult.ProcessInfo.Name.ShouldBeEquivalentTo(ProcessName); - ProcessCheckResult.ProcessInfo.Exists.ShouldBeEquivalentTo(ProcessExists); - ProcessCheckResult.ProcessInfo.Responding.ShouldBeEquivalentTo(ProcessResponding); - }; - } - - [Subject("Process watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_valid : ProcessWatcher_specs - { - static Mock ProcessMock; - static ProcessInfo ProcessInfo; - - Establish context = () => - { - ProcessMock = new Mock(); - ProcessInfo = ProcessInfo.Create(ProcessId, ProcessName, null, ProcessExists, ProcessResponding); - ProcessMock.Setup(x => - x.GetProcessInfoAsync(Moq.It.IsAny(), null)) - .ReturnsAsync(ProcessInfo); - - Configuration = ProcessWatcherConfiguration - .Create(ProcessName) - .EnsureThatAsync(info => Task.Factory.StartNew(() => info.Id == ProcessId - && info.Name == ProcessName && - info.Exists == ProcessExists && - info.Responding == ProcessResponding)) - .WithProcessServiceProvider(() => ProcessMock.Object) - .Build(); - Watcher = ProcessWatcher.Create("Process watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - ProcessCheckResult = CheckResult as ProcessWatcherCheckResult; - }; - - It should_invoke_process_get_process_info_async_method_only_once = () => - ProcessMock.Verify(x => x.GetProcessInfoAsync(Moq.It.IsAny(), null), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_process = () => ProcessCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_process_check_result = () => - { - ProcessCheckResult.WatcherName.Should().NotBeEmpty(); - ProcessCheckResult.WatcherType.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Id.ShouldBeEquivalentTo(ProcessId); - ProcessCheckResult.ProcessInfo.Name.ShouldBeEquivalentTo(ProcessName); - ProcessCheckResult.ProcessInfo.Exists.ShouldBeEquivalentTo(ProcessExists); - ProcessCheckResult.ProcessInfo.Responding.ShouldBeEquivalentTo(ProcessResponding); - }; - } - - [Subject("Process watcher execution")] - public class when_invoking_ensure_predicate_that_is_invalid : ProcessWatcher_specs - { - static Mock ProcessMock; - static ProcessInfo ProcessInfo; - - Establish context = () => - { - ProcessMock = new Mock(); - ProcessInfo = ProcessInfo.Create(ProcessId, ProcessName, null, false, false); - ProcessMock.Setup(x => - x.GetProcessInfoAsync(Moq.It.IsAny(), null)) - .ReturnsAsync(ProcessInfo); - Configuration = ProcessWatcherConfiguration - .Create(ProcessName) - .EnsureThat(info => info.Id == ProcessId - && info.Name == ProcessName && - info.Exists && - info.Responding) - .WithProcessServiceProvider(() => ProcessMock.Object) - .Build(); - Watcher = ProcessWatcher.Create("Process watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - ProcessCheckResult = CheckResult as ProcessWatcherCheckResult; - }; - - It should_invoke_process_get_process_info_async_method_only_once = () => - ProcessMock.Verify(x => x.GetProcessInfoAsync(Moq.It.IsAny(), null), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_process = () => ProcessCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_process_check_result = () => - { - ProcessCheckResult.WatcherName.Should().NotBeEmpty(); - ProcessCheckResult.WatcherType.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Id.ShouldBeEquivalentTo(ProcessId); - ProcessCheckResult.ProcessInfo.Name.ShouldBeEquivalentTo(ProcessName); - ProcessCheckResult.ProcessInfo.Exists.ShouldBeEquivalentTo(false); - ProcessCheckResult.ProcessInfo.Responding.ShouldBeEquivalentTo(false); - }; - } - - [Subject("Process watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_invalid : ProcessWatcher_specs - { - static Mock ProcessMock; - static ProcessInfo ProcessInfo; - - Establish context = () => - { - ProcessMock = new Mock(); - ProcessInfo = ProcessInfo.Create(ProcessId, ProcessName, null, false, false); - ProcessMock.Setup(x => - x.GetProcessInfoAsync(Moq.It.IsAny(), null)) - .ReturnsAsync(ProcessInfo); - Configuration = ProcessWatcherConfiguration - .Create(ProcessName) - .EnsureThatAsync(info => Task.Factory.StartNew(() => info.Id == ProcessId - && info.Name == ProcessName && - info.Exists && - info.Responding)) - .WithProcessServiceProvider(() => ProcessMock.Object) - .Build(); - Watcher = ProcessWatcher.Create("Process watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - ProcessCheckResult = CheckResult as ProcessWatcherCheckResult; - }; - - It should_invoke_process_get_process_info_async_method_only_once = () => - ProcessMock.Verify(x => x.GetProcessInfoAsync(Moq.It.IsAny(), null), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_process = () => ProcessCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_process_check_result = () => - { - ProcessCheckResult.WatcherName.Should().NotBeEmpty(); - ProcessCheckResult.WatcherType.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Should().NotBeNull(); - ProcessCheckResult.ProcessInfo.Id.ShouldBeEquivalentTo(ProcessId); - ProcessCheckResult.ProcessInfo.Name.ShouldBeEquivalentTo(ProcessName); - ProcessCheckResult.ProcessInfo.Exists.ShouldBeEquivalentTo(false); - ProcessCheckResult.ProcessInfo.Responding.ShouldBeEquivalentTo(false); - }; - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Watchers/Redis/RedisWatcherTests.cs b/src/Tests/Warden.Tests/Watchers/Redis/RedisWatcherTests.cs deleted file mode 100644 index f006750..0000000 --- a/src/Tests/Warden.Tests/Watchers/Redis/RedisWatcherTests.cs +++ /dev/null @@ -1,298 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using FluentAssertions; -using Moq; -using Warden.Watchers; -using Warden.Watchers.Redis; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Watchers.Redis -{ - public class RedisWatcher_specs - { - protected static string ConnectionString = "localhost"; - protected static int Database = 1; - protected static RedisWatcher Watcher { get; set; } - protected static RedisWatcherConfiguration Configuration { get; set; } - protected static IWatcherCheckResult CheckResult { get; set; } - protected static RedisWatcherCheckResult RedisCheckResult { get; set; } - protected static Exception Exception { get; set; } - - protected static IEnumerable QueryResult = new List - { - "test-value" - }; - } - - [Subject("Redis watcher initialization")] - public class when_initializing_without_configuration : RedisWatcher_specs - { - Establish context = () => Configuration = null; - - Because of =() => Exception = Catch.Exception((() => Watcher = RedisWatcher.Create("test", Configuration))); - - It should_fail = () => Exception.Should().BeOfType(); - - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Redis Watcher configuration has not been provided."); - } - - [Subject("Redis watcher execution")] - public class when_invoking_execute_async_with_configuration : RedisWatcher_specs - { - static Mock RedisConnectionMock; - - Establish context = () => - { - RedisConnectionMock = new Mock(); - Configuration = RedisWatcherConfiguration - .Create(ConnectionString, Database) - .WithConnectionProvider(connectionString => RedisConnectionMock.Object) - .Build(); - Watcher = RedisWatcher.Create("Redis watcher", Configuration); - }; - - Because of = async () => await Watcher.ExecuteAsync().Await().AsTask; - - It should_invoke_get_database_async_method_only_once = - () => RedisConnectionMock.Verify(x => x.GetDatabaseAsync(Moq.It.IsAny()), Times.Once); - } - - [Subject("Redis watcher execution")] - public class when_invoking_execute_async_with_query : RedisWatcher_specs - { - static Mock RedisConnectionMock; - static Mock RedisMock; - - Establish context = () => - { - RedisConnectionMock = new Mock(); - RedisMock = new Mock(); - RedisMock.Setup(x => x.QueryAsync(Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - RedisConnectionMock.Setup(x => x.GetDatabaseAsync(Moq.It.IsAny())).ReturnsAsync(RedisMock.Object); - Configuration = RedisWatcherConfiguration - .Create(ConnectionString, Database) - .WithQuery("get test") - .WithConnectionProvider(connectionString => RedisConnectionMock.Object) - .Build(); - Watcher = RedisWatcher.Create("Redis watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - RedisCheckResult = CheckResult as RedisWatcherCheckResult; - }; - - It should_invoke_get_database_async_method_only_once = - () => RedisConnectionMock.Verify(x => x.GetDatabaseAsync(Moq.It.IsAny()), Times.Once); - - It should_invoke_query_async_method_only_once = - () => RedisMock.Verify(x => x.QueryAsync(Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_redis = () => RedisCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_redis_check_result = () => - { - RedisCheckResult.WatcherName.Should().NotBeEmpty(); - RedisCheckResult.WatcherType.Should().NotBeNull(); - RedisCheckResult.ConnectionString.Should().NotBeEmpty(); - RedisCheckResult.Query.Should().NotBeEmpty(); - RedisCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("Redis watcher execution")] - public class when_invoking_ensure_predicate_that_is_valid : RedisWatcher_specs - { - static Mock RedisConnectionMock; - static Mock RedisMock; - - Establish context = () => - { - RedisConnectionMock = new Mock(); - RedisMock = new Mock(); - RedisMock.Setup(x => x.QueryAsync(Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - RedisConnectionMock.Setup(x => x.GetDatabaseAsync(Moq.It.IsAny())).ReturnsAsync(RedisMock.Object); - Configuration = RedisWatcherConfiguration - .Create(ConnectionString, Database) - .WithQuery("get test") - .EnsureThat(results => results.Any(x => x == "test-value")) - .WithConnectionProvider(connectionString => RedisConnectionMock.Object) - .Build(); - Watcher = RedisWatcher.Create("Redis watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - RedisCheckResult = CheckResult as RedisWatcherCheckResult; - }; - - - It should_invoke_get_database_async_method_only_once = - () => RedisConnectionMock.Verify(x => x.GetDatabaseAsync(Moq.It.IsAny()), Times.Once); - - It should_invoke_query_async_method_only_once = - () => RedisMock.Verify(x => x.QueryAsync(Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_redis = () => RedisCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_redis_check_result = () => - { - RedisCheckResult.WatcherName.Should().NotBeEmpty(); - RedisCheckResult.WatcherType.Should().NotBeNull(); - RedisCheckResult.ConnectionString.Should().NotBeEmpty(); - RedisCheckResult.Query.Should().NotBeEmpty(); - RedisCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("Redis watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_valid : RedisWatcher_specs - { - static Mock RedisConnectionMock; - static Mock RedisMock; - - Establish context = () => - { - RedisConnectionMock = new Mock(); - RedisMock = new Mock(); - RedisMock.Setup(x => x.QueryAsync(Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - RedisConnectionMock.Setup(x => x.GetDatabaseAsync(Moq.It.IsAny())).ReturnsAsync(RedisMock.Object); - Configuration = RedisWatcherConfiguration - .Create(ConnectionString, Database) - .WithQuery("get test") - .EnsureThatAsync(results => Task.Factory.StartNew(() => results.Any(x => x == "test-value"))) - .WithConnectionProvider(connectionString => RedisConnectionMock.Object) - .Build(); - Watcher = RedisWatcher.Create("Redis watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - RedisCheckResult = CheckResult as RedisWatcherCheckResult; - }; - - It should_invoke_get_database_async_method_only_once = - () => RedisConnectionMock.Verify(x => x.GetDatabaseAsync(Moq.It.IsAny()), Times.Once); - - It should_invoke_query_async_method_only_once = - () => RedisMock.Verify(x => x.QueryAsync(Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_redis = () => RedisCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_redis_check_result = () => - { - RedisCheckResult.WatcherName.Should().NotBeEmpty(); - RedisCheckResult.WatcherType.Should().NotBeNull(); - RedisCheckResult.ConnectionString.Should().NotBeEmpty(); - RedisCheckResult.Query.Should().NotBeEmpty(); - RedisCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("Redis watcher execution")] - public class when_invoking_ensure_predicate_that_is_invalid : RedisWatcher_specs - { - static Mock RedisConnectionMock; - static Mock RedisMock; - - Establish context = () => - { - RedisConnectionMock = new Mock(); - RedisMock = new Mock(); - RedisMock.Setup(x => x.QueryAsync(Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - RedisConnectionMock.Setup(x => x.GetDatabaseAsync(Moq.It.IsAny())).ReturnsAsync(RedisMock.Object); - Configuration = RedisWatcherConfiguration - .Create(ConnectionString, Database) - .WithQuery("get test") - .EnsureThat(results => results.Any(x => x == "invalid-value")) - .WithConnectionProvider(connectionString => RedisConnectionMock.Object) - .Build(); - Watcher = RedisWatcher.Create("Redis watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - RedisCheckResult = CheckResult as RedisWatcherCheckResult; - }; - - - It should_invoke_get_database_async_method_only_once = - () => RedisConnectionMock.Verify(x => x.GetDatabaseAsync(Moq.It.IsAny()), Times.Once); - - It should_invoke_query_async_method_only_once = - () => RedisMock.Verify(x => x.QueryAsync(Moq.It.IsAny()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_redis = () => RedisCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_redis_check_result = () => - { - RedisCheckResult.WatcherName.Should().NotBeEmpty(); - RedisCheckResult.WatcherType.Should().NotBeNull(); - RedisCheckResult.ConnectionString.Should().NotBeEmpty(); - RedisCheckResult.Query.Should().NotBeEmpty(); - RedisCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } - - [Subject("Redis watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_invalid : RedisWatcher_specs - { - static Mock RedisConnectionMock; - static Mock RedisMock; - - Establish context = () => - { - RedisConnectionMock = new Mock(); - RedisMock = new Mock(); - RedisMock.Setup(x => x.QueryAsync(Moq.It.IsAny())) - .ReturnsAsync(QueryResult); - RedisConnectionMock.Setup(x => x.GetDatabaseAsync(Moq.It.IsAny())).ReturnsAsync(RedisMock.Object); - Configuration = RedisWatcherConfiguration - .Create(ConnectionString, Database) - .WithQuery("get test") - .EnsureThatAsync(results => Task.Factory.StartNew(() => results.Any(x => x == "invalid-value"))) - .WithConnectionProvider(connectionString => RedisConnectionMock.Object) - .Build(); - Watcher = RedisWatcher.Create("Redis watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - RedisCheckResult = CheckResult as RedisWatcherCheckResult; - }; - - It should_invoke_get_database_async_method_only_once = - () => RedisConnectionMock.Verify(x => x.GetDatabaseAsync(Moq.It.IsAny()), Times.Once); - - It should_invoke_query_async_method_only_once = - () => RedisMock.Verify(x => x.QueryAsync( Moq.It.IsAny()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_redis = () => RedisCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_redis_check_result = () => - { - RedisCheckResult.WatcherName.Should().NotBeEmpty(); - RedisCheckResult.WatcherType.Should().NotBeNull(); - RedisCheckResult.ConnectionString.Should().NotBeEmpty(); - RedisCheckResult.Query.Should().NotBeEmpty(); - RedisCheckResult.QueryResult.Should().NotBeEmpty(); - }; - } -} \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Watchers/Server/ServerWatcherTests.cs b/src/Tests/Warden.Tests/Watchers/Server/ServerWatcherTests.cs deleted file mode 100644 index 8c0439d..0000000 --- a/src/Tests/Warden.Tests/Watchers/Server/ServerWatcherTests.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Net; -using System.Threading.Tasks; -using FluentAssertions; -using Moq; -using Warden.Watchers; -using Warden.Watchers.Server; -using Machine.Specifications; -using System.Net.NetworkInformation; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Watchers.Server -{ - public class ServerWatcher_specs - { - protected static ServerWatcher Watcher { get; set; } - protected static ServerWatcherConfiguration Configuration { get; set; } - protected static IWatcherCheckResult CheckResult { get; set; } - protected static ServerWatcherCheckResult ServerWatcherCheckResult { get; set; } - protected static Exception Exception { get; set; } - } - - [Subject("Server watcher initialization")] - public class when_initializing_with_invalid_hostname : ServerWatcher_specs - { - private const string InvalidHostname = "http://www.google.pl"; - private const int Port = 80; - - Establish context = () => { }; - - Because of = () => - { - Exception = Catch.Exception(() => - Configuration = ServerWatcherConfiguration - .Create(InvalidHostname, Port) - .Build()); - }; - - It should_fail = () => Exception.Should().BeOfType(); - It should_have_a_specific_reason = () => Exception.Message.Should().StartWith("The hostname should not contain protocol."); - } - - [Subject("Server watcher initialization")] - public class when_initializing_with_invalid_port : ServerWatcher_specs - { - private const string Hostname = "www.google.pl"; - private const int InvalidPort = -1; - - Establish context = () => { }; - - Because of = () => - { - Exception = Catch.Exception(() => - Configuration = ServerWatcherConfiguration - .Create(Hostname, InvalidPort) - .Build()); - }; - - It should_fail = () => Exception.Should().BeOfType(); - It should_have_a_specific_reason = () => Exception.Message.Should().StartWith("Port number can not be less than 0."); - } - - [Subject("Server watcher initialization")] - public class when_trying_to_provide_null_dns_resolver : ServerWatcher_specs - { - private static readonly string TestHostname = "website.com"; - private static readonly int TestPort = 80; - - Establish context = () => - { - Configuration = ServerWatcherConfiguration - .Create(TestHostname, TestPort) - .WithDnsResolverProvider(() => null) - .Build(); - Watcher = ServerWatcher.Create("Server watcher", Configuration); - }; - - Because of = () => - { - Exception = Catch.Exception(() => Watcher.ExecuteAsync().Await().AsTask.Result); - }; - - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("Server watcher initialization")] - public class when_trying_to_provide_null_tcp_client : ServerWatcher_specs - { - private static readonly string TestHostname = "website.com"; - private static readonly int TestPort = 80; - - Establish context = () => { }; - - Because of = () => - { - Configuration = ServerWatcherConfiguration - .Create(TestHostname, TestPort) - .WithTcpClientProvider(() => null) - .Build(); - Watcher = ServerWatcher.Create("Server watcher", Configuration); - }; - - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("Server watcher initialization")] - public class when_trying_to_provide_null_pinger_provider : ServerWatcher_specs - { - private static readonly string TestHostname = "website.com"; - private static readonly int TestPort = 80; - - Establish context = () => { }; - - Because of = () => - { - Configuration = ServerWatcherConfiguration - .Create(TestHostname) - .WithPingerProvider(() => null) - .Build(); - Watcher = ServerWatcher.Create("Ping Watcher", Configuration); - }; - - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("Server watcher execution")] - public class when_server_accepts_connection : ServerWatcher_specs - { - private static Mock TcpClientMock; - private static Mock DnsResolverMock; - private static Mock PingerMock; - - private static readonly string TestHostname = "website.com"; - private static readonly IPAddress TestIpAddress = new IPAddress(0x2414188f); - private static readonly int TestPort = 80; - - Establish context = () => - { - TcpClientMock = new Mock(); - TcpClientMock.Setup(tcp => tcp.ConnectAsync(Moq.It.IsAny(), - Moq.It.IsAny(), Moq.It.IsAny())) - .Returns(Task.FromResult(string.Empty)); - TcpClientMock.Setup(tcp => tcp.IsConnected).Returns(() => true); - PingerMock = new Mock(); - PingerMock.Setup(x => x.PingAsync(Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(IPStatus.Success); - DnsResolverMock = new Mock(); - DnsResolverMock.Setup(dn => dn.GetIpAddress(Moq.It.IsAny())) - .Returns((string ip) => TestIpAddress); - - Configuration = ServerWatcherConfiguration - .Create(TestHostname, TestPort) - .WithTcpClientProvider(() => TcpClientMock.Object) - .WithDnsResolverProvider(() => DnsResolverMock.Object) - .WithPingerProvider(() => PingerMock.Object) - .WithTimeout(TimeSpan.FromSeconds(1)) - .Build(); - Watcher = ServerWatcher.Create("Server watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - ServerWatcherCheckResult = CheckResult as ServerWatcherCheckResult; - }; - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - - It should_invoke_tcp_client_connect_async_method_only_once = - () => TcpClientMock.Verify(tcp => tcp.ConnectAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_a_specific_description = () => CheckResult.Description.Should().StartWith("Successfully connected to the hostname"); - } - - [Subject("Server watcher execution")] - public class when_server_refuses_connection : ServerWatcher_specs - { - private static Mock TcpClientMock; - private static Mock DnsResolverMock; - private static Mock PingerMock; - - private static readonly string TestHostname = "website.com"; - private static readonly IPAddress TestIpAddress = new IPAddress(0x2414188f); - private static readonly int TestPort = 80; - - Establish context = () => - { - TcpClientMock = new Mock(); - TcpClientMock.Setup(tcp => tcp.ConnectAsync(Moq.It.IsAny(), - Moq.It.IsAny(), Moq.It.IsAny())) - .Returns(Task.FromResult(string.Empty)); - TcpClientMock.Setup(tcp => tcp.IsConnected).Returns(() => false); - DnsResolverMock = new Mock(); - DnsResolverMock.Setup(dn => dn.GetIpAddress(Moq.It.IsAny())) - .Returns(TestIpAddress); - PingerMock = new Mock(); - PingerMock.Setup(x => x.PingAsync(Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(IPStatus.Unknown); - - Configuration = ServerWatcherConfiguration - .Create(TestHostname, TestPort) - .WithTcpClientProvider(() => TcpClientMock.Object) - .WithDnsResolverProvider(() => DnsResolverMock.Object) - .WithPingerProvider(() => PingerMock.Object) - .Build(); - Watcher = ServerWatcher.Create("Server watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - ServerWatcherCheckResult = CheckResult as ServerWatcherCheckResult; - }; - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - - It should_invoke_tcp_client_connect_async_method_only_once = - () => TcpClientMock.Verify(tcp => tcp.ConnectAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_a_specific_reason = () => CheckResult.Description.Should().StartWith("Could not resolve the hostname"); - } - - [Subject("Server watcher execution")] - public class when_hostname_cannot_be_resolved : ServerWatcher_specs - { - private static Mock TcpClientMock; - private static Mock DnsResolverMock; - private static Mock PingerMock; - private static readonly string TestHostname = "website.com"; - private static readonly int TestPort = 80; - - Establish context = () => - { - DnsResolverMock = new Mock(); - DnsResolverMock.Setup(dn => dn.GetIpAddress(Moq.It.IsAny())) - .Returns(IPAddress.None); - TcpClientMock = new Mock(); - TcpClientMock.Setup(tcp => tcp.ConnectAsync(Moq.It.IsAny(), - Moq.It.IsAny(), Moq.It.IsAny())) - .Returns(Task.FromResult(string.Empty)); - TcpClientMock.Setup(tcp => tcp.IsConnected).Returns(() => false); - PingerMock = new Mock(); - PingerMock.Setup(x => x.PingAsync(Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(IPStatus.Success); - - Configuration = ServerWatcherConfiguration - .Create(TestHostname, TestPort) - .WithTcpClientProvider(() => TcpClientMock.Object) - .WithDnsResolverProvider(() => DnsResolverMock.Object) - .WithPingerProvider(() => PingerMock.Object) - .Build(); - Watcher = ServerWatcher.Create("Server watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - ServerWatcherCheckResult = CheckResult as ServerWatcherCheckResult; - }; - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_a_specific_reason = () => CheckResult.Description.Should().StartWith("Could not resolve the hostname"); - } -} diff --git a/src/Tests/Warden.Tests/Watchers/Web/WebWatcherTests.cs b/src/Tests/Warden.Tests/Watchers/Web/WebWatcherTests.cs deleted file mode 100644 index 4b3e30a..0000000 --- a/src/Tests/Warden.Tests/Watchers/Web/WebWatcherTests.cs +++ /dev/null @@ -1,272 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Threading.Tasks; -using FluentAssertions; -using Moq; -using Warden.Watchers; -using Warden.Watchers.Web; -using Machine.Specifications; -using It = Machine.Specifications.It; - -namespace Warden.Tests.Watchers.Web -{ - public class WebWatcher_specs - { - protected static WebWatcher Watcher { get; set; } - protected static WebWatcherConfiguration Configuration { get; set; } - protected static IWatcherCheckResult CheckResult { get; set; } - protected static WebWatcherCheckResult WebCheckResult { get; set; } - protected static Exception Exception { get; set; } - } - - [Subject("Web watcher initialization")] - public class when_initializing_without_configuration : WebWatcher_specs - { - Establish context = () => Configuration = null; - - Because of = () => Exception = Catch.Exception(() => Watcher = WebWatcher.Create("test", Configuration)); - - It should_fail = () => Exception.Should().BeOfType(); - It should_have_a_specific_reason = () => Exception.Message.Should().Contain("Web Watcher configuration has not been provided."); - } - - [Subject("Web watcher initialization")] - public class when_initializing_with_invalid_url_in_configuration : WebWatcher_specs - { - Establish context = () => {}; - - Because of = () => Exception = Catch.Exception(() => - { - Configuration = WebWatcherConfiguration - .Create("invalid url") - .Build(); - }); - - It should_fail = () => Exception.Should().BeOfType(); - } - - [Subject("Web watcher execution")] - public class when_invoking_execute_async_method_with_valid_url_for_get_request : WebWatcher_specs - { - static Mock HttpServiceMock; - static IHttpResponse Response; - - Establish context = () => - { - HttpServiceMock = new Mock(); - Response = HttpResponse.Valid(HttpStatusCode.OK, "Ok", new Dictionary(), string.Empty); - HttpServiceMock.Setup(x => - x.ExecuteAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(Response); - - Configuration = WebWatcherConfiguration - .Create("http://website.com", HttpRequest.Get()) - .WithHttpServiceProvider(() => HttpServiceMock.Object) - .Build(); - Watcher = WebWatcher.Create("Web watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - WebCheckResult = CheckResult as WebWatcherCheckResult; - }; - - It should_invoke_http_service_execute_async_method_only_once = () => - HttpServiceMock.Verify(x => x.ExecuteAsync(Moq.It.IsAny(), - Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_web = () => WebCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_web_check_result = () => - { - WebCheckResult.WatcherName.Should().NotBeEmpty(); - WebCheckResult.WatcherType.Should().NotBeNull(); - WebCheckResult.Uri.Should().NotBeNull(); - WebCheckResult.Request.Should().NotBeNull(); - WebCheckResult.Response.Should().NotBeNull(); - }; - } - - [Subject("Web watcher execution")] - public class when_invoking_ensure_predicate_that_is_valid : WebWatcher_specs - { - static Mock HttpServiceMock; - static IHttpResponse Response; - - Establish context = () => - { - Response = HttpResponse.Valid(HttpStatusCode.OK, "Ok", new Dictionary(), string.Empty); - HttpServiceMock = new Mock(); - HttpServiceMock.Setup(x => - x.ExecuteAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(Response); - - Configuration = WebWatcherConfiguration - .Create("http://website.com", HttpRequest.Get()) - .EnsureThat(response => response.ReasonPhrase == "Ok") - .WithHttpServiceProvider(() => HttpServiceMock.Object) - .Build(); - Watcher = WebWatcher.Create("Web watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - WebCheckResult = CheckResult as WebWatcherCheckResult; - }; - - It should_invoke_http_service_execute_async_method_only_once = () => - HttpServiceMock.Verify(x => x.ExecuteAsync(Moq.It.IsAny(), - Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_web = () => WebCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_web_check_result = () => - { - WebCheckResult.WatcherName.Should().NotBeEmpty(); - WebCheckResult.WatcherType.Should().NotBeNull(); - WebCheckResult.Uri.Should().NotBeNull(); - WebCheckResult.Request.Should().NotBeNull(); - WebCheckResult.Response.Should().NotBeNull(); - }; - } - - [Subject("Web watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_valid : WebWatcher_specs - { - static Mock HttpServiceMock; - static IHttpResponse Response; - - Establish context = () => - { - Response = HttpResponse.Valid(HttpStatusCode.OK, "Ok", new Dictionary(), string.Empty); - HttpServiceMock = new Mock(); - HttpServiceMock.Setup(x => - x.ExecuteAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(Response); - - Configuration = WebWatcherConfiguration - .Create("http://website.com", HttpRequest.Get()) - .EnsureThatAsync(response => Task.Factory.StartNew(() => response.ReasonPhrase == "Ok")) - .WithHttpServiceProvider(() => HttpServiceMock.Object) - .Build(); - Watcher = WebWatcher.Create("Web watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - WebCheckResult = CheckResult as WebWatcherCheckResult; - }; - - It should_invoke_http_service_execute_async_method_only_once = () => - HttpServiceMock.Verify(x => x.ExecuteAsync(Moq.It.IsAny(), - Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_valid_check_result = () => CheckResult.IsValid.Should().BeTrue(); - It should_have_check_result_of_type_web = () => WebCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_web_check_result = () => - { - WebCheckResult.WatcherName.Should().NotBeEmpty(); - WebCheckResult.WatcherType.Should().NotBeNull(); - WebCheckResult.Uri.Should().NotBeNull(); - WebCheckResult.Request.Should().NotBeNull(); - WebCheckResult.Response.Should().NotBeNull(); - }; - } - - [Subject("Web watcher execution")] - public class when_invoking_ensure_predicate_that_is_invalid : WebWatcher_specs - { - static Mock HttpServiceMock; - static IHttpResponse Response; - - Establish context = () => - { - Response = HttpResponse.Valid(HttpStatusCode.OK, "Ok", new Dictionary(), string.Empty); - HttpServiceMock = new Mock(); - HttpServiceMock.Setup(x => - x.ExecuteAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(Response); - - Configuration = WebWatcherConfiguration - .Create("http://website.com", HttpRequest.Get()) - .EnsureThat(response => response.ReasonPhrase == "Not ok") - .WithHttpServiceProvider(() => HttpServiceMock.Object) - .Build(); - Watcher = WebWatcher.Create("Web watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - WebCheckResult = CheckResult as WebWatcherCheckResult; - }; - - It should_invoke_http_service_execute_async_method_only_once = () => - HttpServiceMock.Verify(x => x.ExecuteAsync(Moq.It.IsAny(), - Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_web = () => WebCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_web_check_result = () => - { - WebCheckResult.WatcherName.Should().NotBeEmpty(); - WebCheckResult.WatcherType.Should().NotBeNull(); - WebCheckResult.Uri.Should().NotBeNull(); - WebCheckResult.Request.Should().NotBeNull(); - WebCheckResult.Response.Should().NotBeNull(); - }; - } - - [Subject("Web watcher execution")] - public class when_invoking_ensure_async_predicate_that_is_invalid : WebWatcher_specs - { - static Mock HttpServiceMock; - static IHttpResponse Response; - - Establish context = () => - { - Response = HttpResponse.Valid(HttpStatusCode.OK, "Ok", new Dictionary(), string.Empty); - HttpServiceMock = new Mock(); - HttpServiceMock.Setup(x => - x.ExecuteAsync(Moq.It.IsAny(), Moq.It.IsAny(), Moq.It.IsAny())) - .ReturnsAsync(Response); - - Configuration = WebWatcherConfiguration - .Create("http://website.com", HttpRequest.Get()) - .EnsureThatAsync(response => Task.Factory.StartNew(() => response.ReasonPhrase == "Not ok")) - .WithHttpServiceProvider(() => HttpServiceMock.Object) - .Build(); - Watcher = WebWatcher.Create("Web watcher", Configuration); - }; - - Because of = async () => - { - CheckResult = await Watcher.ExecuteAsync().Await().AsTask; - WebCheckResult = CheckResult as WebWatcherCheckResult; - }; - - It should_invoke_http_service_execute_async_method_only_once = () => - HttpServiceMock.Verify(x => x.ExecuteAsync(Moq.It.IsAny(), - Moq.It.IsAny(), Moq.It.IsAny()), Times.Once); - - It should_have_invalid_check_result = () => CheckResult.IsValid.Should().BeFalse(); - It should_have_check_result_of_type_web = () => WebCheckResult.Should().NotBeNull(); - - It should_have_set_values_in_web_check_result = () => - { - WebCheckResult.WatcherName.Should().NotBeEmpty(); - WebCheckResult.WatcherType.Should().NotBeNull(); - WebCheckResult.Uri.Should().NotBeNull(); - WebCheckResult.Request.Should().NotBeNull(); - WebCheckResult.Response.Should().NotBeNull(); - }; - } -} \ No newline at end of file diff --git a/src/UpgradeLog.htm b/src/UpgradeLog.htm deleted file mode 100644 index ef3b9372d4ba6e345e0cfae67776bdbb08de9c1b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 167470 zcmeHw`F9jKvTpwR=A8K-YMMI({TOVF*}I!L#uzX=*g(V3XO8g>-f(#VX72mb?|t7V zIgpfF<(_g`r;c5fnOZ`jh)~2QrS!l5^K0~%=w9?ZnvE8tchQSzE*eA|(LuBwZAEvY zKSzIxnBo#XgJ>8nMMu$Uw1VGj(SEdxRD^q6^Vwe5RtS(a%Wt5l;_M&h2P3 z+QIiKQtjaX0dlZ3UG@N_OKpSbtEzPe_1wmJGeWHmXUrHPnYof623Qa zhm;KQw}#R$;hJ>aKFNI${e-$$%PR7$sNdU)jwMjSw3<5p{|#wZaeWE(4e?uZ;vm|? zoz>_I?rx&}Of~D|yA(Y^**noXQY_*Bs>(Y#vMzGvE9#y6!Gm8EO&cg>9~6*VzoE-g{wXM+DER-s9XAM zfc);~DRQhM-4asjyo1QjO*wLNu;(XLYE2RQXo%}?ioQEYot7tFhFniZ{}(y#g4Pw3 zKuML7{*J3P)rJA?Q3?k5V{dPQUS6%>=`y%Xso?zq%9<=yJ7t~qmZA9HrBX{fKZ3){ z(PzbL>emkHy$y=bMfaoWlfSFcFO|xsE>I@+PfDDEEzp1WE0##UlcSf=14~L*x4tI#@q{RY?jXfw4<-=R&S#khn&KHEfH z)!M&@l2-7cy;@gPUanXYsozH#EQzfxTh4#0{wpI*TK*q`18f8NFok+uEuc*k+s$4! z`apU~EAJQ!QC15!P-hvMt7$;8m!`nqJ=jt5S$~^5@~fIe82P0|{0{E1H?N?bd*D>H zGSf6zk6E_v&7l_gt6C5HSj)mCH5wm)W<4?vR13(la~R2{PX4aonxp6z+PZ?)m9xNN zq2gBL3VLMP-c~xWuG$l)kG-sVcoaaW`|={c|mtCeM2HA*g{V@iXGB{>4s*Tgh0LXU3uq2cA_0B$Tvg9j zY+-iK-G^1-=N3NIY@i^8? zEhjJKHBtBHB6N=yIL>Lie{_GwQy8yFj}+A5L-Y*sL_Yhh%00wbZen82{%SASj_q`W zL@LUnIukLv*^`v2_IvOcvb=(JZYW=#vjmr;zn0YTs(tnXJT&u6dfb+|JTuaYF3Fta zl8QD&Z*{M8#-)nxoKxDTC6)inY2Lq8|NI~1D)vcwv}T^>%89Qy1#Cj*ZuGCR^AA;f zLo`V2oLD)n1%hC3o}TR>-mYyPJu4$cw4l7AM6pMykxR-8HfiW5t>MWnc&mTKcX^w4 z4kfs=05+9fYt0hu1wGYrmQG|w^XHPqL;CVJfTL3n%SmM2zISb-?q9KRyb{lvw(l5M z-;@kUKiWN9)&ic3SwOe$u6tCss9b+m<^7DZ^aITNYfHzLm*w8XkK7B8#btc7zcB|r zWvRqgR@6EIlX4!ql?d8>MSM@1v+xhdy>+i;F!KbETfp5w|Vu2eG8cN?PtXV0p} z@lqnk7Bf3)$}FdoqUUMe^(F9&D~q^Vfitj-LEU@hWH7%ju3+Mvi_D4MR&vsl>+~?Fi^NR%)b(<$VZiG7g9Ze zRP#tJsEUbCG&-WkL9X`UdM}Qu~Z>rIn>-GjJFL4vD zYNS0GU>1XvlP3L})Ds&bA1%I}VMEU$H&2IZ-V=Gu_ogcq~db)80*xymTl(b^9-$e4T+q?|Mio5cYi#ciC!XRoxy5bNxufW zJqf>Xg!N-p$_wPbt=g{+WsNoH0yNcXj z;8`z1VqW8K7XM#i9n(X2kyG%r)=}^K=n-<=MNM3rw+X7=;r^_udl@C)f*#*TF1GY3 zQe8u7GbnQz?VdzEb9j1;zt5oQE6RU~KKqK=w@~IW%6W%8&r$Aml(>Q4>qxPIXHP)I zBcz{2&JA4cqcl=+6TG{DR7bcogYS#cGyEMX4jtjwSCmAmZ-SZ!p!g!%xPVf=A@yC9 zJ%j6Y{8~r(4{$}Kb_OXvqkgV+eT&~uAahTUhSq2W>GqNPDb^{hpmp=8;U(5VzePK* z;>iv;wG7%`fGXC`IN*kwNgaYW+sLs1YA&NRa{37AcEGh4;0PnO$GG<$wH_hmGt|U6 z%g#TOt zLJnL6l{2c}9wF5t=zI*i=xfa3*%9hI0{>~zzM>4S75NB?=E19XpkNhgX2B1l#J_{a zIncWX`gTFXBIsE`?blK6BhT4!)gJzP}%ejRCN!QE$Q-9y}ENlVDJ4Ia#at4Ao4cp=vdP%Gz9 z|2in12YokiZxQLffm3Vfr*+V+5$FRODuyi}H-YfV!#FJOBzkHMFCUQT;NHK-`^g=G8tRtiv;@%S4`x15E zg_T~$^(@MN3yV6dMjcxFmnd@?Hu*lvJissd*DqnINyQSHg!C!ca za<1bZ{o+-W##n@JGCctW&q4PxzKM0-$FHww!F|~6Rn@9ljO>r`_XXnuJ;R%*m!l>< zHIA-taQy;#mQm*x#sb#)3@yEaTx`cz+`F&pTtII6DMOW#WxYjfe+MPEQ0gr_nFLKo z__dBwxCWZu&prHFRyo(f<5$Q{KW7bfeL}9g$ny~8PpK#5>KE|y8CviZWpK5_5}tF+ z-vUP;qmGwqM4ZQ%$m=26#MtlwxOxk%xuwSH%c%1`%KnVhL|7+5=}n}1h3jMFd8s&k z1$U-F89nSP7)RfLPI`{t)xCFk_6((Mq0eSf+IzI^BA(Ghxv4nA(SIFuZsX1r+BpYW zzM(h1g9=79kMW!LIqI|Lxgv|6+dT4oRZ?|?du#ah4Nuw2Z@|54p#6rDvd6f81MPaL zD4In*8+gvXoW`Bc`2PYte5-03s#@=%rBi4PJs(D@L??FDN5*q{to@GYE(X@lNbc4V z#`6P6Q9vvN9dP9#4Y6?LCye9$jpH-0y;Tqkj#RYWHe#^{Te$$+`w~`l7T-*BANKbu zzGq--@8aGQJo$?6ec0}s%0@5YKHuVG+&l|Qz5u)X3g1K_Zs2MLHuojQAC3~V>TmIk z=+;Y&25(`le^=I@R{wX58uOs(8**O5_ZQSMjoJ^8mXYdn5_#_-a_|ZLg+-Kc5w+6uA)N`@e%cuuP5G`J3~?^!&;@y?3JTK!k%*+ zdx|mOJyO0ydsY=aOStm{Tv-F{oE1DmJBWHR<~l^VL)5*1&lK`p1&z}vg?zn^=hG-- zT9tW-9OTtKq<9K0-au{daD5AO-2|00DE&RkAfu zUO}pNXfH9~`)JdB+~3C4Hqu-{4PTLF8R*^+(+tJT-`$( z=ocKIL`J4x(Y{Ii?IG1r<$D0GeFAN7Q13GCtmDZI@O%Y1o}uo$_>e1GsE=|;YBtda z9Jd+$@1S=WmES|{4?yJ&JpHbCHxFJfqP9=?%!Bqh&~l8j7+XKWlV$w=3`*}IJ(2q* zXEok!!t+{whO_}4p`a90{i4d;WY zG4zMH&kAQ~^`0-E&;qWf|r!2)REyz2qD$W@-B zb8u#f*c<11nL|cl`Q|LS-hYCtNQqu?d?p9QH&PQLu%w7DZ=yva3z>LZu`ZxYu%4p}gE0J#R1@u^a zP1#RsE@lw@_lWg!d6bh27aUGape@|jfjAZ|t#JJ3Tn>z$|FC-_tBwoNdGyu}TCRKj zyy`dVfsv{>S2?qv*Fru2l%;X2sEgFS^3P}%pWfgtSzRRn9{C$)sO&)7Ah=0tQUpL|<_c95%aXbtk|rYGduA6h`6a}j0ewaBkd zYQGEWo}H9@;YS^H^`38eXzNHR+`{-SZKX9#$^yOX18AIW{f6)lILIHCz$AiN9a*=TgQulBnPG7B^1PU4&1R&k0@2Xnhw;BwQiFq}P{m zl#$jAKx3S)e}djWu!>D{Xa=d-eo7Y+oK@H^zI&%7qbOH2HF^~I3wGtpqULYW-#}0L z(+SYPah6`lb2Xj_6|{~-Q22g(5$=`cVVsxLwl|l}MAkB`Q`ngI38wTGVPT5O^E zJUCi*aK#PREZY68t&45F@@-@heHBf0xvnKE*spY(kf(Re+b`*%G`-8V zqxpKrd}Z~&3p+Z1C8jM-wzWMA>q@?{TY8^V>Lk}o(7T{Eaxbw9YHZ?q1CGx5I%r!R z{hRBY8AB5Np(n&S3hrA`yqtX7Q^b1dGXF16SbHfDcmxOQ7d*_ulpAn*JH^f zBtt0v&yQb2^rfcx=ja1`qYr2=|Ne;|Dega2GheF@0k2mJp4|M?I2@)wXcEzKWz zFW~3sAF7OhAXQo#Dd%5E#guRVXwC^}&z@e~5w2|P zQ}fBpmFDx6{vcy*_5^)?{^#r^PaxUC6=xjGI483f`C833^3zNo80%cu+K{Gvi<9?M z&(51UcFxc9#1(C=dBt@VT;0##dQY9Qr=!$48-?fL46urU^DeZ_J16u_DSC)?AK^Le zHvN6Bb~E$ba<&ckkdM>+T+IgWD>);|vxqYESu4yHf2w(MCAH4@t~0t;&hzRyDe{f7 zsJ}PVH_vv_zw``QoVpjv=8KPI=C|xol=ZmjNad(%cC}ZnHYwc8VjtOoxt8|=K^to45^iEFP0rFwfP^T;xBS>=9?KSdd zs5brioS4qr)aUpZNKcX6pN>vNccAKTz|IS0|spsy=Xu6-Xo|WnEyfQ++ z%h)B~*<)DKdL6e=dM6{IpSth!o|ozWQRM^~kiM7i?qpz5S#-XuMeAg)%Ji?BEA*!H zqI`GPo3_8l{l^r)ThgHy@`d;vi(S>oB~?Pfhgo4dul!mA#7g?1|@68_)>-s0dX ze%xV#Ske%)ru;Umo`;wh&-E~XtUx!_Kn$cyq%%IbL=(O7_ke9y)Qv6~j*qXNyaoD8PgTEB#C?DD+!WWb7SWo#{O#&cUd^L5Dld1?ulDsT zkN@MMZCOY#<0}1bFxTiOwX9gaGTN0@Vq8zM(zz5@%N4Y$X{{>OTjQ@y51~a|b5DF_ zvy?u$IlI*;x9;LP<>m`o)ty$koF9L^dW!gILG3P7W{fhqy45FBZ*g5Rd4e8wr$>hC z8KwQPuf@L%*p0`_liq~FTtKvC>ZgrRkwkXdGMW%CB`)Lf=Z2!a-bAFuliMuoCokjJVi_{$1 zmt;b{vF64xdVdbd(YF5B)D_ViJAKfXF7(Cb`1tC{D~vLF7y2ZYl^knK>UQmt_nteA&YxB}dZjYC2>K!NcVU^Q7c(&K1 zXi8p9iRtoeo(CCjM}`fDPq#GN7>vlTeXpFvx^vUadp33-@^jZf?Fr~!r5!5Qmy#p& zpxz~nvMf6R>pfoej>`PKfs?tD`zFVC)zkYcx%&`vZ(Vyg<#--*Mvv_2#Zy7K8ytI+ z^|Jo>-p=lx-5P(@d*sR)jof)RUKjUQ)w}F&;MDD8dtA!(x)V7&QO>rA?~xp@LsLDi zsCN0ueR9q2)bV_FxvzjMAFI)pyG5t(67B9W?DAt4V>QnRV0+`c0K5AcXYc*&rqh`A`>t{f_<=Wh5sZ-yu;PqgCc z8{D&g2`i#_4(JZ9cd##d{Im$Yw>{TUajuU$C7IlmDXyuCpSD5i&*P@XaSUW{(aP|>nQ!WpU2QRRG?#CEvm~pC-F5rOU%SgQ1j#G%?GT=a%+J!E zat!6EAs>~EpuOctbqH?KYoXnmRcG_XJr_4-{eYDFDE9+S`_}Kou>?1bj2z9`mLMbX z-NmYp&2gJdP2Yqy+DCsLoJd8M^c3&W;(F^^Q&-cHBa5756>o(fBa2XXc1ITBK)WML zJi3ef&GCI^jm2iHlz!TRe!?+Cd_#^5Zk!V@*Y4Bn5c z=fjieidr1!G0&*g-jW`%IN~S0lZjOSL{7G{zteq{Q4&Rt&^n5p6mLH+Sy|~=YY_>{ z${!@noI$jWelTa8<>3SQl9t75KO`8%1c{R^76_E($~E7VwP9O+SsOjB@H}3(yl9xJekvUs?1vmrnL!ge;vHk=vX;itQd7N7g4Tkp)ZNK zW%Hp)jNjmJb}P@K)VV0>MDz(VN^9kZ)MZiEywqjY6r`>hTeq&z4`TLPn62wu%F?N6 zLaNeB4pP*N6xr4~d!(phyST1o4Ij>BbDsPFqb5&+K2*Pd!POP~{ROjk10b*ThC+_w zydu9|D9=YuOm|O=cjs<2CTY+85i!-M>4lQBd$z><49i1GcwVYLfo>l&iM+#kY~tlx z=v|l2p_-kY`jJo1MH+gtQ{P8O&0WyY5#%d+3*suEiX+E)jSjPs(&_BC0S&8sHxgwxpWGCsWhmVm2o zdL2?aQd>{2gKg5MG@BJC$+?MkQo@`w&rw!cM?YYy2KfBZi96I38UE|QM z1p0x`2r}vq9_?}|IX?J;OS^Q|!)K%y{Ku!cH{-5CB^i&D#hy*>CUIp`YQT)+n6crF zANHnuJlJrcKU-pGsAngHd+pi@y<1naYvT+D{Khd1ok?l&0e?006~hNj`nnNCf4He> zL!CDFhfg#^e}CwNp+D#@ceF_Eu2)tr#|1kyl9AmaKlIK&%+K&HXjM~MRb;i8;d|W? zu?og!YWEF4Gn55vEMQ|zV`E0T{D?yZap?~CG8{-o7F}UlhK71^sBo{{IJEA1%C~Bd ziWT5h$3U&*q|{BdpMP2ODzB`ju&lf~0t&5dW4JRyC z_F2XUi*d*g+al;y8@8nwACkCD^Ro}dD5+;lgp=*sl6p8`F+TVbHx#2bDL>8Pepyt+ z5v#0puHCMdt8Sdo1m2g`zG^M1mdoZt6WD-nZR!Hw%WAVLr@;o$(sCr?`noKhRg+@> z@Vu_t=cCT{iRWeUJ?J9Ozt}>QliZ6ni)U4J(Z%nwN_Tt29*3%6@cFo1F&f&#>$2*v z#^He11-!00UY8|{u0Hw^OADG5V(EjZUMww~Y&Vu}3YU8bJdUSH&ERjdGBW3u(lj>b zmLAZ#RrvM$z*7&`_mU(C*JPp}E@I=rmtp{hKOBXZ|T zP<9Lb)L%c*JC~@Ny+gIuQRk3kLOLEy57GZIGt%vT^{%m z-#6EuesMX|j-c~RuA?)2%|@!KtjO_Co3oHD|MWDA(x8DwaVaC!Vbo>B_kJjC}7uGV1nwqX5M z@r?cT=jczkoBRkD+l`N#!q>R--44!mdVp4L;+r0_jx9HE9&-HD;B1sFUQW|kTfF>$ zxTPU(aW45`R|GNY)~>{Pk@V)eMBn1noMj9y&I|ve@;JpwS@I2!i&I=2k&5RW4{R>p zs%H4%NBrMT+xkTe;%y2xf{}N#@4?1-JdP+{@izLZ%YGtyalQuq>_R__VwmyXsXK;O zMf&1&_>A|(X$`1fK>gZ4{o-=wM~p70Rfy3I7FI7t7ml759B@nRX!p4W0w^UkkNru> z0rg8q{e(Y$*pj~RKH)+Vo#__o6FTbI58-0F_M@$Jb_w93xwGdEiUTFa1-uJ$++#(vH)B1_-UE zOXsuDpwqj~&erCv*7>KWS(FA145O~z!N$mS-BGtX`X)BcZ`@6&42WAm+}c6hM8f=t zj|Ca(8fz0SBt4$f7#|B4+l`N#T4%S2b7nUY(Q=0~ddF4P*x6+?jj`Ef2b3)hWwSZt zhaC}ws9QT?^Pyi$VpDRKu{N6z{zu+6wMqH$4R5olEsoCEx$1iVeqe5Pi|X^ik9fY> zHuW3%+ieLppxJeDHgCsqja;$z`KYsgqHs1pgD$qIi$$?UyGQDd$5qidn+BipIGfIZ z$OS~M4MfhCF+XByL6br(y*q~IMJ!@P2-lztM__LzT{V2o zGMY!#O>N_kcbT^O;zJvXl6~DQZe?nUV=YCV)b((iK%9!uncX(K1x>`A%~8_@%44Vv zlE1H3c<$gtAj1{^Fc_OQHzu{8WT6$^Nq80oL8|E=4zYrG9iAe!Zk+6SK4M`cv^`Y9 z)RArT1J)3*hU!>@kuX1EjyCZG)7GRP>Tk>;9Pw$rj^X5ldZT0oUWR_RWYkVrc{%H1 z2T582nn3I($rnF#y&HTX+4^p^KUx1-!XT2Z_b)a}(wLNx?)};%RoOmZGOdjS^!1L5 zvGrvrFO$}8WmnN)lGjx!?lyW%(j7GMj)RV5ArMK)F#=#{o*)DdIGW&kew!woup*>5&sFY(Z<>l<9jAspY-nAM1PX?*Ngvz zYd+yYwC)GkS7ZaT0Q(AYxTp3i8MP}?cD`y@PHlW@fN7-%n#gERWFew|&;y>}4;|N0h`9vi4w0O$8esmM7S>o*|PJQu|b~~Gh zTDzvX3lu2cCL>Ql7vsDsE_wc;Ky9?8Z=LEB4T|$K=#4oCGtQebdc(YCg<8BM!)4pH zH;)Bn*V`Tv6tA;5*8&<8(4gvQP+abej`UBCtJ2R#q;@0c~<6BfCX@=$&84lgqoHRZVFXqmDc*%H@0A5ix&t(x?c?CtS+q zOF*XrI@KgPB=rh>yv0h7wGj<=(^UB zvx!Sd>wWgXg~p_W^p8ggZAIc=Nn6+J?hA(!`m46JuQ<3a-F@LsLU+*3YIu|IFB_Su zvI?Vr?aM-P`q!^4%7O;1BD$D}(hw1m(lEL$fk$_u@|cov&@Vhms0vt8z>=E9l0>rn zh!+J33Gw3i;YTmj8*n^ndmra%(>^adJL46@lG00Q3Rg-mJzz{W#+1$@KkP@hcvCtj zlD=0L*i$+!XAy@==Y+p;Z#un6De4=aN~d!)ev_W>bmCU&ZE1oB{lwetwWpsbJ-t0a z_jyu9o%fT{`8p0*SlO2OrKf&jWa+#N+Siu$jar|T-XC>G-m;ilIu$s8OfQeZ}E+ zAJn10FMQ0VKj?1NH>Kioyr#*20LuUY_pv>zR*|78&*J8x4Ml3iv%k!%#n=8PY9 zK@gE{?1J6?ek_AcK|R|boNL!MG>s+M?f2K;wy8|YN#A&qP2Fge#ZFz<>+WZ5lih;q z?d>P-ZHD%KuqB)JpsUsPQ@43I4hU1R_V}P{exXb@--0eRp-ZE%CY$4R$Gx&>lU=t@ zc#}<6K%4^N)Fk3$%a$LprJyGvwj9rW)87JdDu2G8&easwq)Q7ZlZ`S-zi<`s0alg` zuy%h7Yk~PTBrVQ7u8G3V(KkrIs_J{arg0C~OSpR* z(y^oDZWVG-RW?P=c2Fi|kuo;Q6U~x}zHuZ?*JwmVr>pBj_k$f(Z(~0(Y;}73!H6`y z{zkN#zNAI=Mfb8$iqrFcn@DU{OZwHLEUJRGr0sL=yS5Y?Y3q(uWzinZHJ@-EO;JF2 z0>aZI!lR|Cy6-Ie;4~4}b&Ks}*~QZm*9o`UT`N#_9Z?bVhH0u|HOzaqkr~b5s)f}XjvoB_*hMwO_CZ$8qFBm3<3hUh&+?{%VgO4eD3)!EMEXzHi$?{6GFfw^>^A7)$i z^mD_=ZbBdBUrbr)S3`hs>WVf5z;JbePTJIed`<_aksrM1~~cPaV(qXU)pbe(4`oSGc{Q-dp2t-{3!bp=Jag9Xa?W_lPN6n;X+ZHNexLhx;5$^QA zPT&A*_&4B<>;pMAII}?{?B``L2s__tMIE}F&riNl@eDYTE7`;77497?w2|Yd&EtW3 zA7fp;t-&`zxB{Q!nmr>h1fKNg=ufym`oq4Kxd#5)SF;YISDsKalXAqn#ifU-gUp!s tc-&qz@8Xn~8FIECNtr~nsY(UnwA Warden is an open source library built to solve the problem of monitoring the resources. - 1.3.2 + 2.0.0-beta-1 Piotr Gankiewicz - net461;netstandard1.6 + netstandard2.0 Warden Warden Warden https://getwarden.net https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 false false false @@ -19,29 +18,4 @@ false - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Watchers/Warden.Watchers.Disk/DirectoryInfo.cs b/src/Watchers/Warden.Watchers.Disk/DirectoryInfo.cs deleted file mode 100644 index 3f90978..0000000 --- a/src/Watchers/Warden.Watchers.Disk/DirectoryInfo.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace Warden.Watchers.Disk -{ - /// - /// Details of the performed directory analysis. - /// - public class DirectoryInfo - { - /// - /// Name of the directory e.g. Images. - /// - public string Name { get; } - - /// - /// Full path of the directory e.g. D:\Images. - /// - public string Path { get; } - - /// - /// Number of files existing in the directory. - /// - public int FilesCount { get; } - - /// - /// Size in bytes. - /// - public long Size { get; } - - /// - /// Flag determining whether the directory exists. - /// - public bool Exists { get; } - - public DirectoryInfo(string name, string path, int filesCount, long size, bool exists) - { - Name = name; - Path = path; - FilesCount = filesCount; - Size = size; - Exists = exists; - } - - /// - /// Factory method for creating a new instance of DirectoryInfo for the non-existing directory. - /// - /// Name of the directory e.g. Images - /// Full path of the directory e.g. D:\Images - /// Instance of DirectoryInfo. - public static DirectoryInfo NotFound(string name, string path) - => new DirectoryInfo(path, name, 0, 0, false); - - /// - /// Factory method for creating a new instance of DirectoryInfo for the existing directory. - /// - /// Name of the directory e.g. Images - /// Full path of the directory e.g. D:\Images - /// Number of files existing in the directory. - /// Size in bytes. - /// Instance of DirectoryInfo. - public static DirectoryInfo Create(string name, string path, int filesCount, long sizeBytes) - => new DirectoryInfo(path, name, filesCount, sizeBytes, true); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Disk/DiskCheck.cs b/src/Watchers/Warden.Watchers.Disk/DiskCheck.cs deleted file mode 100644 index 5b22522..0000000 --- a/src/Watchers/Warden.Watchers.Disk/DiskCheck.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Collections.Generic; - -namespace Warden.Watchers.Disk -{ - /// - /// Details of the performed disk analysis. - /// - public class DiskCheck - { - /// - /// Total free space in bytes available on disk. - /// - public long FreeSpace { get; } - - /// - /// Total used space in bytes on disk. - /// - public long UsedSpace { get; } - - /// - /// Total space in bytes on disk. - /// - public long TotalSpace => UsedSpace + FreeSpace; - - /// - /// Collection of partitions that have been checked. - /// - public IEnumerable Partitions { get; } - - /// - /// Collection of directories that have been checked. - /// - public IEnumerable Directories { get; } - - /// - /// Collection of files that have been checked. - /// - public IEnumerable Files { get; } - - protected DiskCheck(long freeSpace, long usedSpace, - IEnumerable partitions, - IEnumerable directories, - IEnumerable files) - { - FreeSpace = freeSpace; - UsedSpace = usedSpace; - Partitions = partitions; - Directories = directories; - Files = files; - } - - /// - /// - /// - /// Total free space in bytes available on disk. - /// Total used space in bytes on disk. - /// Collection of partitions that have been checked. - /// Collection of directories that have been checked. - /// Collection of files that have been checked. - /// - public static DiskCheck Create(long freeSpace, long usedSpace, - IEnumerable partitions, - IEnumerable directories, - IEnumerable files) - => new DiskCheck(freeSpace, usedSpace, partitions, directories, files); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Disk/DiskWatcher.cs b/src/Watchers/Warden.Watchers.Disk/DiskWatcher.cs deleted file mode 100644 index e259c48..0000000 --- a/src/Watchers/Warden.Watchers.Disk/DiskWatcher.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Threading.Tasks; - -namespace Warden.Watchers.Disk -{ - /// - /// DiskWatcher designed for disk & file monitoring. - /// - public class DiskWatcher : IWatcher - { - private readonly DiskWatcherConfiguration _configuration; - public string Name { get; } - public string Group { get; } - public const string DefaultName = "Disk Watcher"; - - protected DiskWatcher(string name, DiskWatcherConfiguration configuration, string group) - { - if (string.IsNullOrEmpty(name)) - throw new ArgumentException("Watcher name can not be empty."); - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Disk Watcher configuration has not been provided."); - } - - Name = name; - _configuration = configuration; - Group = group; - } - - public async Task ExecuteAsync() - { - try - { - var diskChecker = _configuration.DiskCheckerProvider(); - var diskCheck = await diskChecker.CheckAsync(_configuration.PartitionsToCheck, - _configuration.DirectoriesToCheck, _configuration.FilesToCheck); - var isValid = true; - - if (_configuration.EnsureThatAsync != null) - isValid = await _configuration.EnsureThatAsync?.Invoke(diskCheck); - - isValid = isValid && (_configuration.EnsureThat?.Invoke(diskCheck) ?? true); - var description = $"Disk check has returned {(isValid ? "valid" : "invalid")} result for " + - $"{_configuration.PartitionsToCheck.Count()} partition(s), " + - $"{_configuration.DirectoriesToCheck.Count()} directory/ies " + - $"and {_configuration.FilesToCheck.Count()} file(s)."; - - return DiskWatcherCheckResult.Create(this, isValid, diskCheck, description); - } - catch (IOException exception) - { - return DiskWatcherCheckResult.Create(this, false, null, exception.Message); - } - catch (Exception exception) - { - throw new WatcherException("There was an error while trying to check disk.", - exception); - } - } - - /// - /// Factory method for creating a new instance of DiskWatcher with default name of Disk Watcher. - /// - /// Optional lambda expression for configuring the DiskWatcher. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of DiskWatcher. - public static DiskWatcher Create(Action configurator = null, - string group = null) - { - var config = new DiskWatcherConfiguration.Builder(); - configurator?.Invoke((DiskWatcherConfiguration.Default) config); - - return Create(DefaultName, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of DiskWatcher. - /// - /// Name of the DiskWatcher. - /// Optional lambda expression for configuring the DiskWatcher. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of DiskWatcher. - public static DiskWatcher Create(string name, - Action configurator = null, - string group = null) - { - var config = new DiskWatcherConfiguration.Builder(); - configurator?.Invoke((DiskWatcherConfiguration.Default) config); - - return Create(name, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of DiskWatcher with default name of Disk DiskWatcher. - /// - /// Configuration of DiskWatcher. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of DiskWatcher. - public static DiskWatcher Create(DiskWatcherConfiguration configuration, string group = null) - => Create(DefaultName, configuration, group); - - /// - /// Factory method for creating a new instance of DiskWatcher. - /// - /// Name of the DiskWatcher. - /// Configuration of DiskWatcher. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of DiskWatcher. - public static DiskWatcher Create(string name, DiskWatcherConfiguration configuration, - string group = null) - => new DiskWatcher(name, configuration, group); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Disk/DiskWatcherCheckResult.cs b/src/Watchers/Warden.Watchers.Disk/DiskWatcherCheckResult.cs deleted file mode 100644 index b062cc2..0000000 --- a/src/Watchers/Warden.Watchers.Disk/DiskWatcherCheckResult.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace Warden.Watchers.Disk -{ - /// - /// Custom check result type for DiskWatcher. - /// - public class DiskWatcherCheckResult : WatcherCheckResult - { - public DiskCheck DiskCheck { get; } - - protected DiskWatcherCheckResult(DiskWatcher watcher, bool isValid, string description, - DiskCheck diskCheck) - : base(watcher, isValid, description) - { - DiskCheck = diskCheck; - } - - /// - /// Factory method for creating a new instance of DiskWatcherCheckResult. - /// - /// Instance of DiskWatcher. - /// Flag determining whether the performed check was valid. - /// Instance of DiskCheck. - /// Custom description of the performed check. - /// Instance of DiskWatcherCheckResult. - public static DiskWatcherCheckResult Create(DiskWatcher watcher, bool isValid, - DiskCheck diskCheck, string description = "") - => new DiskWatcherCheckResult(watcher, isValid, description, diskCheck); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Disk/DiskWatcherConfiguration.cs b/src/Watchers/Warden.Watchers.Disk/DiskWatcherConfiguration.cs deleted file mode 100644 index 904bb80..0000000 --- a/src/Watchers/Warden.Watchers.Disk/DiskWatcherConfiguration.cs +++ /dev/null @@ -1,183 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Warden.Watchers.Disk -{ - /// - /// Configuration of the DiskWatcher. - /// - public class DiskWatcherConfiguration - { - /// - /// Collection of partition names that should be checked. - /// - public IEnumerable PartitionsToCheck { get; protected set; } - - /// - /// Collection of directory paths that should be checked. - /// - public IEnumerable DirectoriesToCheck { get; protected set; } - - /// - /// Collection of file paths that should be checked. - /// - public IEnumerable FilesToCheck { get; protected set; } - - /// - /// Predicate that has to be satisfied in order to return the valid result. - /// - public Func EnsureThat { get; protected set; } - - /// - /// Async predicate that has to be satisfied in order to return the valid result. - /// - public Func> EnsureThatAsync { get; protected set; } - - /// - /// Custom provider for the IDiskChecker. - /// - public Func DiskCheckerProvider { get; protected set; } - - protected internal DiskWatcherConfiguration() - { - DiskCheckerProvider = () => new DiskChecker(); - PartitionsToCheck = Enumerable.Empty(); - DirectoriesToCheck = Enumerable.Empty(); - FilesToCheck = Enumerable.Empty(); - } - - /// - /// Factory method for creating a new instance of fluent builder for the DiskWatcherConfiguration. - /// - public static Builder Create() => new Builder(); - - /// - /// Fluent builder for the DiskWatcherConfiguration. - /// - public abstract class Configurator : WatcherConfigurator - where T : Configurator - { - protected Configurator() - { - Configuration = new DiskWatcherConfiguration(); - } - - protected Configurator(DiskWatcherConfiguration configuration) : base(configuration) - { - } - - public T WithPartitionsToCheck(params string[] partitions) - { - if (partitions == null || partitions.Any() == false || partitions.Any(string.IsNullOrWhiteSpace)) - throw new ArgumentException("Partitions to check can not be empty.", nameof(partitions)); - - Configuration.PartitionsToCheck = partitions; - - return Configurator; - } - - public T WithDirectoriesToCheck(params string[] directories) - { - if (directories == null || directories.Any() == false || directories.Any(string.IsNullOrWhiteSpace)) - throw new ArgumentException("Directories to check can not be empty.", nameof(directories)); - - Configuration.DirectoriesToCheck = directories; - - return Configurator; - } - - public T WithFilesToCheck(params string[] files) - { - if (files == null || files.Any() == false || files.Any(string.IsNullOrWhiteSpace)) - throw new ArgumentException("Files to check can not be empty.", nameof(files)); - - Configuration.FilesToCheck = files; - - return Configurator; - } - - /// - /// Sets the predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the DiskWatcherConfiguration. - public T EnsureThat(Func ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThat = ensureThat; - - return Configurator; - } - - /// - /// Sets the async predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the DiskWatcherConfiguration. - public T EnsureThatAsync(Func> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that async predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThatAsync = ensureThat; - - return Configurator; - } - - /// - /// Sets the custom provider for the IDiskChecker. - /// - /// Custom provider for the IDiskChecker. - /// Lambda expression returning an instance of the IDiskChecker. - /// Instance of fluent builder for the DiskWatcherConfiguration. - public T WithDiskCheckerProvider(Func diskCheckerProvider) - { - if (diskCheckerProvider == null) - throw new ArgumentNullException(nameof(diskCheckerProvider), "Disk checker provider can not be null."); - - Configuration.DiskCheckerProvider = diskCheckerProvider; - - return Configurator; - } - } - - /// - /// Default DiskWatcherConfiguration fluent builder used while configuring watcher via lambda expression. - /// - public class Default : Configurator - { - public Default(DiskWatcherConfiguration configuration) : base(configuration) - { - SetInstance(this); - } - } - - /// - /// Extended DiskWatcherConfiguration fluent builder used while configuring watcher directly. - /// - public class Builder : Configurator - { - public Builder() : base() - { - SetInstance(this); - } - - /// - /// Builds the DiskWatcherConfiguration and return its instance. - /// - /// Instance of DiskWatcherConfiguration. - public DiskWatcherConfiguration Build() => Configuration; - - /// - /// Operator overload to provide casting the Builder configurator into Default configurator. - /// - /// Instance of extended Builder configurator. - /// Instance of Default builder configurator. - public static explicit operator Default(Builder builder) => new Default(builder.Configuration); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Disk/Extensions.cs b/src/Watchers/Warden.Watchers.Disk/Extensions.cs deleted file mode 100644 index e5f34e6..0000000 --- a/src/Watchers/Warden.Watchers.Disk/Extensions.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using Warden.Core; - -namespace Warden.Watchers.Disk -{ - /// - /// Custom extension methods for the Disk watcher. - /// - public static class Extensions - { - /// - /// Extension method for adding the Disk watcher to the the WardenConfiguration with the default name of Disk Watcher. - /// - /// Instance of the Warden configuration builder. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddDiskWatcher( - this WardenConfiguration.Builder builder, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(DiskWatcher.Create(group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Disk watcher to the the WardenConfiguration.. - /// - /// Instance of the Warden configuration builder. - /// Name of the DiskWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddDiskWatcher( - this WardenConfiguration.Builder builder, - string name, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(DiskWatcher.Create(name, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Disk watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Lambda expression for configuring the DiskWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddDiskWatcher( - this WardenConfiguration.Builder builder, - Action configurator, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(DiskWatcher.Create(configurator, group), hooks, interval); - - return builder; - } - - - /// - /// Extension method for adding the Disk watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the DiskWatcher. - /// Lambda expression for configuring the DiskWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddDiskWatcher( - this WardenConfiguration.Builder builder, - string name, - Action configurator, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(DiskWatcher.Create(name, configurator, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Disk watcher to the the WardenConfiguration with the default name of Disk Watcher. - /// - /// Instance of the Warden configuration builder. - /// Configuration of DiskWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddDiskWatcher( - this WardenConfiguration.Builder builder, - DiskWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(DiskWatcher.Create(configuration, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Disk watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the DiskWatcher. - /// Configuration of DiskWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that DiskWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddDiskWatcher( - this WardenConfiguration.Builder builder, string name, - DiskWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(DiskWatcher.Create(name, configuration, group), hooks, interval); - - return builder; - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Disk/FileInfo.cs b/src/Watchers/Warden.Watchers.Disk/FileInfo.cs deleted file mode 100644 index 1778cfb..0000000 --- a/src/Watchers/Warden.Watchers.Disk/FileInfo.cs +++ /dev/null @@ -1,82 +0,0 @@ -namespace Warden.Watchers.Disk -{ - /// - /// Details of the performed file analysis. - /// - public class FileInfo - { - /// - /// Name of the file e.g. Image.jpg. - /// - public string Name { get; } - - /// - /// Full path of the file e.g. D:\Images\Image.jpg. - /// - public string Path { get; } - - /// - /// Extension of the file e.g. jpg. - /// - public string Extension { get; } - - /// - /// Flag determining whether the file exists. - /// - public bool Exists { get; } - - /// - /// Size in bytes. - /// - public long Size { get; } - - /// - /// Name of the partition in which the file exists/should exist e.g. D:\. - /// - public string Partition { get; } - - /// - /// Full path of the directory in which the file exists/should exist e.g. D:\Images. - /// - public string Directory { get; } - - protected FileInfo(string path, string name, string extension, - bool exists, long size, string partition, string directory) - { - Path = path; - Name = name; - Partition = partition; - Extension = extension; - Exists = exists; - Size = size; - Partition = partition; - Directory = directory; - } - - /// - /// - /// - /// Name of the file e.g. Image.jpg. - /// Full path of the file e.g. D:\Images\Image.jpg. - /// Extension of the file e.g. jpg. - /// Name of the partition in which the file should exist e.g. D:\. - /// Full path of the directory in which the file exists e.g. D:\Images. - /// - public static FileInfo NotFound(string name, string path, string extension, string partition, string directory) - => new FileInfo(name, path, extension, false, 0, partition, directory); - - /// - /// - /// - /// Name of the file e.g. Image.jpg. - /// Full path of the file e.g. D:\Images\Image.jpg. - /// Extension of the file e.g. jpg. - /// Size in bytes. - /// Name of the directory in which the file exists e.g. D:\. - /// Full path of the directory in which the file exists e.g. D:\Images. - /// - public static FileInfo Create(string name, string path, string extension, long sizeBytes, - string partition, string directory) - => new FileInfo(name, path, extension, true, sizeBytes, partition, directory); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Disk/IDiskChecker.cs b/src/Watchers/Warden.Watchers.Disk/IDiskChecker.cs deleted file mode 100644 index ad8eb59..0000000 --- a/src/Watchers/Warden.Watchers.Disk/IDiskChecker.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; - -namespace Warden.Watchers.Disk -{ - /// - /// Custom disk checker for disk analysis. - /// - public interface IDiskChecker - { - Task CheckAsync(IEnumerable partitions = null, - IEnumerable directories = null, IEnumerable files = null); - } - - /// - /// Default implementation of the IDiskChecker based on System.IO. - /// - public class DiskChecker : IDiskChecker - { - public async Task CheckAsync(IEnumerable partitions = null, - IEnumerable directories = null, IEnumerable files = null) - => await Task.Factory.StartNew(() => DiskCheck.Create(GetFreeSpace(), GetUsedSpace(), - CheckPartitions(partitions), CheckDirectories(directories), CheckFiles(files))); - - private static long GetFreeSpace() - => DriveInfo.GetDrives().Where(x => x.IsReady).Sum(x => x.TotalFreeSpace); - - private static long GetUsedSpace() - => DriveInfo.GetDrives().Where(x => x.IsReady).Sum(x => x.TotalSize) - GetFreeSpace(); - - private IEnumerable CheckPartitions(IEnumerable partitions = null) - => partitions?.Select(CheckPartition) ?? Enumerable.Empty(); - - private PartitionInfo CheckPartition(string partition) - { - if (string.IsNullOrWhiteSpace(partition)) - return null; - - if (partition.EndsWith(":")) - partition += @"\"; - else if (!partition.EndsWith(@":\")) - partition += @":\"; - - var name = partition.ToUpperInvariant(); - var drives = DriveInfo.GetDrives(); - var info = drives.FirstOrDefault(x => x.Name.Equals(name)); - - return info == null - ? PartitionInfo.NotFound(name) - : PartitionInfo.Create(info.Name, info.TotalSize - info.TotalFreeSpace, info.TotalFreeSpace); - } - - private IEnumerable CheckDirectories(IEnumerable directories = null) - => directories?.Select(CheckDirectory) ?? Enumerable.Empty(); - - private DirectoryInfo CheckDirectory(string directory) - { - if (string.IsNullOrWhiteSpace(directory)) - return null; - - var info = new System.IO.DirectoryInfo(directory); - if (!info.Exists) - return DirectoryInfo.NotFound(info.Name, info.FullName); - - var files = info.GetFiles(); - - return DirectoryInfo.Create(info.Name, info.FullName, files.Length, files.Sum(x => x.Length)); - } - - private IEnumerable CheckFiles(IEnumerable files = null) - => files?.Select(CheckFile) ?? Enumerable.Empty(); - - private FileInfo CheckFile(string file) - { - if (string.IsNullOrWhiteSpace(file)) - return null; - - var partition = file.Contains(":") ? $@"{file.Split(':').First().ToUpperInvariant()}:\" : string.Empty; - var info = new System.IO.FileInfo(file); - if (!info.Exists) - return FileInfo.NotFound(info.Name, info.FullName, info.Extension, partition, info.DirectoryName); - - return FileInfo.Create(info.Name, info.FullName, info.Extension, info.Length, partition, - info.DirectoryName); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Disk/PartitionInfo.cs b/src/Watchers/Warden.Watchers.Disk/PartitionInfo.cs deleted file mode 100644 index d5dda26..0000000 --- a/src/Watchers/Warden.Watchers.Disk/PartitionInfo.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace Warden.Watchers.Disk -{ - /// - /// Details of the performed partition analysis. - /// - public class PartitionInfo - { - /// - /// Name of the partition e.g. C:\. - /// - public string Name { get; } - - /// - /// Total used space in bytes on disk by partition. - /// - public long UsedSpace { get; } - - /// - /// Total free space in bytes available on partition. - /// - public long FreeSpace { get; } - - /// - /// Total space in bytes on partition. - /// - public long TotalSpace => UsedSpace + FreeSpace; - - /// - /// Flag determining whether the partition exists. - /// - public bool Exists { get; } - - public PartitionInfo(string name, long usedSpace, long freeSpace, bool exists) - { - Name = name; - UsedSpace = usedSpace; - FreeSpace = freeSpace; - Exists = exists; - } - - /// - /// Factory method for creating a new instance of PartitionInfo for the non-existing partition. - /// - /// Name of the partition e.g. C:\. - /// Instance of PartitionInfo. - public static PartitionInfo NotFound(string name) - => new PartitionInfo(name, 0, 0, false); - - /// - /// Factory method for creating a new instance of PartitionInfo for the existing partition. - /// - /// Name of the partition e.g. C:\. - /// Total used space in bytes on disk by partition. - /// Total free space in bytes available on disk. - /// Instance of PartitionInfo. - public static PartitionInfo Create(string name, long usedSpace, long freeSpace) - => new PartitionInfo(name, usedSpace, freeSpace, true); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Disk/Properties/AssemblyInfo.cs b/src/Watchers/Warden.Watchers.Disk/Properties/AssemblyInfo.cs deleted file mode 100644 index dbd03d4..0000000 --- a/src/Watchers/Warden.Watchers.Disk/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Watchers.Disk")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Watchers.Disk")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("774e4a5c-835b-4e79-8514-f512d32da2d7")] diff --git a/src/Watchers/Warden.Watchers.Disk/Warden.Watchers.Disk.csproj b/src/Watchers/Warden.Watchers.Disk/Warden.Watchers.Disk.csproj deleted file mode 100644 index d743b43..0000000 --- a/src/Watchers/Warden.Watchers.Disk/Warden.Watchers.Disk.csproj +++ /dev/null @@ -1,39 +0,0 @@ - - - - Warden watcher for Disk. - 1.3.1 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Watchers.Disk - Warden.Watchers.Disk - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - diff --git a/src/Watchers/Warden.Watchers.MongoDb/Extensions.cs b/src/Watchers/Warden.Watchers.MongoDb/Extensions.cs deleted file mode 100644 index db554b2..0000000 --- a/src/Watchers/Warden.Watchers.MongoDb/Extensions.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System; - -using Warden.Core; - -namespace Warden.Watchers.MongoDb -{ - /// - /// Custom extension methods for the MongoDB watcher. - /// - public static class Extensions - { - /// - /// Extension method for adding the MongoDB watcher to the the WardenConfiguration with the default name of MongoDB Watcher. - /// - /// Instance of the Warden configuration builder. - /// Connection string of the MongoDB database. - /// Name of the MongoDB database. - /// Optional timeout of the MongoDB query (5 seconds by default). - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMongoDbWatcher( - this WardenConfiguration.Builder builder, - string connectionString, - string database, - TimeSpan? timeout = null, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MongoDbWatcher.Create(connectionString, database, timeout, group: group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the MongoDB watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the MongoDbWatcher. - /// Connection string of the MongoDB database. - /// Name of the MongoDB database. - /// Optional timeout of the MongoDB query (5 seconds by default). - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMongoDbWatcher( - this WardenConfiguration.Builder builder, - string name, - string connectionString, - string database, - TimeSpan? timeout = null, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MongoDbWatcher.Create(name, connectionString, database, timeout, group: group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the MongoDB watcher to the the WardenConfiguration with the default name of MongoDB Watcher. - /// - /// Instance of the Warden configuration builder. - /// Connection string of the MongoDB database. - /// Name of the MongoDB database. - /// Lambda expression for configuring the MongoDbWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional timeout of the MongoDB query (5 seconds by default). - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMongoDbWatcher( - this WardenConfiguration.Builder builder, - string connectionString, - string database, - Action configurator, - Action hooks = null, - TimeSpan? timeout = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MongoDbWatcher.Create(connectionString, database, timeout, configurator, group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the MongoDB watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the MongoDbWatcher. - /// Connection string of the MongoDB database. - /// Name of the MongoDB database. - /// Lambda expression for configuring the MongoDbWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional timeout of the MongoDB query (5 seconds by default). - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMongoDbWatcher( - this WardenConfiguration.Builder builder, - string name, - string connectionString, - string database, - Action configurator, - Action hooks = null, - TimeSpan? timeout = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MongoDbWatcher.Create(name, connectionString, database, timeout, configurator, group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the MongoDB watcher to the the WardenConfiguration with the default name of MongoDB Watcher. - /// - /// Instance of the Warden configuration builder. - /// Configuration of MongoDbWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMongoDbWatcher( - this WardenConfiguration.Builder builder, - MongoDbWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MongoDbWatcher.Create(configuration, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the MongoDB watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the MongoDbWatcher. - /// Configuration of MongoDbWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMongoDbWatcher( - this WardenConfiguration.Builder builder, - string name, - MongoDbWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MongoDbWatcher.Create(name, configuration, group), hooks, interval); - - return builder; - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MongoDb/IMongoDb.cs b/src/Watchers/Warden.Watchers.MongoDb/IMongoDb.cs deleted file mode 100644 index 661e3bd..0000000 --- a/src/Watchers/Warden.Watchers.MongoDb/IMongoDb.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using MongoDB.Bson; -using MongoDB.Driver; - -namespace Warden.Watchers.MongoDb -{ - /// - /// Custom MongoDB connector for executing the MongoDB queries. - /// - public interface IMongoDb - { - /// - /// Executes the MongoDB query and returns a collection of the dynamic results. - /// - /// Name of the collection in selected MongoDB database. - /// MongoDB query. - /// - Task> QueryAsync(string collection, string query); - } - - /// - /// Default implementation of the IMongoDb based on MongoDB Driver. - /// - public class MongoDb : IMongoDb - { - private readonly IMongoDatabase _database; - - public MongoDb(IMongoDatabase database) - { - _database = database; - } - - public async Task> QueryAsync(string collection, string query) - { - var findQuery = MongoDB.Bson.Serialization.BsonSerializer.Deserialize(query); - var result = await _database.GetCollection(collection).FindAsync(findQuery); - - return await result.ToListAsync(); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MongoDb/IMongoDbConnection.cs b/src/Watchers/Warden.Watchers.MongoDb/IMongoDbConnection.cs deleted file mode 100644 index cc4b46d..0000000 --- a/src/Watchers/Warden.Watchers.MongoDb/IMongoDbConnection.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using MongoDB.Driver; - -namespace Warden.Watchers.MongoDb -{ - /// - /// Custom IMongoDbConnection for opening a connection to the MongoDB. - /// - public interface IMongoDbConnection - { - /// - /// Name of the MongoDB database. - /// - string Database { get; } - - /// - /// Connection string of the MongoDB server. - /// - string ConnectionString { get; } - - /// - /// Timeout for connection to the MongoDB server. - /// - TimeSpan Timeout { get; } - - /// - /// Opens a connection to the MongoDB database. - /// - /// Instance of IMongoDb. - Task GetDatabaseAsync(); - } - - /// - /// Default implementation of the IMongoDbConnection based on the MongoClient from MongoDB Driver. - /// - public class MongoDbConnection : IMongoDbConnection - { - private readonly MongoClient _client; - public string Database { get; } - public string ConnectionString { get; } - public TimeSpan Timeout { get; } - - public MongoDbConnection(string database, string connectionString, TimeSpan timeout) - { - Database = database; - ConnectionString = connectionString; - Timeout = timeout; - _client = new MongoClient(InitializeSettings()); - } - - public async Task GetDatabaseAsync() - { - var databases = await _client.ListDatabasesAsync(); - var hasDatabase = false; - while (await databases.MoveNextAsync()) - { - hasDatabase = databases.Current.Any(x => x["name"] == Database); - } - - return hasDatabase ? new MongoDb(_client.GetDatabase(Database)) : null; - } - - protected MongoClientSettings InitializeSettings() - { - var settings = new MongoClientSettings - { - Server = GetServerAddress(), - ConnectTimeout = Timeout, - ServerSelectionTimeout = Timeout - }; - - return settings; - } - - protected MongoServerAddress GetServerAddress() - { - //Remove the "mongodb://" substring - var cleanedConnectionString = ConnectionString.Substring(10); - var hostAndPort = cleanedConnectionString.Split(':'); - - return new MongoServerAddress(hostAndPort[0], int.Parse(hostAndPort[1])); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcher.cs b/src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcher.cs deleted file mode 100644 index f4fc5b9..0000000 --- a/src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcher.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System; -using System.Threading.Tasks; -using MongoDB.Driver; - -namespace Warden.Watchers.MongoDb -{ - /// - /// MongoDbWatcher designed for MongoDB monitoring. - /// - public class MongoDbWatcher : IWatcher - { - private readonly MongoDbWatcherConfiguration _configuration; - private readonly IMongoDbConnection _connection; - public string Name { get; } - public string Group { get; } - public const string DefaultName = "MongoDB Watcher"; - - protected MongoDbWatcher(string name, MongoDbWatcherConfiguration configuration, string group) - { - if (string.IsNullOrEmpty(name)) - throw new ArgumentException("Watcher name can not be empty."); - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "MongoDB Watcher configuration has not been provided."); - } - - Name = name; - _configuration = configuration; - Group = group; - _connection = configuration.ConnectionProvider(configuration.ConnectionString); - } - - public async Task ExecuteAsync() - { - try - { - var mongoDb = _configuration.MongoDbProvider?.Invoke() ?? await _connection.GetDatabaseAsync(); - if (mongoDb == null) - { - return MongoDbWatcherCheckResult.Create(this, false, _configuration.Database, - _configuration.ConnectionString, $"Database: '{_configuration.Database}' has not been found."); - } - if (string.IsNullOrWhiteSpace(_configuration.Query)) - { - return MongoDbWatcherCheckResult.Create(this, true, _configuration.Database, - _configuration.ConnectionString, - $"Database: {_configuration.Database} has been sucessfully checked."); - } - - return await ExecuteForQueryAsync(mongoDb); - } - catch (MongoException exception) - { - return MongoDbWatcherCheckResult.Create(this, false, _configuration.Database, - _configuration.ConnectionString, exception.Message); - } - catch (Exception exception) - { - throw new WatcherException("There was an error while trying to access the MongoDB.", exception); - } - } - - private async Task ExecuteForQueryAsync(IMongoDb mongoDb) - { - var queryResult = await mongoDb.QueryAsync(_configuration.CollectionName, _configuration.Query); - var isValid = true; - if (_configuration.EnsureThatAsync != null) - isValid = await _configuration.EnsureThatAsync?.Invoke(queryResult); - - isValid = isValid && (_configuration.EnsureThat?.Invoke(queryResult) ?? true); - var description = $"MongoDB check has returned {(isValid ? "valid" : "invalid")} result for " + - $"database: '{_configuration.Database}' and given query."; - - return MongoDbWatcherCheckResult.Create(this, isValid, _configuration.Database, - _configuration.ConnectionString, _configuration.Query, queryResult, description); - } - - /// - /// Factory method for creating a new instance of MongoDbWatcher with default name of MongoDB Watcher. - /// - /// Connection string of the MongoDB server. - /// Name of the MongoDB database. - /// Optional timeout of the MongoDB query (5 seconds by default). - /// Optional lambda expression for configuring the MongoDbWatcher. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of MongoDbWatcher. - public static MongoDbWatcher Create(string connectionString, string database, - TimeSpan? timeout = null, Action configurator = null, - string group = null) - => Create(DefaultName, connectionString, database, timeout, configurator, group); - - /// - /// Factory method for creating a new instance of MongoDbWatcher. - /// - /// Name of the MongoDbWatcher. - /// Connection string of the MongoDB server. - /// Name of the MongoDB database. - /// Optional timeout of the MongoDB query (5 seconds by default). - /// Optional lambda expression for configuring the MongoDbWatcher. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of MongoDbWatcher. - public static MongoDbWatcher Create(string name, string connectionString, string database, - TimeSpan? timeout = null, Action configurator = null, - string group = null) - { - var config = new MongoDbWatcherConfiguration.Builder(connectionString, database, timeout); - configurator?.Invoke((MongoDbWatcherConfiguration.Default) config); - - return Create(name, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of MongoDbWatcher with default name of MongoDB Watcher. - /// - /// Configuration of MongoDbWatcher. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of MongoDbWatcher. - public static MongoDbWatcher Create(MongoDbWatcherConfiguration configuration, - string group = null) - => Create(DefaultName, configuration, group); - - /// - /// Factory method for creating a new instance of MongoDbWatcher. - /// - /// Name of the MongoDbWatcher. - /// Configuration of MongoDbWatcher. - /// Optional name of the group that MongoDbWatcher belongs to. - /// Instance of MongoDbWatcher. - public static MongoDbWatcher Create(string name, MongoDbWatcherConfiguration configuration, - string group = null) - => new MongoDbWatcher(name, configuration, group); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcherCheckResult.cs b/src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcherCheckResult.cs deleted file mode 100644 index 62d4113..0000000 --- a/src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcherCheckResult.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace Warden.Watchers.MongoDb -{ - /// - /// Custom check result type for MongoDBWatcher. - /// - public class MongoDbWatcherCheckResult : WatcherCheckResult - { - /// - /// Name of the MongoDB database. - /// - public string Database { get; } - - /// - /// Connection string of the MongoDB server. - /// - public string ConnectionString { get; } - - /// - /// MongoDB Query. - /// - public string Query { get; } - - /// - /// Collection of dynamic results of the MongoDB query. - /// - public IEnumerable QueryResult { get; } - - protected MongoDbWatcherCheckResult(MongoDbWatcher watcher, bool isValid, string description, - string database, string connectionString, string query, IEnumerable queryResult) - : base(watcher, isValid, description) - { - Database = database; - ConnectionString = connectionString; - Query = query; - QueryResult = queryResult; - } - - /// - /// Factory method for creating a new instance of MongoDbWatcherCheckResult. - /// - /// Instance of MongoDbWatcher. - /// Flag determining whether the performed check was valid. - /// Name of the MongoDB database. - /// Connection string of the MongoDB server. - /// Custom description of the performed check. - /// Instance of MongoDbWatcherCheckResult. - public static MongoDbWatcherCheckResult Create(MongoDbWatcher watcher, bool isValid, - string database, string connectionString, string description = "") - => new MongoDbWatcherCheckResult(watcher, isValid, description, database, - connectionString, string.Empty, Enumerable.Empty()); - - /// - /// Factory method for creating a new instance of MongoDbWatcherCheckResult. - /// - /// Instance of MongoDbWatcher. - /// Flag determining whether the performed check was valid. - /// Name of the MongoDB database. - /// Connection string of the MongoDB server. - /// MongoDB query. - /// Collection of dynamic results of the MongoDB query. - /// Custom description of the performed check. - /// Instance of MongoDbWatcherCheckResult. - public static MongoDbWatcherCheckResult Create(MongoDbWatcher watcher, bool isValid, string database, - string connectionString, string query, IEnumerable queryResult, string description = "") - => new MongoDbWatcherCheckResult(watcher, isValid, description, database, connectionString, query, - queryResult); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcherConfiguration.cs b/src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcherConfiguration.cs deleted file mode 100644 index a105fd8..0000000 --- a/src/Watchers/Warden.Watchers.MongoDb/MongoDbWatcherConfiguration.cs +++ /dev/null @@ -1,256 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using MongoDB.Driver; -using Warden.Core; - -namespace Warden.Watchers.MongoDb -{ - /// - /// Configuration of the MongoDbWatcher. - /// - public class MongoDbWatcherConfiguration - { - /// - /// Name of the MongoDB database. - /// - public string Database { get; protected set; } - - /// - /// Connection string of the MongoDB server. - /// - public string ConnectionString { get; protected set; } - - /// - /// MongoDB query. - /// - public string Query { get; protected set; } - - /// - /// Name of the MongoDB collection. - /// - public string CollectionName { get; protected set; } - - /// - /// Optional timeout of the MongoDB query (5 seconds by default). - /// - public TimeSpan Timeout { get; protected set; } - - /// - /// Custom provider for the IMongoDbConnection. Input parameter is connection string. - /// - public Func ConnectionProvider { get; protected set; } - - /// - /// Custom provider for the IMongoDb. - /// - public Func MongoDbProvider { get; protected set; } - - /// - /// Predicate that has to be satisfied in order to return the valid result. - /// - public Func, bool> EnsureThat { get; protected set; } - - /// - /// Async predicate that has to be satisfied in order to return the valid result. - /// - public Func, Task> EnsureThatAsync { get; protected set; } - - protected internal MongoDbWatcherConfiguration(string connectionString, - string database, TimeSpan? timeout = null) - { - if (string.IsNullOrWhiteSpace(connectionString)) - throw new ArgumentException("Connection string can not be empty.", nameof(connectionString)); - - ValidateAndSetDatabase(database); - ConnectionString = connectionString; - if (timeout.HasValue) - { - ValidateTimeout(timeout.Value); - Timeout = timeout.Value; - } - else - Timeout = TimeSpan.FromSeconds(5); - - ConnectionProvider = cs => new MongoDbConnection(Database, connectionString, Timeout); - } - - protected static void ValidateTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); - } - - protected virtual MongoServerAddress GetServerAddress() - { - //Remove the "mongodb://" substring - var cleanedConnectionString = ConnectionString.Substring(10); - var hostAndPort = cleanedConnectionString.Split(':'); - - return new MongoServerAddress(hostAndPort[0], int.Parse(hostAndPort[1])); - } - - protected void ValidateAndSetDatabase(string database) - { - if (string.IsNullOrEmpty(database)) - throw new ArgumentException("Database name can not be empty.", nameof(database)); - - Database = database; - } - - /// - /// Factory method for creating a new instance of fluent builder for the MongoDbWatcherConfiguration. - /// - /// Connection string of the MongoDB server. - /// Name of the MongoDB database. - /// Optional timeout of the MongoDB query (5 seconds by default). - /// Instance of fluent builder for the MongoDbWatcherConfiguration. - public static Builder Create(string connectionString, string database, TimeSpan? timeout = null) - => new Builder(connectionString, database, timeout); - - /// - /// Fluent builder for the MongoDbWatcherConfiguration. - /// - public abstract class Configurator : WatcherConfigurator - where T : Configurator - { - protected Configurator(string connectionString, string database, TimeSpan? timeout = null) - { - Configuration = new MongoDbWatcherConfiguration(connectionString, database, timeout); - } - - protected Configurator(MongoDbWatcherConfiguration configuration) : base(configuration) - { - } - - /// - /// Sets the collection name and a MongoDB query. - /// - /// Name of the MongoDB collection. - /// MongoDB query. - /// Instance of fluent builder for the MongoDbWatcherConfiguration. - public T WithQuery(string collectionName, string query) - { - if (string.IsNullOrEmpty(collectionName)) - throw new ArgumentException("MongoDB collection name can not be empty.", nameof(collectionName)); - - if (string.IsNullOrEmpty(query)) - throw new ArgumentException("MongoDB query can not be empty.", nameof(query)); - - Configuration.CollectionName = collectionName; - Configuration.Query = query; - - return Configurator; - } - - - /// - /// Sets the predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the MongoDbWatcherConfiguration. - public T EnsureThat(Func, bool> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThat = ensureThat; - - return Configurator; - } - - /// - /// Sets the async predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the MongoDbWatcherConfiguration. - public T EnsureThatAsync(Func, Task> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that async predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThatAsync = ensureThat; - - return Configurator; - } - - /// - /// Sets the custom provider for the IMongoDbConnection. - /// - /// Custom provider for the IMongoDbConnection. - /// Lambda expression taking as an input connection string - /// and returning an instance of the IMongoDbConnection. - /// Instance of fluent builder for the MongoDbWatcherConfiguration. - public T WithConnectionProvider(Func connectionProvider) - { - if (connectionProvider == null) - { - throw new ArgumentNullException(nameof(connectionProvider), - "MongoDB connection provider can not be null."); - } - - Configuration.ConnectionProvider = connectionProvider; - - return Configurator; - } - - /// - /// Sets the custom provider for the IMongoDb. - /// - /// Custom provider for the IMongoDb. - /// Lambda expression returning an instance of the IMongoDb. - /// Instance of fluent builder for the MongoDbWatcherConfiguration. - public T WithMongoDbProvider(Func mongoDbProvider) - { - if (mongoDbProvider == null) - { - throw new ArgumentNullException(nameof(mongoDbProvider), "MongoDB provider can not be null."); - } - - Configuration.MongoDbProvider = mongoDbProvider; - - return Configurator; - } - } - - - /// - /// Default MongoDbWatcherConfiguration fluent builder used while configuring watcher via lambda expression. - /// - public class Default : Configurator - { - public Default(MongoDbWatcherConfiguration configuration) : base(configuration) - { - SetInstance(this); - } - } - - /// - /// Extended MongoDbWatcherConfiguration fluent builder used while configuring watcher directly. - /// - public class Builder : Configurator - { - public Builder(string database, string connectionString, TimeSpan? timeout = null) - : base(database, connectionString, timeout) - { - SetInstance(this); - } - - /// - /// Builds the MongoDbWatcherConfiguration and return its instance. - /// - /// Instance of MongoDbWatcherConfiguration. - public MongoDbWatcherConfiguration Build() => Configuration; - - /// - /// Operator overload to provide casting the Builder configurator into Default configurator. - /// - /// Instance of extended Builder configurator. - /// Instance of Default builder configurator. - public static explicit operator Default(Builder builder) => new Default(builder.Configuration); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MongoDb/Properties/AssemblyInfo.cs b/src/Watchers/Warden.Watchers.MongoDb/Properties/AssemblyInfo.cs deleted file mode 100644 index 580966e..0000000 --- a/src/Watchers/Warden.Watchers.MongoDb/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Watchers.MongoDb")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Watchers.MongoDb")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("cf59dae7-3f6d-4795-8ba8-296faa0ecc76")] diff --git a/src/Watchers/Warden.Watchers.MongoDb/Warden.Watchers.MongoDb.csproj b/src/Watchers/Warden.Watchers.MongoDb/Warden.Watchers.MongoDb.csproj deleted file mode 100644 index d33383e..0000000 --- a/src/Watchers/Warden.Watchers.MongoDb/Warden.Watchers.MongoDb.csproj +++ /dev/null @@ -1,39 +0,0 @@ - - - - Warden watcher for MongoDB. - 1.3.1 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Watchers.MongoDb - Warden.Watchers.MongoDb - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - diff --git a/src/Watchers/Warden.Watchers.MsSql/Extensions.cs b/src/Watchers/Warden.Watchers.MsSql/Extensions.cs deleted file mode 100644 index 03ee686..0000000 --- a/src/Watchers/Warden.Watchers.MsSql/Extensions.cs +++ /dev/null @@ -1,150 +0,0 @@ -using System; -using Warden.Core; - -namespace Warden.Watchers.MsSql -{ - /// - /// Custom extension methods for the MSSQL watcher. - /// - public static class Extensions - { - /// - /// Extension method for adding the MSSQL watcher to the the WardenConfiguration with the default name of MSSQL Watcher. - /// - /// Instance of the Warden configuration builder. - /// Connection string of the MSSQL database. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMsSqlWatcher( - this WardenConfiguration.Builder builder, - string connectionString, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MsSqlWatcher.Create(connectionString, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the MSSQL watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the MsSqlWatcher. - /// Connection string of the MSSQL database. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMsSqlWatcher( - this WardenConfiguration.Builder builder, - string name, - string connectionString, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MsSqlWatcher.Create(name, connectionString, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the MSSQL watcher to the the WardenConfiguration with the default name of MSSQL Watcher. - /// - /// Instance of the Warden configuration builder. - /// Connection string of the MSSQL database. - /// Lambda expression for configuring the MsSqlWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMsSqlWatcher( - this WardenConfiguration.Builder builder, - string connectionString, - Action configurator, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MsSqlWatcher.Create(connectionString, configurator, group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the MSSQL watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the MsSqlWatcher. - /// Connection string of the MSSQL database. - /// Lambda expression for configuring the MsSqlWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMsSqlWatcher( - this WardenConfiguration.Builder builder, - string name, - string connectionString, - Action configurator, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MsSqlWatcher.Create(name, connectionString, configurator, group), - hooks, interval); - - return builder; - } - - - /// - /// Extension method for adding the MSSQL watcher to the the WardenConfiguration with the default name of MSSQL Watcher. - /// - /// Instance of the Warden configuration builder. - /// Configuration of MsSqlWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMsSqlWatcher( - this WardenConfiguration.Builder builder, - MsSqlWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MsSqlWatcher.Create(configuration, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the MSSQL watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the MsSqlWatcher. - /// Configuration of MsSqlWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddMsSqlWatcher( - this WardenConfiguration.Builder builder, - string name, - MsSqlWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(MsSqlWatcher.Create(name, configuration, group), hooks, interval); - - return builder; - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MsSql/IMsSql.cs b/src/Watchers/Warden.Watchers.MsSql/IMsSql.cs deleted file mode 100644 index 62efabf..0000000 --- a/src/Watchers/Warden.Watchers.MsSql/IMsSql.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Threading.Tasks; -using Dapper; - -namespace Warden.Watchers.MsSql -{ - /// - /// Custom MSSQL database connector for executing the SQL queries. - /// - public interface IMsSql - { - /// - /// Executes the SQL query and returns a collection of the dynamic results. - /// - /// Instance of IDbConnection. - /// SQL query. - /// SQL query parameters. - /// Optional timeout. - /// - Task> QueryAsync(IDbConnection connection, string query, - IDictionary parameters, TimeSpan? timeout = null); - } - - /// - /// Default implementation of the IMsSql based on Dapper. - /// - public class DapperMsSql : IMsSql - { - public async Task> QueryAsync(IDbConnection connection, string query, - IDictionary parameters, TimeSpan? timeout = null) - { - var queryParameters = new DynamicParameters(); - if (parameters != null) - { - foreach (var parameter in parameters) - { - queryParameters.Add(parameter.Key, parameter.Value); - } - } - - return await connection.QueryAsync(query, queryParameters, - commandTimeout: (int?) timeout?.TotalSeconds); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MsSql/MsSqlWatcher.cs b/src/Watchers/Warden.Watchers.MsSql/MsSqlWatcher.cs deleted file mode 100644 index 3d1f969..0000000 --- a/src/Watchers/Warden.Watchers.MsSql/MsSqlWatcher.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System; -using System.Data; -using System.Data.SqlClient; -using System.Linq; -using System.Threading.Tasks; - -namespace Warden.Watchers.MsSql -{ - /// - /// MsSqlWatcher designed for MSSQL monitoring. - /// - public class MsSqlWatcher : IWatcher - { - private readonly IMsSql _msSql; - private readonly MsSqlWatcherConfiguration _configuration; - public string Name { get; } - public string Group { get; } - public const string DefaultName = "MSSQL Watcher"; - - protected MsSqlWatcher(string name, MsSqlWatcherConfiguration configuration, string group) - { - if (string.IsNullOrEmpty(name)) - throw new ArgumentException("Watcher name can not be empty."); - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "MSSQL Watcher configuration has not been provided."); - } - - Name = name; - _configuration = configuration; - Group = group; - _msSql = _configuration.MsSqlProvider(); - } - - public async Task ExecuteAsync() - { - try - { - using (var connection = _configuration.ConnectionProvider(_configuration.ConnectionString)) - { - connection.Open(); - if (string.IsNullOrWhiteSpace(_configuration.Query)) - { - return MsSqlWatcherCheckResult.Create(this, true, _configuration.ConnectionString, - $"Database: {_configuration.Database} has been sucessfully checked."); - } - - return await ExecuteForQueryAsync(connection); - } - } - catch (SqlException exception) - { - return MsSqlWatcherCheckResult.Create(this, false, _configuration.ConnectionString, - _configuration.Query, Enumerable.Empty(), exception.Message); - } - catch (Exception exception) - { - throw new WatcherException("There was an error while trying to access MSSQL database.", exception); - } - } - - private async Task ExecuteForQueryAsync(IDbConnection connection) - { - var queryResult = await _msSql.QueryAsync(connection, _configuration.Query, - _configuration.QueryParameters, _configuration.QueryTimeout); - - var isValid = true; - if (_configuration.EnsureThatAsync != null) - isValid = await _configuration.EnsureThatAsync?.Invoke(queryResult); - - isValid = isValid && (_configuration.EnsureThat?.Invoke(queryResult) ?? true); - var description = $"MSSQL check has returned {(isValid ? "valid" : "invalid")} result for " + - $"database: '{_configuration.Database}' and given query."; - - return MsSqlWatcherCheckResult.Create(this, isValid, _configuration.ConnectionString, - _configuration.Query, queryResult, description); - } - - /// - /// Factory method for creating a new instance of MsSqlWatcher with default name of MSSQL Watcher. - /// - /// Connection string of the MSSQL database. - /// Optional lambda expression for configuring the MsSqlWatcher. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of MsSqlWatcher. - public static MsSqlWatcher Create(string connectionString, - Action configurator = null, - string group = null) - => Create(DefaultName, connectionString, configurator, group); - - /// - /// Factory method for creating a new instance of MsSqlWatcher. - /// - /// Name of the MsSqlWatcher. - /// Connection string of the MSSQL database. - /// Optional lambda expression for configuring the MsSqlWatcher. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of MsSqlWatcher. - public static MsSqlWatcher Create(string name, string connectionString, - Action configurator = null, - string group = null) - { - var config = new MsSqlWatcherConfiguration.Builder(connectionString); - configurator?.Invoke((MsSqlWatcherConfiguration.Default) config); - - return Create(name, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of MsSqlWatcher with default name of MSSQL Watcher. - /// - /// Configuration of MsSqlWatcher. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of MsSqlWatcher. - public static MsSqlWatcher Create(MsSqlWatcherConfiguration configuration, string group = null) - => Create(DefaultName, configuration, group); - - /// - /// Factory method for creating a new instance of MsSqlWatcher. - /// - /// Name of the MsSqlWatcher. - /// Configuration of MsSqlWatcher. - /// Optional name of the group that MsSqlWatcher belongs to. - /// Instance of MsSqlWatcher. - public static MsSqlWatcher Create(string name, MsSqlWatcherConfiguration configuration, - string group = null) - => new MsSqlWatcher(name, configuration, group); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MsSql/MsSqlWatcherCheckResult.cs b/src/Watchers/Warden.Watchers.MsSql/MsSqlWatcherCheckResult.cs deleted file mode 100644 index 97950a7..0000000 --- a/src/Watchers/Warden.Watchers.MsSql/MsSqlWatcherCheckResult.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace Warden.Watchers.MsSql -{ - /// - /// Custom check result type for MsSqlWatcher. - /// - public class MsSqlWatcherCheckResult : WatcherCheckResult - { - /// - /// Connection string of the MSSQL server. - /// - public string ConnectionString { get; } - - /// - /// SQL Query. - /// - public string Query { get; } - - /// - /// Collection of dynamic results of the SQL query. - /// - public IEnumerable QueryResult { get; } - - protected MsSqlWatcherCheckResult(MsSqlWatcher watcher, bool isValid, string description, - string connectionString, string query, IEnumerable queryResult) - : base(watcher, isValid, description) - { - ConnectionString = connectionString; - Query = query; - QueryResult = queryResult; - } - - /// - /// Factory method for creating a new instance of MsSqlWatcherCheckResult. - /// - /// Instance of MsSqlWatcher. - /// Flag determining whether the performed check was valid. - /// Connection string of the MSSQL server. - /// Custom description of the performed check. - /// Instance of MsSqlWatcherCheckResult. - public static MsSqlWatcherCheckResult Create(MsSqlWatcher watcher, bool isValid, - string connectionString, string description = "") - => new MsSqlWatcherCheckResult(watcher, isValid, description, connectionString, string.Empty, - Enumerable.Empty()); - - /// - /// Factory method for creating a new instance of MsSqlWatcherCheckResult. - /// - /// Instance of MsSqlWatcher. - /// Flag determining whether the performed check was valid. - /// Connection string of the MSSQL server. - /// SQL query. - /// Collection of dynamic results of the SQL query. - /// Custom description of the performed check. - /// Instance of MsSqlWatcherCheckResult. - public static MsSqlWatcherCheckResult Create(MsSqlWatcher watcher, bool isValid, - string connectionString, string query, IEnumerable queryResult, string description = "") - => new MsSqlWatcherCheckResult(watcher, isValid, description, connectionString, query, queryResult); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MsSql/MsSqlWatcherConfiguration.cs b/src/Watchers/Warden.Watchers.MsSql/MsSqlWatcherConfiguration.cs deleted file mode 100644 index 961e7f9..0000000 --- a/src/Watchers/Warden.Watchers.MsSql/MsSqlWatcherConfiguration.cs +++ /dev/null @@ -1,239 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Threading.Tasks; -using Warden.Core; - -namespace Warden.Watchers.MsSql -{ - /// - /// Configuration of the MsSqlWatcher. - /// - public class MsSqlWatcherConfiguration - { - /// - /// Connection string of the MSSQL server. - /// - public string ConnectionString { get; protected set; } - - /// - /// Read-only name of the database. - /// - public string Database { get; protected set; } - - /// - /// SQL Query. - /// - public string Query { get; protected set; } - - /// - /// Optional timeout of the SQL query. - /// - public TimeSpan? QueryTimeout { get; protected set; } - - /// - /// Custom provider for the IDbConnection. Input parameter is connection string. - /// - public Func ConnectionProvider { get; protected set; } - - /// - /// Custom provider for the IMsSql. - /// - public Func MsSqlProvider { get; protected set; } - - /// - /// Collection of SQL query parameters. - /// - public IDictionary QueryParameters { get; protected set; } - - /// - /// Predicate that has to be satisfied in order to return the valid result. - /// - public Func, bool> EnsureThat { get; protected set; } - - /// - /// Async predicate that has to be satisfied in order to return the valid result. - /// - public Func, Task> EnsureThatAsync { get; protected set; } - - protected internal MsSqlWatcherConfiguration(string connectionString) - { - if (string.IsNullOrEmpty(connectionString)) - throw new ArgumentException("MSSQL connection string can not be empty.", nameof(connectionString)); - - try - { - var sqlConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString); - Database = sqlConnectionStringBuilder.InitialCatalog; - } - catch (Exception ex) - { - throw new ArgumentException("MSSQL connection string is invalid.", nameof(connectionString)); - } - - ConnectionString = connectionString; - ConnectionProvider = sqlConnectionString => new SqlConnection(sqlConnectionString); - MsSqlProvider = () => new DapperMsSql(); - } - - /// - /// Factory method for creating a new instance of fluent builder for the MsSqlWatcherConfiguration. - /// - /// Connection string of the MSSQL server. - /// Instance of fluent builder for the MsSqlWatcherConfiguration. - public static Builder Create(string connectionString) => new Builder(connectionString); - - /// - /// Fluent builder for the MsSqlWatcherConfiguration. - /// - public abstract class Configurator : WatcherConfigurator - where T : Configurator - { - protected Configurator(string connectionString) - { - Configuration = new MsSqlWatcherConfiguration(connectionString); - } - - protected Configurator(MsSqlWatcherConfiguration configuration) : base(configuration) - { - } - - /// - /// Sets the SQL query and its parameters (optional). - /// - /// SQL query. - /// Optional SQL query parameters. - /// Instance of fluent builder for the MsSqlWatcherConfiguration. - public T WithQuery(string query, IDictionary parameters = null) - { - if (string.IsNullOrEmpty(query)) - throw new ArgumentException("SQL query can not be empty.", nameof(query)); - - Configuration.Query = query; - Configuration.QueryParameters = parameters; - - return Configurator; - } - - /// - /// Sets the timeout for the SQL query execution. - /// - /// Timeout of SQL query. - /// Instance of fluent builder for the MsSqlWatcherConfiguration. - public T WithQueryTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); - - Configuration.QueryTimeout = timeout; - - return Configurator; - } - - /// - /// Sets the predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the MsSqlWatcherConfiguration. - public T EnsureThat(Func, bool> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThat = results => ensureThat(results); - - return Configurator; - } - - /// - /// Sets the async predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the MsSqlWatcherConfiguration. - public T EnsureThatAsync(Func, Task> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that async predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThatAsync = ensureThat; - - return Configurator; - } - - /// - /// Sets the custom provider for the IDbConnection. - /// - /// Custom provider for the IDbConnection. - /// Lambda expression taking as an input connection string - /// and returning an instance of the IDbConnection. - /// Instance of fluent builder for the MsSqlWatcherConfiguration. - public T WithConnectionProvider(Func connectionProvider) - { - if (connectionProvider == null) - { - throw new ArgumentNullException(nameof(connectionProvider), - "SQL connection provider can not be null."); - } - - Configuration.ConnectionProvider = connectionProvider; - - return Configurator; - } - - /// - /// Sets the custom provider for the IMsSql. - /// - /// Custom provider for the IMsSql. - /// Lambda expression returning an instance of the IMsSql. - /// Instance of fluent builder for the MsSqlWatcherConfiguration. - public T WithMsSqlProvider(Func msSqlProvider) - { - if (msSqlProvider == null) - throw new ArgumentNullException(nameof(msSqlProvider), "MSSQL provider can not be null."); - - Configuration.MsSqlProvider = msSqlProvider; - - return Configurator; - } - } - - /// - /// Default MsSqlWatcherConfiguration fluent builder used while configuring watcher via lambda expression. - /// - public class Default : Configurator - { - public Default(MsSqlWatcherConfiguration configuration) : base(configuration) - { - SetInstance(this); - } - } - - /// - /// Extended MsSqlWatcherConfiguration fluent builder used while configuring watcher directly. - /// - public class Builder : Configurator - { - public Builder(string connectionString) : base(connectionString) - { - SetInstance(this); - } - - /// - /// Builds the MsSqlWatcherConfiguration and return its instance. - /// - /// Instance of MsSqlWatcherConfiguration. - public MsSqlWatcherConfiguration Build() => Configuration; - - /// - /// Operator overload to provide casting the Builder configurator into Default configurator. - /// - /// Instance of extended Builder configurator. - /// Instance of Default builder configurator. - public static explicit operator Default(Builder builder) => new Default(builder.Configuration); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.MsSql/Properties/AssemblyInfo.cs b/src/Watchers/Warden.Watchers.MsSql/Properties/AssemblyInfo.cs deleted file mode 100644 index fec95ad..0000000 --- a/src/Watchers/Warden.Watchers.MsSql/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Watchers.MsSql")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Watchers.MsSql")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("345c0fcc-8d10-423e-b50f-ac3c2794b265")] diff --git a/src/Watchers/Warden.Watchers.MsSql/Warden.Watchers.MsSql.csproj b/src/Watchers/Warden.Watchers.MsSql/Warden.Watchers.MsSql.csproj deleted file mode 100644 index d26bd0e..0000000 --- a/src/Watchers/Warden.Watchers.MsSql/Warden.Watchers.MsSql.csproj +++ /dev/null @@ -1,48 +0,0 @@ - - - - Warden watcher for MSSQL. - 1.3.2 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Watchers.MsSql - Warden.Watchers.MsSql - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Watchers/Warden.Watchers.Performance/Extensions.cs b/src/Watchers/Warden.Watchers.Performance/Extensions.cs deleted file mode 100644 index be644f1..0000000 --- a/src/Watchers/Warden.Watchers.Performance/Extensions.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using Warden.Core; - -namespace Warden.Watchers.Performance -{ - /// - /// Custom extension methods for the Performance watcher. - /// - public static class Extensions - { - /// - /// Extension method for adding the Performance watcher to the the WardenConfiguration with the default name of Performance Watcher. - /// - /// Instance of the Warden configuration builder. - /// Optional lambda expression for configuring the watcher hooks. - /// Delay between resource usage calculation while using the default performance counter (100 ms by default). - /// Optional name of the remote machine. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddPerformanceWatcher( - this WardenConfiguration.Builder builder, - Action hooks = null, - TimeSpan? delay = null, - string machineName = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(PerformanceWatcher.Create(delay, machineName, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Performance watcher to the the WardenConfiguration with the default name of Performance Watcher. - /// - /// Instance of the Warden configuration builder. - /// Name of the PerformanceWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Delay between resource usage calculation while using the default performance counter (100 ms by default). - /// Optional name of the remote machine. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddPerformanceWatcher( - this WardenConfiguration.Builder builder, - string name, - Action hooks = null, - TimeSpan? delay = null, - string machineName = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(PerformanceWatcher.Create(name, delay, machineName, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Performance watcher to the the WardenConfiguration with the default name of Performance Watcher. - /// - /// Instance of the Warden configuration builder. - /// Lambda expression for configuring the PerformanceWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Delay between resource usage calculation while using the default performance counter (100 ms by default). - /// Optional name of the remote machine. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddPerformanceWatcher( - this WardenConfiguration.Builder builder, - Action configurator, - Action hooks = null, - TimeSpan? delay = null, - string machineName = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(PerformanceWatcher.Create(delay, machineName, configurator, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Performance watcher to the the WardenConfiguration with the default name of Performance Watcher. - /// - /// Instance of the Warden configuration builder. - /// Name of the PerformanceWatcher. - /// Lambda expression for configuring the PerformanceWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Delay between resource usage calculation while using the default performance counter (100 ms by default). - /// Optional name of the remote machine. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddPerformanceWatcher( - this WardenConfiguration.Builder builder, - string name, - Action configurator, - Action hooks = null, - TimeSpan? delay = null, - string machineName = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(PerformanceWatcher.Create(name, delay, machineName, configurator, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Performance watcher to the the WardenConfiguration with the default name of Performance Watcher. - /// - /// Instance of the Warden configuration builder. - /// Configuration of PerformanceWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddPerformanceWatcher( - this WardenConfiguration.Builder builder, - PerformanceWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(PerformanceWatcher.Create(configuration, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Performance watcher to the the WardenConfiguration with the default name of Performance Watcher. - /// - /// Instance of the Warden configuration builder. - /// Name of the PerformanceWatcher. - /// Configuration of PerformanceWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddPerformanceWatcher( - this WardenConfiguration.Builder builder, - string name, - PerformanceWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(PerformanceWatcher.Create(name, configuration, group), hooks, interval); - - return builder; - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Performance/IPerformance.cs b/src/Watchers/Warden.Watchers.Performance/IPerformance.cs deleted file mode 100644 index f4ba107..0000000 --- a/src/Watchers/Warden.Watchers.Performance/IPerformance.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Diagnostics; -using System.Threading.Tasks; - -namespace Warden.Watchers.Performance -{ - /// - /// Custom performance analyzer. - /// - public interface IPerformance - { - Task GetResourceUsageAsync(); - } - - /// - /// Default implementation of the IPerformance based on PerformanceCounter. - /// - public class Performance : IPerformance - { - private readonly TimeSpan _delay; - private readonly string _machineName; - - public Performance(TimeSpan delay, string machineName) - { - _delay = delay; - _machineName = machineName; - } - - public async Task GetResourceUsageAsync() - { - var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); - var ramCounter = new PerformanceCounter("Memory", "Available MBytes"); - if (!string.IsNullOrWhiteSpace(_machineName)) - { - cpuCounter.MachineName = _machineName; - ramCounter.MachineName = _machineName; - } - cpuCounter.NextValue(); - ramCounter.NextValue(); - await Task.Delay(_delay); - var cpuUsage = cpuCounter.NextValue(); - var ramUsage = ramCounter.NextValue(); - - return ResourceUsage.Create(cpuUsage, ramUsage); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Performance/PerformanceWatcher.cs b/src/Watchers/Warden.Watchers.Performance/PerformanceWatcher.cs deleted file mode 100644 index 50034b6..0000000 --- a/src/Watchers/Warden.Watchers.Performance/PerformanceWatcher.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Warden.Watchers.Performance -{ - /// - /// PerformanceWatcher designed for CPU & RAM monitoring. - /// - public class PerformanceWatcher : IWatcher - { - private readonly PerformanceWatcherConfiguration _configuration; - public string Name { get; } - public string Group { get; } - public const string DefaultName = "Performance Watcher"; - - protected PerformanceWatcher(string name, PerformanceWatcherConfiguration configuration, string group) - { - if (string.IsNullOrEmpty(name)) - throw new ArgumentException("Watcher name can not be empty."); - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Performance Watcher configuration has not been provided."); - } - - Name = name; - _configuration = configuration; - Group = group; - } - - public async Task ExecuteAsync() - { - try - { - var resourceUsage = await _configuration.PerformanceProvider().GetResourceUsageAsync(); - var isValid = true; - if (_configuration.EnsureThatAsync != null) - isValid = await _configuration.EnsureThatAsync?.Invoke(resourceUsage); - - isValid = isValid && (_configuration.EnsureThat?.Invoke(resourceUsage) ?? true); - var description = $"Performance check has returned {(isValid ? "valid" : "invalid")} result for " + - $"CPU usage: {resourceUsage.Cpu:F}%, RAM usage: {resourceUsage.Ram} MB."; - - return PerformanceWatcherCheckResult.Create(this, isValid, _configuration.Delay, - _configuration.MachineName, resourceUsage, description); - } - catch (Exception exception) - { - throw new WatcherException("There was an error while trying to calculate performance.", exception); - } - } - - /// - /// Factory method for creating a new instance of PerformanceWatcher with default name of Performance Watcher. - /// - /// Delay between resource usage calculation while using the default performance counter (100 ms by default). - /// Optional name of the remote machine. - /// Optional lambda expression for configuring the PerformanceWatcher. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of PerformanceWatcher. - public static PerformanceWatcher Create(TimeSpan? delay = null, - string machineName = null, - Action configurator = null, - string group = null) - => Create(DefaultName, delay, machineName, configurator, group); - - /// - /// Factory method for creating a new instance of PerformanceWatcher with default name of Performance Watcher. - /// - /// Name of the PerformanceWatcher. - /// Delay between resource usage calculation while using the default performance counter (100 ms by default). - /// Optional name of the remote machine. - /// Optional lambda expression for configuring the PerformanceWatcher. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of PerformanceWatcher. - public static PerformanceWatcher Create(string name, TimeSpan? delay = null, - string machineName = null, - Action configurator = null, - string group = null) - { - var config = new PerformanceWatcherConfiguration.Builder(delay, machineName); - configurator?.Invoke((PerformanceWatcherConfiguration.Default) config); - - return Create(name, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of PerformanceWatcher with default name of Performance Watcher. - /// - /// Configuration of PerformanceWatcher. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of PerformanceWatcher. - public static PerformanceWatcher Create(PerformanceWatcherConfiguration configuration, - string group = null) - => Create(DefaultName, configuration, group); - - /// - /// Factory method for creating a new instance of PerformanceWatcher. - /// - /// Name of the PerformanceWatcher. - /// Configuration of PerformanceWatcher. - /// Optional name of the group that PerformanceWatcher belongs to. - /// Instance of PerformanceWatcher. - public static PerformanceWatcher Create(string name, PerformanceWatcherConfiguration configuration, - string group = null) - => new PerformanceWatcher(name, configuration, group); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Performance/PerformanceWatcherCheckResult.cs b/src/Watchers/Warden.Watchers.Performance/PerformanceWatcherCheckResult.cs deleted file mode 100644 index 7231cfb..0000000 --- a/src/Watchers/Warden.Watchers.Performance/PerformanceWatcherCheckResult.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; - -namespace Warden.Watchers.Performance -{ - /// - /// Custom check result type for PerformanceWatcher. - /// - public class PerformanceWatcherCheckResult : WatcherCheckResult - { - /// - /// Delay between resource usage calculation while using the default performance counter (100 ms by default). - /// - public TimeSpan Delay { get; } - - /// - /// Optional name of the remote machine. - /// - public string MachineName { get; } - - /// - /// Usage of the resources such as CPU and RAM. - /// - public ResourceUsage ResourceUsage { get; } - - protected PerformanceWatcherCheckResult(PerformanceWatcher watcher, bool isValid, string description, - TimeSpan delay, string machineName, ResourceUsage resourceUsage) - : base(watcher, isValid, description) - { - Delay = delay; - MachineName = machineName; - ResourceUsage = resourceUsage; - } - - /// - /// Factory method for creating a new instance of PerformanceWatcherCheckResult. - /// - /// Instance of PerformanceWatcher. - /// Flag determining whether the performed check was valid. - /// Delay between resource usage calculation while using the default performance counter (100 ms by default). - /// Optional name of the remote machine. - /// Usage of the resources such as CPU and RAM. - /// Custom description of the performed check. - /// Instance of PerformanceWatcherCheckResult. - public static PerformanceWatcherCheckResult Create(PerformanceWatcher watcher, bool isValid, - TimeSpan delay, string machineName, ResourceUsage resourceUsage, string description = "") - => new PerformanceWatcherCheckResult(watcher, isValid, description, delay, machineName, resourceUsage); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Performance/PerformanceWatcherConfiguration.cs b/src/Watchers/Warden.Watchers.Performance/PerformanceWatcherConfiguration.cs deleted file mode 100644 index 6f97461..0000000 --- a/src/Watchers/Warden.Watchers.Performance/PerformanceWatcherConfiguration.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Warden.Watchers.Performance -{ - /// - /// Configuration of the PerformanceWatcher. - /// - public class PerformanceWatcherConfiguration - { - /// - /// Delay between resource usage calculation while using the default performance counter (100 ms by default). - /// - public TimeSpan Delay { get; protected set; } - - /// - /// Optional name of the remote machine. - /// - public string MachineName { get; } - - /// - /// Predicate that has to be satisfied in order to return the valid result. - /// - public Func EnsureThat { get; protected set; } - - /// - /// Async predicate that has to be satisfied in order to return the valid result. - /// - public Func> EnsureThatAsync { get; protected set; } - - /// - /// Custom provider for the IPerformance. - /// - public Func PerformanceProvider { get; protected set; } - - protected internal PerformanceWatcherConfiguration(TimeSpan? delay = null, string machineName = null) - { - Delay = delay ?? TimeSpan.FromMilliseconds(100); - MachineName = machineName ?? string.Empty; - PerformanceProvider = () => new Performance(Delay, MachineName); - } - - /// - /// Factory method for creating a new instance of fluent builder for the PerformanceWatcherConfiguration. - /// - /// Optional delay between resource usage calculation while using the default performance counter (100 ms by default). - /// Optional name of the remote machine. - /// Instance of fluent builder for the PerformanceWatcherConfiguration. - public static Builder Create(TimeSpan? delay = null, string machineName = null) => new Builder(delay, machineName); - - public abstract class Configurator : WatcherConfigurator - where T : Configurator - { - protected Configurator(TimeSpan? delay = null, string machineName = null) - { - Configuration = new PerformanceWatcherConfiguration(delay, machineName); - } - - protected Configurator(PerformanceWatcherConfiguration configuration) : base(configuration) - { - } - - /// - /// Sets the predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the PerformanceWatcherConfiguration. - public T EnsureThat(Func ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThat = ensureThat; - - return Configurator; - } - - /// - /// Sets the async predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the PerformanceWatcherConfiguration. - public T EnsureThatAsync(Func> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that async predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThatAsync = ensureThat; - - return Configurator; - } - - /// - /// Sets the custom provider for the IPerformance. - /// - /// Custom provider for the IPerformance. - /// Lambda expression returning an instance of the IPerformance. - /// Instance of fluent builder for the PerformanceWatcherConfiguration. - public T WithPerformanceProvider(Func performanceProvider) - { - if (performanceProvider == null) - { - throw new ArgumentNullException(nameof(performanceProvider), - "IPerformance provider can not be null."); - } - - Configuration.PerformanceProvider = performanceProvider; - - return Configurator; - } - } - - /// - /// Default PerformanceWatcherConfiguration fluent builder used while configuring watcher via lambda expression. - /// - public class Default : Configurator - { - public Default(PerformanceWatcherConfiguration configuration) : base(configuration) - { - SetInstance(this); - } - } - - /// - /// Extended PerformanceWatcherConfiguration fluent builder used while configuring watcher directly. - /// - public class Builder : Configurator - { - public Builder(TimeSpan? delay = null, string machineName = null) : base(delay, machineName) - { - SetInstance(this); - } - - /// - /// Builds the PerformanceWatcherConfiguration and return its instance. - /// - /// Instance of PerformanceWatcherConfiguration. - public PerformanceWatcherConfiguration Build() => Configuration; - - /// - /// Operator overload to provide casting the Builder configurator into Default configurator. - /// - /// Instance of extended Builder configurator. - /// Instance of Default builder configurator. - public static explicit operator Default(Builder builder) => new Default(builder.Configuration); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Performance/Properties/AssemblyInfo.cs b/src/Watchers/Warden.Watchers.Performance/Properties/AssemblyInfo.cs deleted file mode 100644 index 60b4182..0000000 --- a/src/Watchers/Warden.Watchers.Performance/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Watchers.Performance")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Watchers.Performance")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("b0914764-2190-47bd-b3d5-8c1d324d360e")] diff --git a/src/Watchers/Warden.Watchers.Performance/ResourceUsage.cs b/src/Watchers/Warden.Watchers.Performance/ResourceUsage.cs deleted file mode 100644 index 70ace40..0000000 --- a/src/Watchers/Warden.Watchers.Performance/ResourceUsage.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace Warden.Watchers.Performance -{ - /// - /// Usage of the resources such as CPU and RAM. - /// - public class ResourceUsage - { - /// - /// Percentage usage of the CPU. - /// - public double Cpu { get; } - - /// - /// Megabytes usage of the RAM. - /// - public double Ram { get; } - - protected ResourceUsage(double cpu, double ram) - { - Cpu = cpu; - Ram = ram; - } - - /// - /// Factory method for creating a new instance of ResourceUsage. - /// - /// Percentage usage of the CPU. - /// Megabytes usage of the RAM. - /// Instance of ResourceUsage. - public static ResourceUsage Create(double cpu, double memory) - => new ResourceUsage(cpu, memory); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Performance/Warden.Watchers.Performance.csproj b/src/Watchers/Warden.Watchers.Performance/Warden.Watchers.Performance.csproj deleted file mode 100644 index a547516..0000000 --- a/src/Watchers/Warden.Watchers.Performance/Warden.Watchers.Performance.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - Warden watcher for Performance. - 1.3.1 - Piotr Gankiewicz - net461 - Warden.Watchers.Performance - Warden.Watchers.Performance - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - false - false - false - false - false - false - - - - - - - - - - - - - - - - diff --git a/src/Watchers/Warden.Watchers.Process/Extensions.cs b/src/Watchers/Warden.Watchers.Process/Extensions.cs deleted file mode 100644 index 20b87d0..0000000 --- a/src/Watchers/Warden.Watchers.Process/Extensions.cs +++ /dev/null @@ -1,156 +0,0 @@ -using System; -using Warden.Core; - -namespace Warden.Watchers.Process -{ - /// - /// Custom extension methods for the Process watcher. - /// - public static class Extensions - { - /// - /// Extension method for adding the Process watcher to the the WardenConfiguration with the default name of Process Watcher. - /// - /// Instance of the Warden configuration builder. - /// Name of the process. - /// Optional name of the remote machine. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddProcessWatcher( - this WardenConfiguration.Builder builder, - string processName, - string machineName = null, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ProcessWatcher.Create(processName, machineName: machineName, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Process watcher to the the WardenConfiguration with the default name of Process Watcher. - /// - /// Instance of the Warden configuration builder. - /// Name of the ProcessWatcher. - /// Name of the process. - /// Optional name of the remote machine. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddProcessWatcher( - this WardenConfiguration.Builder builder, - string name, - string processName, - string machineName, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ProcessWatcher.Create(name, processName, machineName, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Process watcher to the the WardenConfiguration with the default name of Process Watcher. - /// - /// Instance of the Warden configuration builder. - /// Name of the process. - /// Optional name of the remote machine. - /// Lambda expression for configuring the ProcessWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddProcessWatcher( - this WardenConfiguration.Builder builder, - string processName, - Action configurator, - string machineName = null, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ProcessWatcher.Create(processName, machineName, configurator, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Process watcher to the the WardenConfiguration with the default name of Process Watcher. - /// - /// Instance of the Warden configuration builder. - /// Name of the ProcessWatcher. - /// Name of the process. - /// Optional name of the remote machine. - /// Lambda expression for configuring the ProcessWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddProcessWatcher( - this WardenConfiguration.Builder builder, - string name, - string processName, - Action configurator, - string machineName = null, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ProcessWatcher.Create(name, processName, machineName, configurator, group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Process watcher to the the WardenConfiguration with the default name of Process Watcher. - /// - /// Instance of the Warden configuration builder. - /// Configuration of ProcessWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddProcessWatcher( - this WardenConfiguration.Builder builder, - ProcessWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ProcessWatcher.Create(configuration, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Process watcher to the the WardenConfiguration with the default name of Process Watcher. - /// - /// Instance of the Warden configuration builder. - /// Name of the ProcessWatcher. - /// Configuration of ProcessWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddProcessWatcher( - this WardenConfiguration.Builder builder, - string name, - ProcessWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ProcessWatcher.Create(name, configuration, group), hooks, interval); - - return builder; - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Process/IProcessService.cs b/src/Watchers/Warden.Watchers.Process/IProcessService.cs deleted file mode 100644 index f6d4a07..0000000 --- a/src/Watchers/Warden.Watchers.Process/IProcessService.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Threading.Tasks; -using System.Linq; - -namespace Warden.Watchers.Process -{ - /// - /// Custom service for checking process status. - /// - public interface IProcessService - { - /// - /// Checks if the process exists and return its details. - /// - /// Name of the process. - /// - Task GetProcessInfoAsync(string name, string machineName = null); - } - - /// - /// Default implementation of the IProcessService based on System.Diagnostics.Process. - /// - public class ProcessService : IProcessService - { - public async Task GetProcessInfoAsync(string name, string machineName = null) - { - var processes = machineName == null - ? System.Diagnostics.Process.GetProcessesByName(name) - : System.Diagnostics.Process.GetProcessesByName(name, machineName); - var process = processes.FirstOrDefault(); - var processId = process?.Id ?? 0; - var exists = process != null; - var isResponding = true; - - //TODO: Fix this when .NET Core finally gets this property. - //var isResponding = process?.Responding ?? false; - - return await Task.FromResult(ProcessInfo.Create(processId, name, machineName, exists, isResponding)); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Process/ProcessInfo.cs b/src/Watchers/Warden.Watchers.Process/ProcessInfo.cs deleted file mode 100644 index 6df9c1f..0000000 --- a/src/Watchers/Warden.Watchers.Process/ProcessInfo.cs +++ /dev/null @@ -1,64 +0,0 @@ -namespace Warden.Watchers.Process -{ - /// - /// Details of the process; - /// - public class ProcessInfo - { - /// - /// Unique identifier of the process. - /// - public int Id { get; } - - /// - /// Name of the process. - /// - public string Name { get; } - - /// - /// Name of the remote machine, if specified. - /// - public string Machine { get; set; } - - - /// - /// Flag determining whether the process exists. - /// - public bool Exists { get; } - - /// - /// Flag determining whether the process is responding. - /// Currently it's always true as it's a still missing property in .NET Core. - /// - public bool Responding { get; } - - protected ProcessInfo() - { - } - - protected ProcessInfo(int id, string name, string machine, bool exists, bool responding) - { - Id = id; - Name = name; - Machine = machine; - Exists = exists; - Responding = responding; - } - - /// - /// Factory method for creating process details - /// - /// Unique identifier of the process. - /// Name of the process. - /// Flag determining whether the process exists. - /// Flag determining whether the process is responding. - /// Instance of DirectoryInfo. - public static ProcessInfo Create(int id, string name, string machine, bool exists, bool responding) - => new ProcessInfo(id, name, machine, exists, responding); - - /// - /// Factory method for creating empty process details. - /// - public static ProcessInfo Empty => new ProcessInfo(); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Process/ProcessWatcher.cs b/src/Watchers/Warden.Watchers.Process/ProcessWatcher.cs deleted file mode 100644 index 776d328..0000000 --- a/src/Watchers/Warden.Watchers.Process/ProcessWatcher.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Warden.Watchers.Process -{ - /// - /// ProcessWatcher designed for process monitoring. - /// - public class ProcessWatcher : IWatcher - { - private readonly ProcessWatcherConfiguration _configuration; - public string Name { get; } - public string Group { get; } - public const string DefaultName = "Process Watcher"; - - protected ProcessWatcher(string name, ProcessWatcherConfiguration configuration, string group) - { - if (string.IsNullOrEmpty(name)) - throw new ArgumentException("Watcher name can not be empty."); - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Process Watcher configuration has not been provided."); - } - - Name = name; - _configuration = configuration; - Group = group; - } - - public async Task ExecuteAsync() - { - var processService = _configuration.ProcessServiceProvider(); - var processInfo = await processService.GetProcessInfoAsync(_configuration.Name); - var isValid = _configuration.DoesNotHaveToBeResponding - ? processInfo.Exists - : processInfo.Exists && processInfo.Responding; - - var description = $"Process '{_configuration.Name}' does {(processInfo.Exists ? string.Empty : "not ")}exist."; - var result = ProcessWatcherCheckResult.Create(this, isValid, processInfo, description); - - return await Task.FromResult(result); - } - - /// - /// Factory method for creating a new instance of ProcessWatcher with default name of Process Watcher. - /// - /// Name of the process. - /// Optional name of the remote machine. - /// Optional lambda expression for configuring the ProcessWatcher. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of ProcessWatcher. - public static ProcessWatcher Create(string processName, - string machineName = null, - Action configurator = null, - string group = null) - => Create(DefaultName, processName, machineName, configurator, group); - - /// - /// Factory method for creating a new instance of ProcessWatcher with default name of Process Watcher. - /// - /// Name of the ProcessWatcher. - /// Name of the process. - /// Optional name of the remote machine. - /// Optional lambda expression for configuring the ProcessWatcher. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of ProcessWatcher. - public static ProcessWatcher Create(string name, string processName, - string machineName = null, - Action configurator = null, - string group = null) - { - var config = new ProcessWatcherConfiguration.Builder(processName, machineName); - configurator?.Invoke((ProcessWatcherConfiguration.Default)config); - - return Create(name, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of ProcessWatcher with default name of Process Watcher. - /// - /// Configuration of ProcessWatcher. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of ProcessWatcher. - public static ProcessWatcher Create(ProcessWatcherConfiguration configuration, string group = null) - => Create(DefaultName, configuration, group); - - /// - /// Factory method for creating a new instance of ProcessWatcher. - /// - /// Name of the ProcessWatcher. - /// Configuration of ProcessWatcher. - /// Optional name of the group that ProcessWatcher belongs to. - /// Instance of ProcessWatcher. - public static ProcessWatcher Create(string name, ProcessWatcherConfiguration configuration, - string group = null) - => new ProcessWatcher(name, configuration, group); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Process/ProcessWatcherCheckResult.cs b/src/Watchers/Warden.Watchers.Process/ProcessWatcherCheckResult.cs deleted file mode 100644 index d8a696d..0000000 --- a/src/Watchers/Warden.Watchers.Process/ProcessWatcherCheckResult.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace Warden.Watchers.Process -{ - /// - /// Custom check result type for ProcessWatcher. - /// - public class ProcessWatcherCheckResult : WatcherCheckResult - { - /// - /// Details of the process. - /// - public ProcessInfo ProcessInfo { get; } - - protected ProcessWatcherCheckResult(ProcessWatcher watcher, bool isValid, string description, - ProcessInfo processInfo) - : base(watcher, isValid, description) - { - ProcessInfo = processInfo; - } - - /// - /// Factory method for creating a new instance of ProcessWatcherCheckResult. - /// - /// Instance of ProcessWatcher. - /// Flag determining whether the performed check was valid. - /// Details of the process. - /// Custom description of the performed check. - /// Instance of ProcessWatcherCheckResult. - public static ProcessWatcherCheckResult Create(ProcessWatcher watcher, bool isValid, - ProcessInfo processInfo, string description = "") - => new ProcessWatcherCheckResult(watcher, isValid, description, processInfo); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Process/ProcessWatcherConfiguration.cs b/src/Watchers/Warden.Watchers.Process/ProcessWatcherConfiguration.cs deleted file mode 100644 index 523a143..0000000 --- a/src/Watchers/Warden.Watchers.Process/ProcessWatcherConfiguration.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Warden.Watchers.Process -{ - /// - /// Configuration of the ProcessWatcher. - /// - public class ProcessWatcherConfiguration - { - /// - /// Name of the process. - /// - public string Name { get; } - - /// - /// Optional name of the remote machine. - /// - public string MachineName { get; } - - /// - /// Flag determining whether the existing but not responding process should be treated as valid one. - /// - public bool DoesNotHaveToBeResponding { get; protected set; } - - /// - /// Predicate that has to be satisfied in order to return the valid result. - /// - public Func EnsureThat { get; protected set; } - - /// - /// Async predicate that has to be satisfied in order to return the valid result. - /// - public Func> EnsureThatAsync { get; protected set; } - - /// - /// Custom provider for the IProcessService. - /// - public Func ProcessServiceProvider { get; protected set; } - - protected internal ProcessWatcherConfiguration(string name, string machineName = null) - { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Process name can not be empty.", nameof(name)); - - Name = name; - MachineName = machineName; - ProcessServiceProvider = () => new ProcessService(); - } - - /// - /// Factory method for creating a new instance of fluent builder for the ProcessWatcherConfiguration. - /// - /// Name of the process. - /// Optional name of the remote machine. - /// Instance of fluent builder for the ProcessWatcherConfiguration. - public static Builder Create(string name, string machineName = null) => new Builder(name, machineName); - - public abstract class Configurator : WatcherConfigurator - where T : Configurator - { - protected Configurator(string name, string machineName) - { - Configuration = new ProcessWatcherConfiguration(name, machineName); - } - - protected Configurator(ProcessWatcherConfiguration configuration) : base(configuration) - { - } - - /// - /// Skips the validation of the responding state for existing process. - /// - /// Instance of fluent builder for the ProcessWatcherConfiguration. - public T DoesNotHaveToBeResponding() - { - Configuration.DoesNotHaveToBeResponding = true; - - return Configurator; - } - - /// - /// Sets the predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the ProcessWatcherConfiguration. - public T EnsureThat(Func ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThat = ensureThat; - - return Configurator; - } - - /// - /// Sets the async predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the ProcessWatcherConfiguration. - public T EnsureThatAsync(Func> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that async predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThatAsync = ensureThat; - - return Configurator; - } - - /// - /// Sets the custom provider for the IProcessService. - /// - /// Custom provider for the IProcessService. - /// Lambda expression returning an instance of the IProcessService. - /// Instance of fluent builder for the ProcessWatcherConfiguration. - public T WithProcessServiceProvider(Func processServiceProvider) - { - if (processServiceProvider == null) - { - throw new ArgumentNullException(nameof(processServiceProvider), - "IProcessService provider can not be null."); - } - - Configuration.ProcessServiceProvider = processServiceProvider; - - return Configurator; - } - } - - /// - /// Default ProcessWatcherConfiguration fluent builder used while configuring watcher via lambda expression. - /// - public class Default : Configurator - { - public Default(ProcessWatcherConfiguration configuration) : base(configuration) - { - SetInstance(this); - } - } - - /// - /// Extended ProcessWatcherConfiguration fluent builder used while configuring watcher directly. - /// - public class Builder : Configurator - { - public Builder(string name, string machineName = null) : base(name, machineName) - { - SetInstance(this); - } - - /// - /// Builds the ProcessWatcherConfiguration and return its instance. - /// - /// Instance of ProcessWatcherConfiguration. - public ProcessWatcherConfiguration Build() => Configuration; - - /// - /// Operator overload to provide casting the Builder configurator into Default configurator. - /// - /// Instance of extended Builder configurator. - /// Instance of Default builder configurator. - public static explicit operator Default(Builder builder) => new Default(builder.Configuration); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Process/Properties/AssemblyInfo.cs b/src/Watchers/Warden.Watchers.Process/Properties/AssemblyInfo.cs deleted file mode 100644 index 0c249bd..0000000 --- a/src/Watchers/Warden.Watchers.Process/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -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: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Watchers.Process")] -[assembly: AssemblyTrademark("")] - -// 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("e66f4313-6747-4201-b49c-3093031cfb7c")] diff --git a/src/Watchers/Warden.Watchers.Process/Warden.Watchers.Process.csproj b/src/Watchers/Warden.Watchers.Process/Warden.Watchers.Process.csproj deleted file mode 100644 index 9e008fc..0000000 --- a/src/Watchers/Warden.Watchers.Process/Warden.Watchers.Process.csproj +++ /dev/null @@ -1,41 +0,0 @@ - - - - Warden watcher for Process. - 1.3.1 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Watchers.Process - Warden.Watchers.Process - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Watchers/Warden.Watchers.Redis/Extensions.cs b/src/Watchers/Warden.Watchers.Redis/Extensions.cs deleted file mode 100644 index 73d4e6c..0000000 --- a/src/Watchers/Warden.Watchers.Redis/Extensions.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System; - -using Warden.Core; - -namespace Warden.Watchers.Redis -{ - /// - /// Custom extension methods for the Redis watcher. - /// - public static class Extensions - { - /// - /// Extension method for adding the Redis watcher to the the WardenConfiguration with the default name of Redis Watcher. - /// - /// Instance of the Warden configuration builder. - /// Connection string of the Redis database.m - /// Name of the Redis database. - /// Optional timeout of the Redis query (5 seconds by default). - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that param belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddRedisWatcher( - this WardenConfiguration.Builder builder, - string connectionString, - int database, - TimeSpan? timeout = null, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(RedisWatcher.Create(connectionString, database, timeout, group: group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Redis watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the RedisWatcher. - /// Connection string of the Redis database. - /// Name of the Redis database. - /// Optional timeout of the Redis query (5 seconds by default). - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that param belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddRedisWatcher( - this WardenConfiguration.Builder builder, - string name, - string connectionString, - int database, - TimeSpan? timeout = null, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(RedisWatcher.Create(name, connectionString, database, timeout, group: group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Redis watcher to the the WardenConfiguration with the default name of Redis Watcher. - /// - /// Instance of the Warden configuration builder. - /// Connection string of the Redis database. - /// Name of the Redis database. - /// Lambda expression for configuring the RedisWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional timeout of the Redis query (5 seconds by default). - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that param belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddRedisWatcher( - this WardenConfiguration.Builder builder, - string connectionString, - int database, - Action configurator, - Action hooks = null, - TimeSpan? timeout = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(RedisWatcher.Create(connectionString, database, timeout, configurator, group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Redis watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the RedisWatcher. - /// Connection string of the Redis database. - /// Name of the Redis database. - /// Lambda expression for configuring the RedisWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional timeout of the Redis query (5 seconds by default). - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that param belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddRedisWatcher( - this WardenConfiguration.Builder builder, - string name, - string connectionString, - int database, - Action configurator, - Action hooks = null, - TimeSpan? timeout = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(RedisWatcher.Create(name, connectionString, database, timeout, configurator, group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Redis watcher to the the WardenConfiguration with the default name of Redis Watcher. - /// - /// Instance of the Warden configuration builder. - /// Configuration of RedisWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that param belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddRedisWatcher( - this WardenConfiguration.Builder builder, - RedisWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(RedisWatcher.Create(configuration, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Redis watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the RedisWatcher. - /// Configuration of RedisWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that param belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddRedisWatcher( - this WardenConfiguration.Builder builder, - string name, - RedisWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(RedisWatcher.Create(name, configuration, group), hooks, interval); - - return builder; - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Redis/IRedis.cs b/src/Watchers/Warden.Watchers.Redis/IRedis.cs deleted file mode 100644 index 3b67177..0000000 --- a/src/Watchers/Warden.Watchers.Redis/IRedis.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using StackExchange.Redis; - -namespace Warden.Watchers.Redis -{ - /// - /// Custom Redis server connector for executing the commands. - /// - public interface IRedis - { - /// - /// Executes the Redis query and returns a collection of the dynamic results. - /// - /// Redis query. - /// - Task> QueryAsync(string query); - } - - /// - /// Default implementation of the IRedis based on StackExchange.Redis. - /// - public class Redis : IRedis - { - private readonly IDatabase _database; - - public Redis(IDatabase database) - { - _database = database; - } - - public async Task> QueryAsync(string query) - { - if (string.IsNullOrWhiteSpace(query)) - return Enumerable.Empty(); - - var command = new Command(query); - - return await ExecuteCommandAsync(command); - } - - private async Task> ExecuteCommandAsync(Command command) - { - if (string.IsNullOrWhiteSpace(command.Name)) - return Enumerable.Empty(); - - switch (command.Name) - { - case "get": - return await ExecuteGetAsync(command); - case "set": - return await ExecuteSetAsync(command); - case "lrange": - return await ExecuteLRangeAsync(command); - default: - throw new Exception($"Redis command is not implemented: '{command.Name}'."); - } - } - - private async Task> ExecuteGetAsync(Command command) - => new List {await _database.StringGetAsync(command.Arguments[0])}; - - private async Task> ExecuteSetAsync(Command command) - => new List {await _database.StringSetAsync(command.Arguments[0], command.Arguments[1])}; - - private async Task> ExecuteLRangeAsync(Command command) - => new List - { - await _database.ListRangeAsync(command.Arguments[0], - long.Parse(command.Arguments[1]), - long.Parse(command.Arguments[2])) - }; - - private class Command - { - public string Name { get; } - public string[] Arguments { get; } - - public Command(string query) - { - var command = query.ToLowerInvariant().Trim().Split(' '); - if (!command.Any()) - return; - - Name = command[0].ToLowerInvariant(); - Arguments = command.Skip(1).ToArray(); - } - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Redis/IRedisConnection.cs b/src/Watchers/Warden.Watchers.Redis/IRedisConnection.cs deleted file mode 100644 index 10ed245..0000000 --- a/src/Watchers/Warden.Watchers.Redis/IRedisConnection.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Threading.Tasks; -using StackExchange.Redis; - -namespace Warden.Watchers.Redis -{ - public interface IRedisConnection - { - - /// - /// Connection string of the Redis server. - /// - string ConnectionString { get; } - - /// - /// Timeout for connection to the Redis server. - /// - TimeSpan Timeout { get; } - - /// - /// Opens a connection to the Redis database. - /// - /// Instance of IRedis. - Task GetDatabaseAsync(int database); - - /// - /// Closes the connection to Redis - /// - Task CloseConnectionAsync(); - } - - /// - /// Default implementation of the IRedisConnection based on the StackExchange.Redis. - /// - public class RedisConnection : IRedisConnection - { - private IConnectionMultiplexer _connectionMultiplexer; - - public string ConnectionString { get; } - public TimeSpan Timeout { get; } - - public RedisConnection(string connectionString, TimeSpan timeout) - { - ConnectionString = connectionString; - Timeout = timeout; - } - - public async Task GetDatabaseAsync(int databaseId) - { - _connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(new ConfigurationOptions - { - EndPoints = { ConnectionString }, - ConnectTimeout = (int)Timeout.TotalMilliseconds - }); - - var database = _connectionMultiplexer.GetDatabase(databaseId); - - return new Redis(database); - } - - public async Task CloseConnectionAsync() - { - if (_connectionMultiplexer != null && _connectionMultiplexer.IsConnected) - { - await _connectionMultiplexer.CloseAsync(); - } - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Redis/Properties/AssemblyInfo.cs b/src/Watchers/Warden.Watchers.Redis/Properties/AssemblyInfo.cs deleted file mode 100644 index d4534ef..0000000 --- a/src/Watchers/Warden.Watchers.Redis/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Watchers.Redis")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Watchers.Redis")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("56bcc5af-7e4a-4def-ab68-eb220c8f2fa4")] diff --git a/src/Watchers/Warden.Watchers.Redis/RedisWatcher.cs b/src/Watchers/Warden.Watchers.Redis/RedisWatcher.cs deleted file mode 100644 index d4a08ef..0000000 --- a/src/Watchers/Warden.Watchers.Redis/RedisWatcher.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System; -using System.Threading.Tasks; -using StackExchange.Redis; - -namespace Warden.Watchers.Redis -{ - /// - /// RedisWatcher designed for Redis monitoring. - /// - public class RedisWatcher : IWatcher - { - private readonly IRedisConnection _connection; - private readonly RedisWatcherConfiguration _configuration; - public string Name { get; } - public string Group { get; } - public const string DefaultName = "Redis Watcher"; - - protected RedisWatcher(string name, RedisWatcherConfiguration configuration, string group) - { - if (string.IsNullOrEmpty(name)) - throw new ArgumentException("Watcher name can not be empty."); - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Redis Watcher configuration has not been provided."); - } - - Name = name; - _configuration = configuration; - Group = group; - _connection = _configuration.ConnectionProvider(_configuration.ConnectionString); - } - - public async Task ExecuteAsync() - { - try - { - var redis = _configuration.RedisProvider?.Invoke() ?? await _connection.GetDatabaseAsync(_configuration.Database); - if (redis == null) - { - return RedisWatcherCheckResult.Create(this, false, _configuration.Database, - _configuration.ConnectionString, $"Database: '{_configuration.Database}' has not been found."); - } - if (string.IsNullOrWhiteSpace(_configuration.Query)) - { - return RedisWatcherCheckResult.Create(this, true, _configuration.Database, - _configuration.ConnectionString, - $"Database: {_configuration.Database} has been sucessfully checked."); - } - - return await ExecuteForQueryAsync(redis); - } - catch (RedisException exception) - { - return RedisWatcherCheckResult.Create(this, false, _configuration.Database, - _configuration.ConnectionString, exception.Message); - } - catch (Exception exception) - { - throw new WatcherException("There was an error while trying to access the Redis.", exception); - } - finally - { - await _connection.CloseConnectionAsync(); - } - } - - private async Task ExecuteForQueryAsync(IRedis redis) - { - var queryResult = await redis.QueryAsync(_configuration.Query); - var isValid = true; - if (_configuration.EnsureThatAsync != null) - isValid = await _configuration.EnsureThatAsync?.Invoke(queryResult); - - isValid = isValid && (_configuration.EnsureThat?.Invoke(queryResult) ?? true); - var description = $"Redis check has returned {(isValid ? "valid" : "invalid")} result for " + - $"database: '{_configuration.Database}' and given query."; - - return RedisWatcherCheckResult.Create(this, isValid, _configuration.Database, - _configuration.ConnectionString, _configuration.Query, queryResult, description); - } - - /// - /// Factory method for creating a new instance of RedisWatcher with default name of Redis Watcher. - /// - /// Connection string of the Redis server. - /// Id of the Redis database. - /// Optional timeout of the Redis query (5 seconds by default). - /// Optional lambda expression for configuring the RedisWatcher. - /// Optional name of the group that param belongs to. - /// Instance of RedisWatcher. - public static RedisWatcher Create(string connectionString, int database, - TimeSpan? timeout = null, Action configurator = null, - string group = null) - => Create(DefaultName, connectionString, database, timeout, configurator, group); - - /// - /// Factory method for creating a new instance of RedisWatcher. - /// - /// Name of the RedisWatcher. - /// Connection string of the Redis server. - /// Id of the Redis database. - /// Optional timeout of the Redis query (5 seconds by default). - /// Optional lambda expression for configuring the RedisWatcher. - /// Optional name of the group that param belongs to. - /// Instance of RedisWatcher. - public static RedisWatcher Create(string name, string connectionString, int database, - TimeSpan? timeout = null, Action configurator = null, - string group = null) - { - var config = new RedisWatcherConfiguration.Builder(connectionString, database, timeout); - configurator?.Invoke((RedisWatcherConfiguration.Default)config); - - return Create(name, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of RedisWatcher with default name of Redis Watcher. - /// - /// Configuration of RedisWatcher. - /// Optional name of the group that param belongs to. - /// Instance of RedisWatcher. - public static RedisWatcher Create(RedisWatcherConfiguration configuration, string group = null) - => Create(DefaultName, configuration, group); - - /// - /// Factory method for creating a new instance of RedisWatcher. - /// - /// Name of the RedisWatcher. - /// Configuration of RedisWatcher. - /// Optional name of the group that param belongs to. - /// Instance of RedisWatcher. - public static RedisWatcher Create(string name, RedisWatcherConfiguration configuration, string group = null) - => new RedisWatcher(name, configuration, group); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Redis/RedisWatcherCheckResult.cs b/src/Watchers/Warden.Watchers.Redis/RedisWatcherCheckResult.cs deleted file mode 100644 index 18fb032..0000000 --- a/src/Watchers/Warden.Watchers.Redis/RedisWatcherCheckResult.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace Warden.Watchers.Redis -{ - /// - /// Custom check result type for RedisWatcher. - /// - public class RedisWatcherCheckResult : WatcherCheckResult - { - /// - /// Connection string of the Redis server. - /// - public string ConnectionString { get; protected set; } - - /// - /// Id of the Redis database. - /// - public int Database { get; } - - /// - /// Redis query. - /// - public string Query { get; } - - /// - /// Collection of dynamic results of the Redis query. - /// - public IEnumerable QueryResult { get; } - - protected RedisWatcherCheckResult(RedisWatcher watcher, bool isValid, string description, - int database, string connectionString, string query, IEnumerable queryResult) - : base(watcher, isValid, description) - { - Database = database; - ConnectionString = connectionString; - Query = query; - QueryResult = queryResult; - } - - /// - /// Factory method for creating a new instance of RedisWatcherCheckResult. - /// - /// Instance of RedisWatcher. - /// Flag determining whether the performed check was valid. - /// Id of the Redis database. - /// Connection string of the Redis server. - /// Custom description of the performed check. - /// Instance of RedisWatcherCheckResult. - public static RedisWatcherCheckResult Create(RedisWatcher watcher, bool isValid, - int database, string connectionString, string description = "") - => new RedisWatcherCheckResult(watcher, isValid, description, database, - connectionString, string.Empty, Enumerable.Empty()); - - /// - /// Factory method for creating a new instance of RedisWatcherCheckResult. - /// - /// Instance of RedisWatcher. - /// Flag determining whether the performed check was valid. - /// Connection string of the Redis server. - /// Id of the Redis database. - /// Redis query. - /// Collection of dynamic results of the Redis query. - /// Custom description of the performed check. - /// Instance of RedisWatcherCheckResult. - public static RedisWatcherCheckResult Create(RedisWatcher watcher, bool isValid, - int database, string connectionString, string query, IEnumerable queryResult, - string description = "") - => new RedisWatcherCheckResult(watcher, isValid, description, database, connectionString, query, - queryResult); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Redis/RedisWatcherConfiguration.cs b/src/Watchers/Warden.Watchers.Redis/RedisWatcherConfiguration.cs deleted file mode 100644 index 8cda282..0000000 --- a/src/Watchers/Warden.Watchers.Redis/RedisWatcherConfiguration.cs +++ /dev/null @@ -1,228 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Warden.Core; - -namespace Warden.Watchers.Redis -{ - /// - /// Configuration of the RedisWatcher. - /// - public class RedisWatcherConfiguration - { - /// - /// Connection string of the Redis server. - /// - public string ConnectionString { get; protected set; } - - /// - /// Id of the Redis database. - /// - public int Database { get; protected set; } - - /// - /// Redis query. - /// - public string Query { get; protected set; } - - /// - /// Optional timeout of the Redis (5 seconds by default). - /// - public TimeSpan Timeout { get; protected set; } - - /// - /// Custom provider for the IRedisConnection. Input parameter is connection string. - /// - public Func ConnectionProvider { get; protected set; } - - /// - /// Custom provider for the IRedis. - /// - public Func RedisProvider { get; protected set; } - - /// - /// Predicate that has to be satisfied in order to return the valid result. - /// - public Func, bool> EnsureThat { get; protected set; } - - /// - /// Async predicate that has to be satisfied in order to return the valid result. - /// - public Func, Task> EnsureThatAsync { get; protected set; } - - protected internal RedisWatcherConfiguration(string connectionString, int database, TimeSpan? timeout = null) - { - if (string.IsNullOrEmpty(connectionString)) - throw new ArgumentException("Redis connection string can not be empty.", nameof(connectionString)); - if (database < 0) - throw new ArgumentException("Database id can not be less than 0.", nameof(database)); - - if (timeout.HasValue) - { - ValidateTimeout(timeout.Value); - Timeout = timeout.Value; - } - else - Timeout = TimeSpan.FromSeconds(5); - - Database = database; - ConnectionString = connectionString; - ConnectionProvider = redisConnectionString => new RedisConnection(redisConnectionString, Timeout); - } - - protected static void ValidateTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); - } - - /// - /// Factory method for creating a new instance of fluent builder for the RedisWatcherConfiguration. - /// - /// Connection string of the Redis server. - /// Id of the Redis database. - /// Optional timeout of the Redis (5 seconds by default). - /// Instance of fluent builder for the RedisWatcherConfiguration. - public static Builder Create(string connectionString, int database, TimeSpan? timeout = null) - => new Builder(connectionString, database, timeout); - - /// - /// Fluent builder for the RedisWatcherConfiguration. - /// - public abstract class Configurator : WatcherConfigurator - where T : Configurator - { - protected Configurator(string connectionString, int database, TimeSpan? timeout = null) - { - Configuration = new RedisWatcherConfiguration(connectionString, database, timeout); - } - - protected Configurator(RedisWatcherConfiguration configuration) : base(configuration) - { - } - - /// - /// Sets the Redis query. - /// - /// Redis query. - /// Instance of fluent builder for the RedisWatcherConfiguration. - public T WithQuery(string query) - { - if (string.IsNullOrEmpty(query)) - throw new ArgumentException("Redis query can not be empty.", nameof(query)); - - Configuration.Query = query; - - return Configurator; - } - - - /// - /// Sets the predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the RedisWatcherConfiguration. - public T EnsureThat(Func, bool> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThat = ensureThat; - - return Configurator; - } - - /// - /// Sets the async predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the RedisWatcherConfiguration. - public T EnsureThatAsync(Func, Task> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that async predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThatAsync = ensureThat; - - return Configurator; - } - - /// - /// Sets the custom provider for the IRedisConnection. - /// - /// Custom provider for the IRedisConnection. - /// Lambda expression taking as an input connection string - /// and returning an instance of the IRedisConnection. - /// Instance of fluent builder for the RedisWatcherConfiguration. - public T WithConnectionProvider(Func connectionProvider) - { - if (connectionProvider == null) - { - throw new ArgumentNullException(nameof(connectionProvider), - "Redis connection provider can not be null."); - } - - Configuration.ConnectionProvider = connectionProvider; - - return Configurator; - } - - /// - /// Sets the custom provider for the IRedis. - /// - /// Custom provider for the IRedis. - /// Lambda expression returning an instance of the IRedis. - /// Instance of fluent builder for the RedisWatcherConfiguration. - public T WithRedisProvider(Func redisProvider) - { - if (redisProvider == null) - { - throw new ArgumentNullException(nameof(redisProvider), "Redis provider can not be null."); - } - - Configuration.RedisProvider = redisProvider; - - return Configurator; - } - } - - /// - /// Default RedisWatcherConfiguration fluent builder used while configuring watcher via lambda expression. - /// - public class Default : Configurator - { - public Default(RedisWatcherConfiguration configuration) : base(configuration) - { - SetInstance(this); - } - } - - /// - /// Extended RedisWatcherConfiguration fluent builder used while configuring watcher directly. - /// - public class Builder : Configurator - { - public Builder(string connectionString, int database, TimeSpan? timeout = null) - : base(connectionString, database, timeout) - { - SetInstance(this); - } - - /// - /// Builds the RedisWatcherConfiguration and return its instance. - /// - /// Instance of RedisWatcherConfiguration. - public RedisWatcherConfiguration Build() => Configuration; - - /// - /// Operator overload to provide casting the Builder configurator into Default configurator. - /// - /// Instance of extended Builder configurator. - /// Instance of Default builder configurator. - public static explicit operator Default(Builder builder) => new Default(builder.Configuration); - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Redis/Warden.Watchers.Redis.csproj b/src/Watchers/Warden.Watchers.Redis/Warden.Watchers.Redis.csproj deleted file mode 100644 index cfa9e69..0000000 --- a/src/Watchers/Warden.Watchers.Redis/Warden.Watchers.Redis.csproj +++ /dev/null @@ -1,39 +0,0 @@ - - - - Warden watcher for Redis. - 1.3.2 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Watchers.Redis - Warden.Watchers.Redis - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - diff --git a/src/Watchers/Warden.Watchers.Server/ConnectionInfo.cs b/src/Watchers/Warden.Watchers.Server/ConnectionInfo.cs deleted file mode 100644 index 3449562..0000000 --- a/src/Watchers/Warden.Watchers.Server/ConnectionInfo.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Net; -using System.Net.NetworkInformation; - -namespace Warden.Watchers.Server -{ - /// - /// Details of the resolved connection to the specified hostname and port. - /// - public class ConnectionInfo - { - /// - /// Resolved hostname. - /// - public string Hostname { get; } - - /// - /// IP address of the resolved hostname. - /// - public IPAddress IpAddress { get; } - - /// - /// Optional port number that was checked. - /// - public int Port { get; } - - /// - /// Flag determining whether the port number (if specified) is being opened. - /// - public bool PortOpened { get; } - - /// - /// Status of the ping request. - /// - public IPStatus PingStatus { get; } - - /// - /// Status message of the ping request. - /// - public string PingStatusMessage { get; } - - protected ConnectionInfo(string hostname, IPAddress ipAddress, - int port, bool portOpened, - IPStatus pingStatus, string pingStatusMessage) - { - Hostname = hostname; - Port = port; - PortOpened = portOpened; - PingStatus = pingStatus; - PingStatusMessage = pingStatusMessage; - IpAddress = ipAddress; - } - - /// - /// Factory method for creating connection info details. - /// - /// Resolved hostname. - /// IP address of the resolved hostname. - /// Optional port number that was checked. - /// Flag determining whether the port number (if specified) is being opened. - /// Status of the ping request. - /// Status message of the ping request. - /// Instance of ConnectionInfo. - public static ConnectionInfo Create(string hostname, IPAddress ipAddress, - int port, bool portOpened, IPStatus pingStatus, string pingStatusMessage) - => new ConnectionInfo(hostname, ipAddress, port, portOpened, pingStatus, pingStatusMessage); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Server/Extensions.cs b/src/Watchers/Warden.Watchers.Server/Extensions.cs deleted file mode 100644 index e9d0012..0000000 --- a/src/Watchers/Warden.Watchers.Server/Extensions.cs +++ /dev/null @@ -1,175 +0,0 @@ -using System; -using Warden.Core; - -namespace Warden.Watchers.Server -{ - /// - /// Custom extension methods for the Server watcher. - /// - public static class Extensions - { - /// - /// Gets the hostname (if possible) from url-formatted input string. - /// - /// The URL formatted string. - /// The URL string without protocol part. If URL has invalid format, returns original input value. - internal static string GetHostname(this string hostname) - { - if (hostname == null) - throw new ArgumentNullException(nameof(hostname)); - - try - { - var uri = new Uri(hostname); - - return uri.Host; - } - catch (UriFormatException) - { - return hostname; - } - } - - /// - /// Validates the hostname. - /// - /// The URL formatted string. - /// The URL string without protocol part. If URL has invalid format an exception is thrown. - internal static void ValidateHostname(this string hostname) - { - if (string.IsNullOrEmpty(hostname)) - throw new ArgumentException("Hostname can not be empty.", nameof(hostname)); - - if (hostname.Contains("://")) - { - throw new ArgumentException("The hostname should not contain protocol. " + - $"Did you mean \" {hostname.GetHostname()}\"?", nameof(hostname)); - } - } - - /// - /// Extension method for adding the Server watcher to the the WardenConfiguration with the default name of Server Watcher. - /// - /// Instance of the Warden configuration builder. - /// Hostname to be resolved. - /// Optional port number of the hostname (0 means not specified). - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ServerWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddServerWatcher( - this WardenConfiguration.Builder builder, - string hostname, - int port = 0, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ServerWatcher.Create(hostname, port, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Server watcher to the the WardenConfiguration.. - /// - /// Instance of the Warden configuration builder. - /// Name of the Server watcher. - /// Hostname to be resolved. - /// Optional port number of the hostname (0 means not specified). - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ServerWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddServerWatcher( - this WardenConfiguration.Builder builder, - string name, - string hostname, - int port = 0, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ServerWatcher.Create(name, hostname, port, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Server watcher to the the WardenConfiguration with the default name of Server watcher. - /// - /// Instance of the Warden configuration builder. - /// Hostname to be resolved. - /// Lambda expression for configuring the ServerWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional port number of the hostname (0 means not specified). - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ServerWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddServerWatcher( - this WardenConfiguration.Builder builder, - string hostname, - Action configurator, - Action hooks = null, - int port = 0, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ServerWatcher.Create(hostname, port, configurator, group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Server watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the ServerWatcher. - /// Hostname to be resolved. - /// Lambda expression for configuring the ServerWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional port number of the hostname (0 means not specified). - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ServerWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddServerWatcher( - this WardenConfiguration.Builder builder, - string name, - string hostname, - Action configurator, - Action hooks = null, - int port = 0, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ServerWatcher.Create(name, hostname, port, configurator, group), - hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Server watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the ServerWatcher. - /// Configuration of ServerWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that ServerWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddServerWatcher( - this WardenConfiguration.Builder builder, - string name, - ServerWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(ServerWatcher.Create(name, configuration, group), hooks, interval); - - return builder; - } - } -} diff --git a/src/Watchers/Warden.Watchers.Server/IDnsResolver.cs b/src/Watchers/Warden.Watchers.Server/IDnsResolver.cs deleted file mode 100644 index 14d125f..0000000 --- a/src/Watchers/Warden.Watchers.Server/IDnsResolver.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Net; -using System.Linq; - -namespace Warden.Watchers.Server -{ - /// - /// Custom DNS resolver service. - /// - public interface IDnsResolver : IDisposable - { - /// - /// Gets the IP address or hostname. - /// - /// A hostname or IPv4 address. - /// IP address of the resolved hostname (if exists). - IPAddress GetIpAddress(string hostnameOrIp); - } - - /// - /// Default implementation of the IDnsResolver. - /// - public class DnsResolver : IDnsResolver - { - /// - /// Gets the IP address of provided hostname or provider. - /// - /// A hostname or IPv4 address. - /// An IP address or null if cannot be resolved. - public IPAddress GetIpAddress(string hostnameOrIp) => Dns.GetHostAddresses(hostnameOrIp).FirstOrDefault(); - - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - public void Dispose() - { - } - } -} diff --git a/src/Watchers/Warden.Watchers.Server/IPinger.cs b/src/Watchers/Warden.Watchers.Server/IPinger.cs deleted file mode 100644 index 717f2a4..0000000 --- a/src/Watchers/Warden.Watchers.Server/IPinger.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Net; -using System.Net.NetworkInformation; -using System.Threading.Tasks; - -namespace Warden.Watchers.Server -{ - /// - /// Provides a functionality to ping specified address. - /// - public interface IPinger : IDisposable - { - /// - /// Sends the ICMP echo request to the specified IP address. - /// - /// A destination IP address. - /// Optional timeout for connection. - /// ICMP echo request status. - Task PingAsync(IPAddress addressIp, TimeSpan? timeout = null); - } - - public class Pinger : IPinger - { - /// - /// Sends the ICMP echo request to the specified IP address. - /// - /// A destination IP address. - /// Optional timeout for connection. - /// ICMP echo request status. - public async Task PingAsync(IPAddress addressIp, TimeSpan? timeout = null) - { - var ping = new Ping(); - if (timeout.HasValue) - { - return await ping.SendPingAsync(addressIp, timeout.Value.Milliseconds) - .ContinueWith(pingTask => pingTask.Result.Status); - } - - return await ping.SendPingAsync(addressIp) - .ContinueWith(pingTask => pingTask.Result.Status); - } - - public void Dispose() - { - } - } -} diff --git a/src/Watchers/Warden.Watchers.Server/ITcpClient.cs b/src/Watchers/Warden.Watchers.Server/ITcpClient.cs deleted file mode 100644 index b7c3dac..0000000 --- a/src/Watchers/Warden.Watchers.Server/ITcpClient.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; -using System.Threading.Tasks; - -namespace Warden.Watchers.Server -{ - /// - /// Custom TCP Client service. - /// - public interface ITcpClient : IDisposable - { - /// - /// Flag determining whether the connection has been established. - /// - bool IsConnected { get; } - - /// - /// Connects to thespecified IP address via TCP protocol. - /// - /// IP address of the server. - /// Port number of the server to connect to. - /// Optional timeout of the connection. - /// - Task ConnectAsync(IPAddress ipAddress, int port, TimeSpan? timeout = null); - } - - /// - /// Default implementation of the ITcpClient. - /// - public class TcpClient : ITcpClient - { - /// - /// Socket instance that is used to connect to the remote server. - /// - private readonly Socket _socket; - - /// - /// Gets a flag that indicates whether the current instance is connected to any server. - /// - public bool IsConnected { get; protected set; } - - /// - /// Creates a default TCP Client that allows to connect to a remote server via TCP protocol. - /// - public TcpClient() - { - _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - } - - /// - /// Connects to the specified IP address via TCP protocol. - /// - /// IP address of a server. - /// Port number of the hostname to connect to. - /// Optional timeout for the connection. - /// Task that perfroms a connection. - public async Task ConnectAsync(IPAddress ipAddress, int port, TimeSpan? timeout = null) - { - try - { - var asyncConnectionResult = _socket.BeginConnect(ipAddress, port, null, null); - await Task.Factory.StartNew(() => timeout.HasValue - ? asyncConnectionResult.AsyncWaitHandle.WaitOne(timeout.Value) - : asyncConnectionResult.AsyncWaitHandle.WaitOne()); - - IsConnected = _socket.Connected; - _socket.EndConnect(asyncConnectionResult); - } - catch (SocketException) - { - IsConnected = false; - } - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - _socket.Dispose(); - } - } -} diff --git a/src/Watchers/Warden.Watchers.Server/Properties/AssemblyInfo.cs b/src/Watchers/Warden.Watchers.Server/Properties/AssemblyInfo.cs deleted file mode 100644 index 256994c..0000000 --- a/src/Watchers/Warden.Watchers.Server/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -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: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Watchers.ServerStatus")] -[assembly: AssemblyTrademark("")] - -// 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("3043ba97-5ec7-450a-a80a-b0d5c199733c")] diff --git a/src/Watchers/Warden.Watchers.Server/ServerWatcher.cs b/src/Watchers/Warden.Watchers.Server/ServerWatcher.cs deleted file mode 100644 index a6ee384..0000000 --- a/src/Watchers/Warden.Watchers.Server/ServerWatcher.cs +++ /dev/null @@ -1,292 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.NetworkInformation; -using System.Threading.Tasks; - -namespace Warden.Watchers.Server -{ - /// - /// ServerWatcher designed for monitoring server availability including opened ports (if specified). - /// - public class ServerWatcher : IWatcher - { - private readonly ServerWatcherConfiguration _configuration; - - private readonly Dictionary _pingStatusMessages = new Dictionary - { - {IPStatus.Unknown, "ICMP echo request to host '{0}' failed because of uknown error."}, - {IPStatus.Success, "Success."}, - {IPStatus.BadDestination, "ICMP echo request failed. Host '{0}' cannot receive ICMP echo requests."}, - {IPStatus.BadHeader, "ICMP echo request to host '{0}' failed because of invalid header."}, - {IPStatus.BadOption, "ICMP echo request to host '{0}' failed contains invalid option."}, - { - IPStatus.BadRoute, - "ICMP echo request failed because there is no valid route between source and host '{0}'." - }, - {IPStatus.DestinationHostUnreachable, "ICMP echo request failed because host '{0}' is not reachable."}, - { - IPStatus.DestinationNetworkUnreachable, - "ICMP echo request failed because network that contains host '{0}' is not reachable." - }, - { - IPStatus.DestinationPortUnreachable, - "ICMP echo request failed because the Ping on host '{0}' is not reachable." - }, - { - IPStatus.DestinationProtocolUnreachable, - "ICMP echo request failed because host '{0}' doesn't supPing the packet's protocol." - }, - {IPStatus.HardwareError, "ICMP echo request to host '{0}' failed because of hardware error."}, - {IPStatus.IcmpError, "ICMP echo request to host '{0}' failed because of ICMP protocol error."}, - { - IPStatus.TtlExpired, - "ICMP echo request to host '{0}' failed because its Time To Live (TTL) reached 0, so forwarding node (router or gateway) discared the request." - }, - { - IPStatus.TimedOut, - "ICMP echo request failed because the reply from host '{0}' was not received in specified time." - }, - {IPStatus.SourceQuench, "ICMP echo request failed because host '{0}' discarded the packet."}, - {IPStatus.NoResources, "ICMP echo request to host '{0}' failed because of insufficient sources."}, - { - IPStatus.PacketTooBig, - "ICMP echo request to host '{0}' failed because the packet is larger than MTU of node (router of gateway)." - }, - { - IPStatus.ParameterProblem, - "ICMP echo request to host '{0}' failed because the node (router or gateway) failed while processing packet header." - }, - }; - - public string Group { get; } - - /// - /// Default name of the ServerWatcher. - /// - public const string DefaultName = "Server Watcher"; - - /// - /// Name of the ServerWatcher. - /// - public string Name { get; } - - protected ServerWatcher(string name, ServerWatcherConfiguration configuration, string group) - { - if (string.IsNullOrEmpty(name)) - throw new ArgumentException("Watcher name can not be empty."); - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Server watcher configuration has not been provided."); - } - - Name = name; - _configuration = configuration; - Group = group; - } - - public async Task ExecuteAsync() - { - try - { - return await ExecuteCheckAsync(); - } - catch (TaskCanceledException exception) - { - var connectionInfo = ConnectionInfo.Create(_configuration.Hostname, - IPAddress.None, _configuration.Port, false, IPStatus.Unknown, string.Empty); - - return ServerWatcherCheckResult.Create(this, false, connectionInfo, - "A connection timeout has occurred while trying to access the hostname: " + - $"'{_configuration.Hostname}' using port: {_configuration.Port}."); - } - catch (Exception exception) - { - throw new WatcherException("There was an error while trying to access the hostname: " + - $"'{_configuration.Hostname}' using port: {_configuration.Port}.", - exception); - } - } - - private async Task ExecuteCheckAsync() - { - using (var servicesProvider = GetServicesProviders()) - { - var ipStatusAndAddressAndOpenedPort = await TryConnectAsync(servicesProvider); - var ipStatus = ipStatusAndAddressAndOpenedPort.Item1; - var ipAddress = ipStatusAndAddressAndOpenedPort.Item2; - var portOpened = ipStatusAndAddressAndOpenedPort.Item3; - var ipStatusMessage = _pingStatusMessages[ipStatus]; - var portSpecified = _configuration.Port > 0; - var connectionInfo = ConnectionInfo.Create(_configuration.Hostname, - ipAddress, _configuration.Port, portOpened, ipStatus, ipStatusMessage); - - if (ipStatus == IPStatus.Unknown) - { - return ServerWatcherCheckResult.Create(this, false, connectionInfo, - $"Could not resolve the hostname '{_configuration.Hostname}' " + - $"{(portSpecified ? $"using port: {_configuration.Port}" : string.Empty)}. " + - $"Ping status: '{ipStatusMessage}'"); - } - if (ipStatus != IPStatus.Success) - { - return ServerWatcherCheckResult.Create(this, false, connectionInfo, - $"Unable to connect to the hostname '{_configuration.Hostname}' " + - $"{(portSpecified ? $"using port: {_configuration.Port}" : string.Empty)}. " + - $"Ping status: '{ipStatusMessage}'"); - } - if (portSpecified && !portOpened) - { - return ServerWatcherCheckResult.Create(this, false, connectionInfo, - $"Unable to connect to the hostname '{_configuration.Hostname}' " + - $"using port: {_configuration.Port}. " + - $"Ping status: '{ipStatusMessage}'"); - } - - return await EnsureAsync(connectionInfo); - } - } - - private async Task EnsureAsync(ConnectionInfo connectionInfo) - { - var isValid = true; - var portSpecified = _configuration.Port > 0; - if (_configuration.EnsureThatAsync != null) - isValid = await _configuration.EnsureThatAsync?.Invoke(connectionInfo); - - isValid = isValid && (_configuration.EnsureThat?.Invoke(connectionInfo) ?? true); - - return ServerWatcherCheckResult.Create(this, isValid, connectionInfo, - $"Successfully connected to the hostname '{_configuration.Hostname}' " + - $"{(portSpecified ? $"using port: {_configuration.Port}" : string.Empty)}."); - } - - /// - /// Resolves the hostname and checks whether the opened port (if specified) is being opened on the remote host. - /// - /// - /// IPStatus, if remote host has accepted connection, otherwise unknown. None IP address if host could not be resolved. True if port is being oepened. - private async Task> TryConnectAsync(ServerServicesProvider servicesProvider) - { - var ipAddress = servicesProvider.DnsResolver.GetIpAddress(_configuration.Hostname); - if (Equals(ipAddress, IPAddress.None)) - return new Tuple(IPStatus.Unknown, IPAddress.None, false); - - var portOpened = false; - var ipStatus = await servicesProvider.Pinger.PingAsync(ipAddress, _configuration.Timeout); - if (_configuration.Port > 0) - { - await servicesProvider.TcpClient.ConnectAsync(ipAddress, _configuration.Port, _configuration.Timeout); - portOpened = servicesProvider.TcpClient.IsConnected; - } - - return new Tuple(ipStatus, ipAddress, portOpened); - } - - /// - /// Creates PortServicesProvider instance. - /// - /// PortServicesProvider instance. - private ServerServicesProvider GetServicesProviders() - { - var client = _configuration.TcpClientProvider(); - var dnsResolver = _configuration.DnsResolverProvider(); - var pinger = _configuration.PingerProvider(); - - return new ServerServicesProvider(client, dnsResolver, pinger); - } - - /// - /// Class that holds useful providers to check the connection. - /// - private class ServerServicesProvider : IDisposable - { - /// - /// ITcpClient implementation instance. - /// - public ITcpClient TcpClient { get; } - - /// - /// IPinger implementation instance. - /// - public IPinger Pinger { get; } - - /// - /// IDnsResolver implementation instance. - /// - public IDnsResolver DnsResolver { get; } - - public ServerServicesProvider(ITcpClient tcpClient, IDnsResolver dnsResolver, IPinger pinger) - { - TcpClient = tcpClient; - DnsResolver = dnsResolver; - Pinger = pinger; - } - - public void Dispose() - { - TcpClient.Dispose(); - DnsResolver.Dispose(); - Pinger.Dispose(); - } - } - - /// - /// Factory method for creating a new instance of ServerWatcher. - /// - /// Hostname to connect to. - /// Optional port number of the hostname (0 means not specified). - /// A configuration bulider that should be used by watcher. - /// Optional name of the group that ServerWatcher belongs to. - /// A ServerWatcher instance. - public static ServerWatcher Create(string hostname, int port = 0, - Action configurator = null, string group = null) - { - var config = new ServerWatcherConfiguration.Builder(hostname, port); - configurator?.Invoke((ServerWatcherConfiguration.Default) config); - - return Create(DefaultName, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of ServerWatcher. - /// - /// Name of the ServerWatcher. - /// Hostname to connect to. - /// Optional port number of the hostname (0 means not specified). - /// A configuration that should be used by watcher. - /// Optional name of the group that ServerWatcher belongs to. - /// A ServerWatcher instance. - public static ServerWatcher Create(string name, string hostname, int port = 0, - Action configurator = null, string group = null) - { - var config = new ServerWatcherConfiguration.Builder(hostname, port); - configurator?.Invoke((ServerWatcherConfiguration.Default) config); - - return Create(name, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of ServerWatcher with default name of Server watcher. - /// - /// Configuration of ServerWatcher. - /// Optional name of the group that ServerWatcher belongs to. - /// A ServerWatcher instance. - public static ServerWatcher Create(ServerWatcherConfiguration configuration, - string group = null) - => Create(DefaultName, configuration, group); - - /// - /// Factory method for creating a new instance of ServerWatcher. - /// - /// Name of the ServerWatcher. - /// Configuration of ServerWatcher. - /// Optional name of the group that ServerWatcher belongs to. - /// A ServerWatcher instance. - public static ServerWatcher Create(string name, ServerWatcherConfiguration configuration, - string group = null) - => new ServerWatcher(name, configuration, group); - } -} diff --git a/src/Watchers/Warden.Watchers.Server/ServerWatcherCheckResult.cs b/src/Watchers/Warden.Watchers.Server/ServerWatcherCheckResult.cs deleted file mode 100644 index 629bc85..0000000 --- a/src/Watchers/Warden.Watchers.Server/ServerWatcherCheckResult.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace Warden.Watchers.Server -{ - /// - /// Custom check result type for ServerWatcher. - /// - public class ServerWatcherCheckResult : WatcherCheckResult - { - public ConnectionInfo ConnectionInfo { get; } - - protected ServerWatcherCheckResult(ServerWatcher watcher, bool isValid, - string description, ConnectionInfo connectionInfo) - : base(watcher, isValid, description) - { - ConnectionInfo = connectionInfo; - } - - /// - /// Factory method for creating a new instance of ServerWatcherCheckResult. - /// - /// Instance of ServerWatcher. - /// Flag determining whether the performed check was valid. - /// Details of the resolved connection to the specified hostname and port. - /// Custom description of the performed check. - /// Instance of ServerWatcherCheckResult. - public static ServerWatcherCheckResult Create(ServerWatcher watcher, bool isValid, - ConnectionInfo connectionInfo, string description = "") - => new ServerWatcherCheckResult(watcher, isValid, description, connectionInfo); - } -} diff --git a/src/Watchers/Warden.Watchers.Server/ServerWatcherConfiguration.cs b/src/Watchers/Warden.Watchers.Server/ServerWatcherConfiguration.cs deleted file mode 100644 index 57b0c77..0000000 --- a/src/Watchers/Warden.Watchers.Server/ServerWatcherConfiguration.cs +++ /dev/null @@ -1,233 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Warden.Watchers.Server -{ - /// - /// Configuration of the ServerWatcher. - /// - public class ServerWatcherConfiguration - { - /// - /// The destination hostname or IP address. - /// - public string Hostname { get; } - - /// - /// Optional port number for watching (0 means not specified). - /// - public int Port { get; } - - /// - /// Optional timeout for connection. - /// - public TimeSpan? Timeout { get; protected set; } - - /// - /// Predicate that has to be satisfied in order to return the valid result. - /// - public Func EnsureThat { get; protected set; } - - /// - /// Async predicate that has to be satisfied in order to return the valid result. - /// - public Func> EnsureThatAsync { get; protected set; } - - /// - /// Custom provider for the ITcpClient. - /// - public Func TcpClientProvider { get; protected set; } - - /// - /// Custom provider for the IDnsResolver. - /// - public Func DnsResolverProvider { get; protected set; } - - /// - /// Custom provider for the IPinger. - /// - public Func PingerProvider { get; protected set; } - - /// - /// Factory method for creating a new instance of fluent builder for the ServerWatcherConfiguration. - /// Uses the default 30 seconds timeout. - /// - /// Hostname to be resolved. - /// Port number of the hostname. - public static Builder Create(string hostname, int port = 0) => new Builder(hostname, port); - - protected internal ServerWatcherConfiguration(string hostname, int port) - { - hostname.ValidateHostname(); - if (port < 0) - throw new ArgumentException("Port number can not be less than 0.", nameof(port)); - - Hostname = hostname; - Port = port; - DnsResolverProvider = () => new DnsResolver(); - TcpClientProvider = () => new TcpClient(); - PingerProvider = () => new Pinger(); - } - - /// - /// Fluent builder for the ServerWatcherConfiguration. - /// - public abstract class Configurator : WatcherConfigurator - where T : Configurator - { - protected Configurator(string hostname, int port = 0) - { - ValidateHostnameAndPort(hostname, port); - Configuration = new ServerWatcherConfiguration(hostname, port); - } - - protected Configurator(ServerWatcherConfiguration configuration) : base(configuration) - { - } - - private void ValidateHostnameAndPort(string hostname, int port = 0) - { - hostname.ValidateHostname(); - if (port < 0) - throw new ArgumentException("Port number can not be less than 0.", nameof(port)); - } - - /// - /// Timeout of the connection. - /// - /// Timeout. - /// Instance of fluent builder for the ServerWatcherConfiguration. - public T WithTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); - - Configuration.Timeout = timeout; - - return Configurator; - } - - /// - /// Sets the predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the ServerWatcherConfiguration. - public T EnsureThat(Func ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThat = ensureThat; - - return Configurator; - } - - /// - /// Sets the async predicate that has to be satisfied in order to return the valid result. - /// Lambda expression predicate. - /// - /// Instance of fluent builder for the ServerWatcherConfiguration. - public T EnsureThatAsync(Func> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that async predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThatAsync = ensureThat; - - return Configurator; - } - - /// - /// Sets the custom provider for the ITcpClient. - /// - /// Custom provider for the ITcpClient. - /// Instance of fluent builder for the ServerWatcherConfiguration. - public T WithTcpClientProvider(Func tcpClientProvider) - { - if (tcpClientProvider == null) - { - throw new ArgumentNullException(nameof(tcpClientProvider), - "TCP Client provider can not be null."); - } - - Configuration.TcpClientProvider = tcpClientProvider; - - return Configurator; - } - - /// - /// Sets the custom provider for the IDnsResolver. - /// - /// Custom provider for the IDnsResolver. - /// Instance of fluent builder for the ServerWatcherConfiguration. - public T WithDnsResolverProvider(Func dsnResolverProvider) - { - if (dsnResolverProvider == null) - { - throw new ArgumentNullException(nameof(dsnResolverProvider), - "DNS Resolver provider can not be null."); - } - - Configuration.DnsResolverProvider = dsnResolverProvider; - - return Configurator; - } - - /// - /// Sets the custom provider for the IPinger. - /// - /// Custom provider for the IPinger. - /// Instance of fluent builder for the ServerWatcherConfiguration. - public T WithPingerProvider(Func pingerProvider) - { - if (pingerProvider == null) - { - throw new ArgumentNullException(nameof(pingerProvider), - "Pinger provider can not be null."); - } - - Configuration.PingerProvider = pingerProvider; - - return Configurator; - } - } - - /// - /// Default ServerWatcherConfiguration fluent builder used while configuring watcher via lambda expression. - /// - public class Default : Configurator - { - public Default(ServerWatcherConfiguration configuration) : base(configuration) - { - SetInstance(this); - } - } - - /// - /// Extended PortConfiugration fluent builder used while configuring watcher directly. - /// - public class Builder : Configurator - { - public Builder(string hostname, int port) : base(hostname, port) - { - SetInstance(this); - } - - /// - /// Builds the PortConfiugration and return its instance. - /// - /// Instance of PortConfiugration. - public ServerWatcherConfiguration Build() => Configuration; - - /// - /// Operator overload to provide casting the Builder configurator into Default configurator. - /// - /// Instance of extended Builder configurator. - /// Instance of Default builder configurator. - public static explicit operator Default(Builder builder) => new Default(builder.Configuration); - } - } -} diff --git a/src/Watchers/Warden.Watchers.Server/Warden.Watchers.Server.csproj b/src/Watchers/Warden.Watchers.Server/Warden.Watchers.Server.csproj deleted file mode 100644 index 59912e0..0000000 --- a/src/Watchers/Warden.Watchers.Server/Warden.Watchers.Server.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - Warden watcher for Server. - 1.3.1 - Piotr Gankiewicz;Patryk Wąsiewicz - net461 - Warden.Watchers.Server - Warden.Watchers.Server - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - 1.6.0 - false - false - false - - - - - - - - - - - - - - - - diff --git a/src/Watchers/Warden.Watchers.Web/Extensions.cs b/src/Watchers/Warden.Watchers.Web/Extensions.cs deleted file mode 100644 index 3f4beb3..0000000 --- a/src/Watchers/Warden.Watchers.Web/Extensions.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System; -using Warden.Core; - -namespace Warden.Watchers.Web -{ - /// - /// Custom extension methods for the Web watcher. - /// - public static class Extensions - { - internal static string GetFullUrl(this IHttpRequest request, string baseUrl) - { - var endpoint = request.Endpoint; - if (string.IsNullOrWhiteSpace(endpoint)) - return baseUrl; - - if (baseUrl.EndsWith("/")) - return $"{baseUrl}{(endpoint.StartsWith("/") ? endpoint.Substring(1) : $"{endpoint}")}"; - - return $"{baseUrl}{(endpoint.StartsWith("/") ? endpoint : $"/{endpoint}")}"; - } - - /// - /// Extension method for adding the Web watcher to the the WardenConfiguration with the default name of Web Watcher. - /// Uses the default HTTP GET request. - /// - /// Instance of the Warden configuration builder. - /// Base URL of the request. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddWebWatcher( - this WardenConfiguration.Builder builder, - string url, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(WebWatcher.Create(url, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Web watcher to the the WardenConfiguration with the default name of Web Watcher. - /// - /// Instance of the Warden configuration builder. - /// Base URL of the request. - /// Instance of the IHttpRequest. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddWebWatcher( - this WardenConfiguration.Builder builder, - string url, - IHttpRequest request, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(WebWatcher.Create(url, request, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Web watcher to the the WardenConfiguration.. - /// - /// Instance of the Warden configuration builder. - /// Name of the WebWatcher. - /// Base URL of the request. - /// Instance of the IHttpRequest. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddWebWatcher( - this WardenConfiguration.Builder builder, - string name, - string url, - IHttpRequest request, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(WebWatcher.Create(name, url, request, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Web watcher to the the WardenConfiguration with the default name of Web Watcher. - /// Uses the default HTTP GET request. - /// - /// Instance of the Warden configuration builder. - /// Base URL of the request. - /// Lambda expression for configuring the WebWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that WebWatcher belongs to. - public static WardenConfiguration.Builder AddWebWatcher( - this WardenConfiguration.Builder builder, - string url, - Action configurator, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(WebWatcher.Create(url, configurator, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Web watcher to the the WardenConfiguration with the default name of Web Watcher. - /// - /// Instance of the Warden configuration builder. - /// Base URL of the request. - /// Instance of the IHttpRequest. - /// Lambda expression for configuring the WebWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddWebWatcher( - this WardenConfiguration.Builder builder, - string url, - IHttpRequest request, - Action configurator, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(WebWatcher.Create(url, request, configurator, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Web watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the WebWatcher. - /// Base URL of the request. - /// Instance of the IHttpRequest. - /// Lambda expression for configuring the WebWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddWebWatcher( - this WardenConfiguration.Builder builder, - string name, - string url, - IHttpRequest request, - Action configurator, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(WebWatcher.Create(name, url, request, configurator, group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Web watcher to the the WardenConfiguration with the default name of Web Watcher. - /// - /// Instance of the Warden configuration builder. - /// Configuration of WebWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddWebWatcher( - this WardenConfiguration.Builder builder, - WebWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(WebWatcher.Create(configuration, group: group), hooks, interval); - - return builder; - } - - /// - /// Extension method for adding the Web watcher to the the WardenConfiguration. - /// - /// Instance of the Warden configuration builder. - /// Name of the WebWatcher. - /// Configuration of WebWatcher. - /// Optional lambda expression for configuring the watcher hooks. - /// Optional interval (5 seconds by default) after which the next check will be invoked. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of fluent builder for the WardenConfiguration. - public static WardenConfiguration.Builder AddWebWatcher( - this WardenConfiguration.Builder builder, - string name, - WebWatcherConfiguration configuration, - Action hooks = null, - TimeSpan? interval = null, - string group = null) - { - builder.AddWatcher(WebWatcher.Create(name, configuration, group), hooks, interval); - - return builder; - } - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Web/IHttpRequest.cs b/src/Watchers/Warden.Watchers.Web/IHttpRequest.cs deleted file mode 100644 index 7c5d795..0000000 --- a/src/Watchers/Warden.Watchers.Web/IHttpRequest.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System.Collections.Generic; - -namespace Warden.Watchers.Web -{ - /// - /// Representation of the HTTP method type. - /// - public enum HttpMethod - { - Get = 1, - Put = 2, - Post = 3, - Delete = 4 - } - - /// - /// Custom interface for HTTP request. - /// - public interface IHttpRequest - { - /// - /// Type of HTTP method. - /// - HttpMethod Method { get; } - - /// - /// Endpoint of the request (part of the base URL). - /// - string Endpoint { get; } - - /// - /// Request data that may be required for either POST or PUT request. - /// - object Data { get; } - - /// - /// Request headers. - /// - IDictionary Headers { get; } - } - - - /// - /// Default implementation of the IHttpRequest. - /// - public class HttpRequest : IHttpRequest - { - public HttpMethod Method { get; } - public string Endpoint { get; } - public object Data { get; } - public IDictionary Headers { get; } - - protected HttpRequest(HttpMethod method, string endpoint, - IDictionary headers = null, dynamic data = null) - { - - Method = method; - Endpoint = endpoint; - Headers = headers ?? new Dictionary(); - Data = data; - } - - /// - /// GET request with optional headers. - /// - /// Request headers - /// Instance of IHttpRequest. - public static IHttpRequest Get(IDictionary headers = null) - => new HttpRequest(HttpMethod.Get, string.Empty, headers); - - /// - /// GET request with endpoint and optional headers. - /// - /// Endpoint of the request - /// Request headers - /// Instance of IHttpRequest. - public static IHttpRequest Get(string endpoint, IDictionary headers = null) - => new HttpRequest(HttpMethod.Get, endpoint, headers); - - /// - /// POST request with data and optional headers. - /// - /// Request body - /// Request headers - /// Instance of IHttpRequest. - public static IHttpRequest Post(object data, IDictionary headers = null) - => new HttpRequest(HttpMethod.Post, string.Empty, headers, data); - - /// - /// POST request with endpoint and optional data and headers. - /// - /// Endpoint of the request - /// Request body - /// Request headers - /// Instance of IHttpRequest. - public static IHttpRequest Post(string endpoint, object data = null, IDictionary headers = null) - => new HttpRequest(HttpMethod.Post, endpoint, headers, data); - - /// - /// PUT request with data and optional headers. - /// - /// Request body - /// Request headers - /// Instance of IHttpRequest. - public static IHttpRequest Put(object data, IDictionary headers = null) - => new HttpRequest(HttpMethod.Put, string.Empty, headers, data); - - /// - /// PUT request with endpoint and optional data and headers. - /// - /// Endpoint of the request - /// Request body - /// Request headers - /// Instance of IHttpRequest. - public static IHttpRequest Put(string endpoint, object data = null, IDictionary headers = null) - => new HttpRequest(HttpMethod.Put, endpoint, headers, data); - - /// - /// DELETE request with optional headers. - /// - /// Request headers - /// Instance of IHttpRequest. - public static IHttpRequest Delete(IDictionary headers = null) - => new HttpRequest(HttpMethod.Delete, string.Empty, headers); - - /// - /// DELETE request with endpoint and optional headers. - /// - /// Endpoint of the request - /// Request headers - /// Instance of IHttpRequest. - public static IHttpRequest Delete(string endpoint, IDictionary headers = null) - => new HttpRequest(HttpMethod.Delete, endpoint, headers); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Web/IHttpResponse.cs b/src/Watchers/Warden.Watchers.Web/IHttpResponse.cs deleted file mode 100644 index d139bf1..0000000 --- a/src/Watchers/Warden.Watchers.Web/IHttpResponse.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System.Collections.Generic; -using System.Net; - -namespace Warden.Watchers.Web -{ - /// - /// Custom interface for HTTP response. - /// - public interface IHttpResponse - { - /// - /// Status code of response. - /// - HttpStatusCode StatusCode { get; } - - /// - /// Flag determining whether response is valid. - /// - bool IsValid { get; } - - /// - /// Reason phrase that can be provided in response. - /// - string ReasonPhrase { get; } - - /// - /// Response headers. - /// - IDictionary Headers { get; } - - /// - /// Response content. - /// - string Data { get; } - } - - /// - /// Default implementation of the IHttpResponse. - /// - public class HttpResponse : IHttpResponse - { - public HttpStatusCode StatusCode { get; } - public bool IsValid { get; } - public string ReasonPhrase { get; } - public IDictionary Headers { get; } - public string Data { get; } - - protected HttpResponse(HttpStatusCode statusCode, bool isValid, - string reasonPhrase, IDictionary headers, string data) - { - StatusCode = statusCode; - IsValid = isValid; - ReasonPhrase = reasonPhrase; - Headers = headers ?? new Dictionary(); - Data = data; - } - - /// - /// Valid HTTP response. - /// - /// Status code of response. - /// Reason phrase. - /// Response headers. - /// Response content. - /// Instance of IHttpResponse. - public static IHttpResponse Valid(HttpStatusCode statusCode, string reasonPhrase, - IDictionary headers, string data) => new HttpResponse(statusCode, true, - reasonPhrase, headers, data); - - /// - /// Invalid HTTP response. - /// - /// Status code of response. - /// Reason phrase. - /// Response headers. - /// Response content. - /// Instance of IHttpResponse. - public static IHttpResponse Invalid(HttpStatusCode statusCode, string reasonPhrase, - IDictionary headers, string data) => new HttpResponse(statusCode, false, - reasonPhrase, headers, data); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Web/IHttpService.cs b/src/Watchers/Warden.Watchers.Web/IHttpService.cs deleted file mode 100644 index dddb7a0..0000000 --- a/src/Watchers/Warden.Watchers.Web/IHttpService.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace Warden.Watchers.Web -{ - /// - /// Custom HTTP service for executing the requests. - /// - public interface IHttpService - { - /// - /// Executes the HTTP request and returns an instance of the IHttpResponse. - /// - /// Base URL of the request (e.g. http://www.example.com) - /// Instance of the IHttpRequest that contains request details (method type, headers, etc.). - /// Optional timeout for the request. - /// Instance of IHttpResponse. - Task ExecuteAsync(string baseUrl, IHttpRequest request, TimeSpan? timeout = null); - } - - /// - /// Default implementation of the IHttpService based on HtpClient. - /// - public class HttpService : IHttpService - { - private readonly HttpClient _client; - - public HttpService(HttpClient client) - { - _client = client; - } - - public async Task ExecuteAsync(string baseUrl, IHttpRequest request, TimeSpan? timeout = null) - { - SetRequestHeaders(request.Headers); - SetTimeout(timeout); - var response = await GetHttpResponseAsync(baseUrl, request); - var data = response.Content != null ? await response.Content.ReadAsStringAsync() : string.Empty; - var valid = response.IsSuccessStatusCode; - var responseHeaders = GetResponseHeaders(response.Headers); - - return valid - ? HttpResponse.Valid(response.StatusCode, response.ReasonPhrase, responseHeaders, data) - : HttpResponse.Invalid(response.StatusCode, response.ReasonPhrase, responseHeaders, data); - } - - private async Task GetHttpResponseAsync(string baseUrl, IHttpRequest request) - { - var fullUrl = request.GetFullUrl(baseUrl); - - return await ExecuteHttpResponseAsync(fullUrl, request); - } - - private async Task ExecuteHttpResponseAsync(string fullUrl, IHttpRequest request) - { - var method = request.Method; - switch (method) - { - case HttpMethod.Get: - return await _client.GetAsync(fullUrl); - case HttpMethod.Post: - return await _client.PostAsync(fullUrl, new StringContent( - JsonConvert.SerializeObject(request.Data ?? new { }), Encoding.UTF8, "application/json")); - case HttpMethod.Put: - return await _client.PutAsync(fullUrl, new StringContent( - JsonConvert.SerializeObject(request.Data ?? new { }), Encoding.UTF8, "application/json")); - case HttpMethod.Delete: - return await _client.DeleteAsync(fullUrl); - default: - throw new ArgumentException($"Invalid HTTP method: {method}.", nameof(method)); - } - } - - private void SetTimeout(TimeSpan? timeout) - { - if (timeout > TimeSpan.Zero) - _client.Timeout = timeout.Value; - } - - private void SetRequestHeaders(IDictionary headers) - { - if (headers == null) - return; - - foreach (var header in headers) - { - var existingHeader = _client.DefaultRequestHeaders - .FirstOrDefault(x => string.Equals(x.Key, header.Key, StringComparison.CurrentCultureIgnoreCase)); - if (existingHeader.Key != null) - _client.DefaultRequestHeaders.Remove(existingHeader.Key); - - _client.DefaultRequestHeaders.Add(header.Key, header.Value); - } - } - - private IDictionary GetResponseHeaders(HttpResponseHeaders headers) - => headers?.ToDictionary(header => header.Key, header => header.Value?.FirstOrDefault()) ?? - new Dictionary(); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Web/Properties/AssemblyInfo.cs b/src/Watchers/Warden.Watchers.Web/Properties/AssemblyInfo.cs deleted file mode 100644 index 5a30945..0000000 --- a/src/Watchers/Warden.Watchers.Web/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Watchers.Web")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Watchers.Web")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("5251958c-6a0c-4b14-b41b-b66409a151b5")] diff --git a/src/Watchers/Warden.Watchers.Web/Warden.Watchers.Web.csproj b/src/Watchers/Warden.Watchers.Web/Warden.Watchers.Web.csproj deleted file mode 100644 index b57dbd4..0000000 --- a/src/Watchers/Warden.Watchers.Web/Warden.Watchers.Web.csproj +++ /dev/null @@ -1,48 +0,0 @@ - - - - Warden watcher for Web. - 1.3.1 - Piotr Gankiewicz - net461;netstandard1.6 - Warden.Watchers.Web - Warden.Watchers.Web - Warden - https://getwarden.net - https://github.com/warden-stack/Warden/blob/master/LICENSE - $(PackageTargetFallback);dotnet5.6;dnxcore50 - false - false - false - false - false - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Watchers/Warden.Watchers.Web/WebWatcher.cs b/src/Watchers/Warden.Watchers.Web/WebWatcher.cs deleted file mode 100644 index 10191f0..0000000 --- a/src/Watchers/Warden.Watchers.Web/WebWatcher.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Warden.Watchers.Web -{ - /// - /// WebWatcher designed for website or API monitoring. - /// - public class WebWatcher : IWatcher - { - private readonly WebWatcherConfiguration _configuration; - private readonly IHttpService _httpService; - public string Name { get; } - public string Group { get; } - public const string DefaultName = "Web Watcher"; - - protected WebWatcher(string name, WebWatcherConfiguration configuration, string group) - { - if (string.IsNullOrEmpty(name)) - throw new ArgumentException("Watcher name can not be empty."); - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration), - "Web Watcher configuration has not been provided."); - } - - Name = name; - _configuration = configuration; - Group = group; - _httpService = configuration.HttpServiceProvider(); - } - - public async Task ExecuteAsync() - { - var baseUrl = _configuration.Uri.ToString(); - var fullUrl = _configuration.Request.GetFullUrl(baseUrl); - try - { - var response = await _httpService.ExecuteAsync(baseUrl, _configuration.Request, _configuration.Timeout); - var isValid = HasValidResponse(response); - if (!isValid) - { - return WebWatcherCheckResult.Create(this, false, - _configuration.Uri, _configuration.Request, response, - $"Web endpoint: '{fullUrl}' has returned an invalid response with status code: {response.StatusCode}."); - } - - return await EnsureAsync(fullUrl, response); - } - catch (TaskCanceledException exception) - { - return WebWatcherCheckResult.Create(this, - false, _configuration.Uri, - _configuration.Request, null, - $"A connection timeout occurred while trying to access the Web endpoint: '{fullUrl}'."); - } - catch (Exception exception) - { - throw new WatcherException($"There was an error while trying to access the Web endpoint: '{fullUrl}'.", - exception); - } - } - - private async Task EnsureAsync(string fullUrl, IHttpResponse response) - { - var isValid = true; - if (_configuration.EnsureThatAsync != null) - isValid = await _configuration.EnsureThatAsync?.Invoke(response); - - isValid = isValid && (_configuration.EnsureThat?.Invoke(response) ?? true); - - return WebWatcherCheckResult.Create(this, - isValid, _configuration.Uri, - _configuration.Request, response, - $"Web endpoint: '{fullUrl}' has returned a response with status code: {response.StatusCode}."); - } - - private bool HasValidResponse(IHttpResponse response) - => response.IsValid || _configuration.SkipStatusCodeValidation; - - /// - /// Factory method for creating a new instance of WebWatcher with default name of Web Watcher. - /// Uses the default HTTP GET request. - /// - /// Base URL of the request. - /// Optional lambda expression for configuring the WebWatcher. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of WebWatcher. - public static WebWatcher Create(string url, Action configurator = null, - string group = null) - { - var config = new WebWatcherConfiguration.Builder(url); - configurator?.Invoke((WebWatcherConfiguration.Default)config); - - return Create(DefaultName, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of WebWatcher with default name of Web Watcher. - /// - /// Base URL of the request. - /// Instance of the IHttpRequest. - /// Optional lambda expression for configuring the WebWatcher. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of WebWatcher. - public static WebWatcher Create(string url, IHttpRequest request, - Action configurator = null, string group = null) - => Create(DefaultName, url, request, configurator, group); - - /// - /// Factory method for creating a new instance of WebWatcher. - /// - /// Name of the WebWatcher. - /// Base URL of the request. - /// Instance of the IHttpRequest. - /// Optional lambda expression for configuring the WebWatcher. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of WebWatcher. - public static WebWatcher Create(string name, string url, IHttpRequest request, - Action configurator = null, string group = null) - { - var config = new WebWatcherConfiguration.Builder(url, request); - configurator?.Invoke((WebWatcherConfiguration.Default) config); - - return Create(name, config.Build(), group); - } - - /// - /// Factory method for creating a new instance of WebWatcher with default name of Web Watcher. - /// - /// Configuration of WebWatcher. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of WebWatcher. - public static WebWatcher Create(WebWatcherConfiguration configuration, string group = null) - => Create(DefaultName, configuration, group); - - /// - /// Factory method for creating a new instance of WebWatcher. - /// - /// Name of the WebWatcher. - /// Configuration of WebWatcher. - /// Optional name of the group that WebWatcher belongs to. - /// Instance of WebWatcher. - public static WebWatcher Create(string name, WebWatcherConfiguration configuration, string group = null) - => new WebWatcher(name, configuration, group); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Web/WebWatcherCheckResult.cs b/src/Watchers/Warden.Watchers.Web/WebWatcherCheckResult.cs deleted file mode 100644 index d8223f7..0000000 --- a/src/Watchers/Warden.Watchers.Web/WebWatcherCheckResult.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; - -namespace Warden.Watchers.Web -{ - /// - /// Custom check result type for WebWatcher. - /// - public class WebWatcherCheckResult : WatcherCheckResult - { - /// - /// Base URL of the request. - /// - public Uri Uri { get; } - - /// - /// Instance of IHttpRequest. - /// - public IHttpRequest Request { get; } - - /// - /// Instance of IHttpResponse. - /// - public IHttpResponse Response { get; } - - protected WebWatcherCheckResult(WebWatcher watcher, bool isValid, string description, - Uri uri, IHttpRequest request, IHttpResponse response) - : base(watcher, isValid, description) - { - Uri = uri; - Request = request; - Response = response; - Response = response; - } - - /// - /// Factory method for creating a new instance of WebWatcherCheckResult. - /// - /// Instance of WebWatcher. - /// Flag determining whether the performed check was valid. - /// Base URL of the request. - /// Instance of IHttpRequest. - /// Instance of IHttpResponse. - /// Custom description of the performed check. - /// Instance of WebWatcherCheckResult. - public static WebWatcherCheckResult Create(WebWatcher watcher, bool isValid, Uri uri, - IHttpRequest request, IHttpResponse response, string description = "") - => new WebWatcherCheckResult(watcher, isValid, description, uri, request, response); - } -} \ No newline at end of file diff --git a/src/Watchers/Warden.Watchers.Web/WebWatcherConfiguration.cs b/src/Watchers/Warden.Watchers.Web/WebWatcherConfiguration.cs deleted file mode 100644 index 9977b7c..0000000 --- a/src/Watchers/Warden.Watchers.Web/WebWatcherConfiguration.cs +++ /dev/null @@ -1,222 +0,0 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; - -namespace Warden.Watchers.Web -{ - /// - /// Configuration of the WebWatcher. - /// - public class WebWatcherConfiguration - { - /// - /// Base URL of the request. - /// - public Uri Uri { get; protected set; } - - /// - /// Instance of IHttpRequest. - /// - public IHttpRequest Request { get; protected set; } - - /// - /// Custom provider for the IHttpService. - /// - public Func HttpServiceProvider { get; protected set; } - - /// - /// Flag determining whether the invalid status code should be treated as valid one. - /// - public bool SkipStatusCodeValidation { get; protected set; } - - /// - /// Optional timeout of the HTTP request. - /// - public TimeSpan? Timeout { get; protected set; } - - /// - /// Predicate that has to be satisfied in order to return the valid result. - /// - public Func EnsureThat { get; protected set; } - - /// - /// Async predicate that has to be satisfied in order to return the valid result. - /// - public Func> EnsureThatAsync { get; protected set; } - - protected internal WebWatcherConfiguration(string url, IHttpRequest request) - { - if (string.IsNullOrEmpty(url)) - throw new ArgumentException("URL can not be empty.", nameof(url)); - - if (request == null) - throw new ArgumentNullException(nameof(request), "Request can not be null."); - - Uri = new Uri(url); - Request = request; - HttpServiceProvider = () => new HttpService(new HttpClient()); - } - - /// - /// Factory method for creating a new instance of fluent builder for the WebWatcherConfiguration. - /// Uses the default HTTP GET request. - /// - /// Base URL of the request. - public static Builder Create(string url) => new Builder(url, HttpRequest.Get()); - - /// - /// Factory method for creating a new instance of fluent builder for the WebWatcherConfiguration. - /// - /// Base URL of the request. - /// Instance of IHttpRequest. - /// Instance of fluent builder for the WebWatcherConfiguration. - public static Builder Create(string url, IHttpRequest request) => new Builder(url, request); - - /// - /// Fluent builder for the WebWatcherConfiguration. - /// - public abstract class Configurator : WatcherConfigurator - where T : Configurator - { - protected Configurator(string url, IHttpRequest request) - { - Configuration = new WebWatcherConfiguration(url, request); - } - - protected Configurator(WebWatcherConfiguration configuration) : base(configuration) - { - } - - /// - /// Sets the HTTP request. - /// - /// Instance of IHttpRequest. - /// Instance of fluent builder for the WebWatcherConfiguration. - public T WithRequest(IHttpRequest request) - { - if (request == null) - throw new ArgumentNullException(nameof(request), "HTTP request can not be null."); - - Configuration.Request = request; - - return Configurator; - } - - /// - /// Timeout of the HTTP request. - /// - /// Timeout. - /// Instance of fluent builder for the WebWatcherConfiguration. - public T WithTimeout(TimeSpan timeout) - { - if (timeout == null) - throw new ArgumentNullException(nameof(timeout), "Timeout can not be null."); - - if (timeout == TimeSpan.Zero) - throw new ArgumentException("Timeout can not be equal to zero.", nameof(timeout)); - - Configuration.Timeout = timeout; - - return Configurator; - } - - /// - /// Skips the validation of the status code. - /// - /// Instance of fluent builder for the WebWatcherConfiguration. - public T SkipStatusCodeValidation() - { - Configuration.SkipStatusCodeValidation = true; - - return Configurator; - } - - /// - /// Sets the predicate that has to be satisfied in order to return the valid result. - /// - /// Lambda expression predicate. - /// Instance of fluent builder for the WebWatcherConfiguration. - public T EnsureThat(Func ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThat = ensureThat; - - return Configurator; - } - - /// - /// Sets the async predicate that has to be satisfied in order to return the valid result. - /// Lambda expression predicate. - /// - /// Instance of fluent builder for the WebWatcherConfiguration. - public T EnsureThatAsync(Func> ensureThat) - { - if (ensureThat == null) - throw new ArgumentException("Ensure that async predicate can not be null.", nameof(ensureThat)); - - Configuration.EnsureThatAsync = ensureThat; - - return Configurator; - } - - /// - /// Sets the custom provider for the IHttpService. - /// - /// Custom provider for the IHttpService. - /// Lambda expression returning an instance of the IHttpService. - /// Instance of fluent builder for the WebWatcherConfiguration. - public T WithHttpServiceProvider(Func httpServiceProvider) - { - if (httpServiceProvider == null) - throw new ArgumentNullException(nameof(httpServiceProvider), - "HTTP service provider can not be null."); - - Configuration.HttpServiceProvider = httpServiceProvider; - - return Configurator; - } - } - - /// - /// Default WebWatcherConfiguration fluent builder used while configuring watcher via lambda expression. - /// - public class Default : Configurator - { - public Default(WebWatcherConfiguration configuration) : base(configuration) - { - SetInstance(this); - } - } - - /// - /// Extended WebWatcherConfiguration fluent builder used while configuring watcher directly. - /// - public class Builder : Configurator - { - public Builder(string url) : base(url, HttpRequest.Get()) - { - SetInstance(this); - } - - public Builder(string url, IHttpRequest request) : base(url, request) - { - SetInstance(this); - } - - /// - /// Builds the WebWatcherConfiguration and return its instance. - /// - /// Instance of WebWatcherConfiguration. - public WebWatcherConfiguration Build() => Configuration; - - /// - /// Operator overload to provide casting the Builder configurator into Default configurator. - /// - /// Instance of extended Builder configurator. - /// Instance of Default builder configurator. - public static explicit operator Default(Builder builder) => new Default(builder.Configuration); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/ApiKey.cs b/src/Web/Warden.Web.Core/Domain/ApiKey.cs deleted file mode 100644 index 684444e..0000000 --- a/src/Web/Warden.Web.Core/Domain/ApiKey.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Domain -{ - public class ApiKey : Entity, ITimestampable - { - public string Key { get; protected set; } - public Guid UserId { get; protected set; } - public DateTime CreatedAt { get; protected set; } - - protected ApiKey() - { - } - - public ApiKey(string key, User user) - { - if (key.Empty()) - throw new DomainException("API key can not be empty."); - if (user == null) - throw new DomainException("Can not create an API key without user."); - - Key = key; - UserId = user.Id; - CreatedAt = DateTime.UtcNow; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/DomainException.cs b/src/Web/Warden.Web.Core/Domain/DomainException.cs deleted file mode 100644 index 0467f64..0000000 --- a/src/Web/Warden.Web.Core/Domain/DomainException.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public class DomainException : Exception - { - public DomainException() - { - } - - public DomainException(string message, params object[] args) : this(null, message, args) - { - } - - public DomainException(Exception innerException, string message, params object[] args) - : base(string.Format(message, args), innerException) - { - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/Entity.cs b/src/Web/Warden.Web.Core/Domain/Entity.cs deleted file mode 100644 index c1ea38a..0000000 --- a/src/Web/Warden.Web.Core/Domain/Entity.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public abstract class Entity : IIdentifiable - { - public Guid Id { get; protected set; } - - protected Entity() - { - Id = Guid.NewGuid(); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/ExceptionInfo.cs b/src/Web/Warden.Web.Core/Domain/ExceptionInfo.cs deleted file mode 100644 index aa13e32..0000000 --- a/src/Web/Warden.Web.Core/Domain/ExceptionInfo.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Domain -{ - public class ExceptionInfo - { - public string Message { get; protected set; } - public string Source { get; protected set; } - public string StackTrace { get; protected set; } - public ExceptionInfo InnerException { get; protected set; } - - protected ExceptionInfo() - { - } - - protected ExceptionInfo(string message, string source, string stackTrace, - ExceptionInfo innerException = null) - { - if (message.Empty()) - throw new DomainException("Exception message can not be empty."); - - Message = message; - Source = source; - StackTrace = stackTrace; - InnerException = innerException; - } - - public static ExceptionInfo Create(string message, string source, string stackTrace, - ExceptionInfo innerException = null) - => new ExceptionInfo(message, source, stackTrace, innerException); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/ICompletable.cs b/src/Web/Warden.Web.Core/Domain/ICompletable.cs deleted file mode 100644 index a7f8fa8..0000000 --- a/src/Web/Warden.Web.Core/Domain/ICompletable.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public interface ICompletable - { - DateTime CompletedAt { get; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/IIdentifiable.cs b/src/Web/Warden.Web.Core/Domain/IIdentifiable.cs deleted file mode 100644 index 11bdd38..0000000 --- a/src/Web/Warden.Web.Core/Domain/IIdentifiable.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public interface IIdentifiable - { - Guid Id { get; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/ITimestampable.cs b/src/Web/Warden.Web.Core/Domain/ITimestampable.cs deleted file mode 100644 index 88d422e..0000000 --- a/src/Web/Warden.Web.Core/Domain/ITimestampable.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public interface ITimestampable - { - DateTime CreatedAt { get; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/IValidatable.cs b/src/Web/Warden.Web.Core/Domain/IValidatable.cs deleted file mode 100644 index eeb8dd3..0000000 --- a/src/Web/Warden.Web.Core/Domain/IValidatable.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Warden.Web.Core.Domain -{ - public interface IValidatable - { - bool IsValid { get; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/Organization.cs b/src/Web/Warden.Web.Core/Domain/Organization.cs deleted file mode 100644 index e6da7b4..0000000 --- a/src/Web/Warden.Web.Core/Domain/Organization.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Domain -{ - public class Organization : Entity, ITimestampable - { - private HashSet _users = new HashSet(); - private HashSet _wardens = new HashSet(); - - public string Name { get; protected set; } - public Guid OwnerId { get; protected set; } - public bool AutoRegisterNewWarden { get; protected set; } - public DateTime CreatedAt { get; protected set; } - public DateTime UpdatedAt { get; protected set; } - - public IEnumerable Users - { - get { return _users; } - protected set { _users = new HashSet(value); } - } - - public IEnumerable Wardens - { - get { return _wardens; } - protected set { _wardens = new HashSet(value); } - } - - protected Organization() - { - } - - public Organization(string name, User owner, bool autoRegisterNewWarden = true) - { - SetName(name); - SetOwner(owner); - CreatedAt = DateTime.UtcNow; - UpdatedAt = DateTime.UtcNow; - if(autoRegisterNewWarden) - EnableAutoRegisterNewWarden(); - } - - public void SetName(string name) - { - if (name.Empty()) - throw new DomainException("Organization name can not be empty."); - - Name = name.Trim(); - UpdatedAt = DateTime.UtcNow; - } - - public void SetOwner(User owner) - { - if (owner == null) - throw new DomainException("Organization owner can not be null."); - - OwnerId = owner.Id; - AddUser(owner, OrganizationRole.Owner); - UpdatedAt = DateTime.UtcNow; - } - - public void AddUser(User user, OrganizationRole role = OrganizationRole.User) - { - if (user == null) - throw new DomainException("Can not add empty user to the organization."); - - if (Users.Any(x => x.Id == user.Id)) - throw new DomainException($"User '{user.Email}' is already in the organization."); - - _users.Add(UserInOrganization.Create(user, role)); - UpdatedAt = DateTime.UtcNow; - } - - public void RemoveUser(Guid id) - { - var userInOrganization = Users.FirstOrDefault(x => x.Id == id); - if (userInOrganization == null) - throw new DomainException($"User with id '{id}' was not found in the organization."); - if (OwnerId == id) - throw new DomainException("Owner can not be removed from organization."); - - _users.Remove(userInOrganization); - UpdatedAt = DateTime.UtcNow; - } - - public void AddWarden(string name, bool enabled = true) - { - if (name.Empty()) - throw new DomainException("Can not add a warden without a name to the organization."); - - var warden = GetWardenByName(name); - if (warden != null) - throw new DomainException($"Warden with name: '{name}' has been already added."); - - _wardens.Add(new Warden(name, enabled)); - UpdatedAt = DateTime.UtcNow; - } - - public void EditWarden(string name, string newName) - { - var warden = GetWardenByNameOrFail(name); - var existingWarden = GetWardenByName(newName); - if(existingWarden != null && existingWarden.Id != warden.Id) - throw new DomainException($"Warden with name: '{newName}' already exists."); - - warden.SetName(newName); - UpdatedAt = DateTime.UtcNow; - } - - public void RemoveWarden(string name) - { - if (name.Empty()) - throw new DomainException("Can not remove a warden without a name from the organization."); - - var warden = GetWardenByNameOrFail(name); - _wardens.Remove(warden); - UpdatedAt = DateTime.UtcNow; - } - - public void EnableWarden(string name) - { - var warden = GetWardenByNameOrFail(name); - warden.Enable(); - UpdatedAt = DateTime.UtcNow; - } - - public void DisableWarden(string name) - { - var warden = GetWardenByNameOrFail(name); - warden.Disable(); - UpdatedAt = DateTime.UtcNow; - } - - public Warden GetWardenByNameOrFail(string name) - { - if (name.Empty()) - throw new DomainException("Warden name can not be empty."); - - var warden = GetWardenByName(name); - if (warden == null) - throw new DomainException($"Warden with name: '{name}' has not been found."); - - return warden; - } - - public Warden GetWardenByName(string name) => Wardens.FirstOrDefault(x => x.Name.EqualsCaseInvariant(name)); - - public void EnableAutoRegisterNewWarden() - { - if(AutoRegisterNewWarden) - return; - - AutoRegisterNewWarden = true; - UpdatedAt = DateTime.UtcNow; - } - - public void DisableAutoRegisterNewWarden() - { - if (!AutoRegisterNewWarden) - return; - - AutoRegisterNewWarden = false; - UpdatedAt = DateTime.UtcNow; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/OrganizationRole.cs b/src/Web/Warden.Web.Core/Domain/OrganizationRole.cs deleted file mode 100644 index 8d47385..0000000 --- a/src/Web/Warden.Web.Core/Domain/OrganizationRole.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Warden.Web.Core.Domain -{ - public enum OrganizationRole - { - User = 1, - Admin = 2, - Owner = 3 - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/PagedQueryBase.cs b/src/Web/Warden.Web.Core/Domain/PagedQueryBase.cs deleted file mode 100644 index 9d5030e..0000000 --- a/src/Web/Warden.Web.Core/Domain/PagedQueryBase.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Warden.Web.Core.Domain -{ - public abstract class PagedQueryBase - { - public int Page { get; set; } - public int Results { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/PagedResult.cs b/src/Web/Warden.Web.Core/Domain/PagedResult.cs deleted file mode 100644 index fcda5a8..0000000 --- a/src/Web/Warden.Web.Core/Domain/PagedResult.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace Warden.Web.Core.Domain -{ - public class PagedResult : PagedResultBase - { - public IEnumerable Items { get; } - - protected PagedResult() - { - Items = Enumerable.Empty(); - } - - protected PagedResult(IEnumerable items, - int currentPage, int resultsPerPage, - int totalPages, long totalResults) : - base(currentPage, resultsPerPage, totalPages, totalResults) - { - Items = items; - } - - public static PagedResult Create(IEnumerable items, - int currentPage, int resultsPerPage, - int totalPages, long totalResults) - => new PagedResult(items, currentPage, resultsPerPage, totalPages, totalResults); - - - public static PagedResult From(PagedResultBase result, IEnumerable items) - => new PagedResult(items, result.CurrentPage, result.ResultsPerPage, - result.TotalPages, result.TotalResults); - - public static PagedResult Empty => new PagedResult(); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/PagedResultBase.cs b/src/Web/Warden.Web.Core/Domain/PagedResultBase.cs deleted file mode 100644 index a4e76d6..0000000 --- a/src/Web/Warden.Web.Core/Domain/PagedResultBase.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace Warden.Web.Core.Domain -{ - public abstract class PagedResultBase - { - public int CurrentPage { get; } - public int ResultsPerPage { get; } - public int TotalPages { get; } - public long TotalResults { get; } - - protected PagedResultBase() - { - } - - protected PagedResultBase(int currentPage, int resultsPerPage, - int totalPages, long totalResults) - { - CurrentPage = currentPage > totalPages ? totalPages : currentPage; - ResultsPerPage = resultsPerPage; - TotalPages = totalPages; - TotalResults = totalResults; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/Role.cs b/src/Web/Warden.Web.Core/Domain/Role.cs deleted file mode 100644 index a3bf876..0000000 --- a/src/Web/Warden.Web.Core/Domain/Role.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Warden.Web.Core.Domain -{ - public enum Role - { - User = 1, - Moderator = 2, - Admin = 3 - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/SecuredOperation.cs b/src/Web/Warden.Web.Core/Domain/SecuredOperation.cs deleted file mode 100644 index 30daa14..0000000 --- a/src/Web/Warden.Web.Core/Domain/SecuredOperation.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Domain -{ - public class SecuredOperation : Entity, ITimestampable - { - public Guid? UserId { get; protected set; } - public string Email { get; protected set; } - public SecuredOperationType Type { get; protected set; } - public string Token { get; protected set; } - public string RequesterIpAddress { get; protected set; } - public string RequesterUserAgent { get; protected set; } - public string ConsumerIpAddress { get; protected set; } - public string ConsumerUserAgent { get; protected set; } - public bool Consumed { get; set; } - public DateTime CreatedAt { get; protected set; } - public DateTime UpdatedAt { get; protected set; } - public DateTime Expiry { get; protected set; } - - public SecuredOperation(SecuredOperationType type, string token, - DateTime expiry, Guid? userId = null, string email = null, - string ipAddress = null, string userAgent = null) - { - if (!userId.HasValue) - { - if (email.Empty()) - throw new DomainException("Both user id and email can not be empty."); - - if (!email.IsEmail()) - throw new DomainException($"Invalid email: '{email}."); - } - - if (token.Empty()) - throw new DomainException("Token can not be empty."); - - UserId = userId; - Email = email?.ToLowerInvariant(); - Type = type; - Token = token; - Expiry = expiry.ToUniversalTime(); - RequesterIpAddress = ipAddress; - RequesterUserAgent = userAgent; - CreatedAt = DateTime.UtcNow; - UpdatedAt = DateTime.UtcNow; - } - - public void CheckIfCanBeConsumedOrFail() - { - if (Consumed) - throw new DomainException("Token has been already consumed."); - - if (Expiry <= DateTime.UtcNow) - throw new DomainException($"Token has expired at: {Expiry}."); - } - - public void Consume(string ipAddress = null, string userAgent = null) - { - CheckIfCanBeConsumedOrFail(); - Consumed = true; - ConsumerIpAddress = ipAddress; - ConsumerUserAgent = userAgent; - UpdatedAt = DateTime.UtcNow; - } - } - - public enum SecuredOperationType - { - NotSet = 0, - ResetPassword = 1 - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/ServiceException.cs b/src/Web/Warden.Web.Core/Domain/ServiceException.cs deleted file mode 100644 index 9bc3d15..0000000 --- a/src/Web/Warden.Web.Core/Domain/ServiceException.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public class ServiceException : Exception - { - public ServiceException() - { - } - - public ServiceException(string message, params object[] args) : this(null, message, args) - { - } - - public ServiceException(Exception innerException, string message, params object[] args) - : base(string.Format(message, args), innerException) - { - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/State.cs b/src/Web/Warden.Web.Core/Domain/State.cs deleted file mode 100644 index 04517b9..0000000 --- a/src/Web/Warden.Web.Core/Domain/State.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Warden.Web.Core.Domain -{ - public enum State - { - Inactive = 0, - Active = 1, - Locked = 2, - Deleted = 3, - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/User.cs b/src/Web/Warden.Web.Core/Domain/User.cs deleted file mode 100644 index d1c3e94..0000000 --- a/src/Web/Warden.Web.Core/Domain/User.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System; -using System.Linq; -using Warden.Web.Core.Extensions; -using Warden.Web.Core.Services; - -namespace Warden.Web.Core.Domain -{ - public class User : Entity, ITimestampable - { - public string Email { get; protected set; } - public Role Role { get; protected set; } - public State State { get; protected set; } - public string Password { get; protected set; } - public string Salt { get; protected set; } - public DateTime CreatedAt { get; protected set; } - public DateTime UpdatedAt { get; protected set; } - public Guid RecentlyViewedOrganizationId { get; protected set; } - public Guid RecentlyViewedWardenId { get; protected set; } - - protected User() - { - } - - public User(string email, string password, IEncrypter encrypter, Role role = Role.User) - { - SetEmail(email); - SetPassword(password, encrypter); - Role = role; - State = State.Inactive; - CreatedAt = DateTime.UtcNow; - UpdatedAt = DateTime.UtcNow; - } - - public void SetEmail(string email) - { - if (email.Empty()) - throw new DomainException("Email can not be empty."); - - if (!email.IsEmail()) - throw new DomainException($"Invalid email: '{email}."); - - if (Email.EqualsCaseInvariant(email)) - return; - - Email = email.ToLowerInvariant(); - UpdatedAt = DateTime.UtcNow; - } - - public void SetRole(Role role) - { - if (Role == role) - return; - - Role = role; - UpdatedAt = DateTime.UtcNow; - } - - public void SetPassword(string password, IEncrypter encrypter) - { - if (password.Empty()) - throw new DomainException("Password can not be empty."); - - var salt = encrypter.GetSalt(password); - var hash = encrypter.GetHash(password, salt); - - Password = hash; - Salt = salt; - UpdatedAt = DateTime.UtcNow; - } - - public void Lock() - { - if(State == State.Locked) - return; - - State = State.Locked; - UpdatedAt = DateTime.UtcNow; - } - - public void Activate() - { - if (State == State.Active) - return; - - State = State.Active; - UpdatedAt = DateTime.UtcNow; - } - - public void Delete() - { - if (State == State.Deleted) - return; - - State = State.Deleted; - UpdatedAt = DateTime.UtcNow; - } - - public bool ValidatePassword(string password, IEncrypter encrypter) - { - var hashedPassword = encrypter.GetHash(password, Salt); - - return Password.Equals(hashedPassword); - } - - public void SetRecentlyViewedWardenInOrganization(Organization organization, Guid wardenId) - { - var organizationId = organization?.Id ?? Guid.Empty; - var foundWardenId = organization?.Wardens.Any(x => x.Id == wardenId) == true ? wardenId : Guid.Empty; - if (RecentlyViewedOrganizationId == organizationId && RecentlyViewedWardenId == foundWardenId) - return; - - RecentlyViewedOrganizationId = organizationId; - RecentlyViewedWardenId = foundWardenId; - UpdatedAt = DateTime.UtcNow; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/UserInOrganization.cs b/src/Web/Warden.Web.Core/Domain/UserInOrganization.cs deleted file mode 100644 index 06f6641..0000000 --- a/src/Web/Warden.Web.Core/Domain/UserInOrganization.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public class UserInOrganization : ITimestampable - { - public Guid Id { get; protected set; } - public string Email { get; protected set; } - public OrganizationRole Role { get; protected set; } - public DateTime CreatedAt { get; protected set; } - - protected UserInOrganization() - { - } - - protected UserInOrganization(User user, OrganizationRole role) - { - if (user == null) - throw new DomainException("Can not create new user in organization from empty user."); - - Id = user.Id; - Email = user.Email; - Role = role; - CreatedAt = DateTime.UtcNow; - } - - public static UserInOrganization Create(User user, OrganizationRole role = OrganizationRole.User) - => new UserInOrganization(user, role); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/UserSession.cs b/src/Web/Warden.Web.Core/Domain/UserSession.cs deleted file mode 100644 index 8ea2ab2..0000000 --- a/src/Web/Warden.Web.Core/Domain/UserSession.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public class UserSession : Entity, ITimestampable - { - public Guid UserId { get; protected set; } - public string UserAgent { get; protected set; } - public string IpAddress { get; protected set; } - public string Referrer { get; protected set; } - public DateTime CreatedAt { get; protected set; } - - protected UserSession() - { - } - - public UserSession(User user, string userAgent = null, - string ipAddress = null, string referrer = null) - { - if (user == null) - throw new DomainException("Can not create an empty user session."); - - UserId = user.Id; - UserAgent = userAgent; - IpAddress = ipAddress; - Referrer = referrer; - CreatedAt = DateTime.UtcNow; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/Warden.cs b/src/Web/Warden.Web.Core/Domain/Warden.cs deleted file mode 100644 index 5f215b5..0000000 --- a/src/Web/Warden.Web.Core/Domain/Warden.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Domain -{ - public class Warden : Entity, ITimestampable - { - private HashSet _watchers = new HashSet(); - - public string Name { get; protected set; } - public bool Enabled { get; protected set; } - public DateTime CreatedAt { get; protected set; } - public DateTime UpdatedAt { get; protected set; } - - public IEnumerable Watchers - { - get { return _watchers; } - protected set { _watchers = new HashSet(value); } - } - - protected Warden() - { - } - - public Warden(string name, bool enabled = true) - { - SetName(name); - CreatedAt = DateTime.UtcNow; - UpdatedAt = DateTime.UtcNow; - if (enabled) - Enable(); - } - - public void SetName(string name) - { - if (name.Empty()) - throw new DomainException("Warden name can not be empty."); - - Name = name; - UpdatedAt = DateTime.UtcNow; - } - - public void Enable() - { - if (Enabled) - return; - - Enabled = true; - UpdatedAt = DateTime.UtcNow; - } - - public void Disable() - { - if (!Enabled) - return; - - Enabled = false; - UpdatedAt = DateTime.UtcNow; - } - - public void AddWatcher(string name, WatcherType type, string group = null) - { - if (name.Empty()) - throw new DomainException("Can not add a watcher without a name to the Warden."); - - var watcher = GetWatcherByName(name); - if (watcher != null) - throw new DomainException($"Watcher with name: '{name}' has been already added."); - - _watchers.Add(Watcher.Create(name, type, group)); - UpdatedAt = DateTime.UtcNow; - } - - public void RemoveWatcher(string name) - { - if (name.Empty()) - throw new DomainException("Can not remove a watcher without a name from the Warden."); - - var watcher = GetWatcherByNameOrFail(name); - _watchers.Remove(watcher); - UpdatedAt = DateTime.UtcNow; - } - - public Watcher GetWatcherByNameOrFail(string name) - { - if (name.Empty()) - throw new DomainException("Watcher name can not be empty."); - - var watcher = GetWatcherByName(name); - if (watcher == null) - throw new DomainException($"Watcher with name: '{name}' has not been found."); - - return watcher; - } - - public Watcher GetWatcherByName(string name) => Watchers.FirstOrDefault(x => x.Name.EqualsCaseInvariant(name)); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/WardenCheckResult.cs b/src/Web/Warden.Web.Core/Domain/WardenCheckResult.cs deleted file mode 100644 index 35f12e1..0000000 --- a/src/Web/Warden.Web.Core/Domain/WardenCheckResult.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public class WardenCheckResult : IValidatable, ICompletable - { - public bool IsValid { get; protected set; } - public WatcherCheckResult WatcherCheckResult { get; protected set; } - public DateTime StartedAt { get; protected set; } - public DateTime CompletedAt { get; protected set; } - public TimeSpan ExecutionTime => CompletedAt - StartedAt; - public ExceptionInfo Exception { get; protected set; } - - protected WardenCheckResult() - { - } - - protected WardenCheckResult(bool isValid, WatcherCheckResult watcherCheckResult, - DateTime startedAt, DateTime completedAt, ExceptionInfo exception = null) - { - IsValid = isValid; - WatcherCheckResult = watcherCheckResult; - StartedAt = startedAt; - CompletedAt = completedAt; - Exception = exception; - } - - public static WardenCheckResult Valid(WatcherCheckResult watcherCheckResult, - DateTime startedAt, DateTime completedAt) - => new WardenCheckResult(true, watcherCheckResult, startedAt, completedAt); - - public static WardenCheckResult Invalid(WatcherCheckResult watcherCheckResult, - DateTime startedAt, DateTime completedAt, ExceptionInfo exception) - => new WardenCheckResult(false, watcherCheckResult, startedAt, completedAt, exception); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/WardenInfo.cs b/src/Web/Warden.Web.Core/Domain/WardenInfo.cs deleted file mode 100644 index 53917a0..0000000 --- a/src/Web/Warden.Web.Core/Domain/WardenInfo.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; - -namespace Warden.Web.Core.Domain -{ - public class WardenInfo - { - public Guid Id { get; protected set; } - public Guid OrganizationId { get; protected set; } - public string Name { get; protected set; } - - protected WardenInfo() - { - } - - protected WardenInfo(string name, Organization organization) - { - var warden = organization.GetWardenByNameOrFail(name); - if(warden == null) - throw new DomainException("Warden can not be null."); - if (organization == null) - throw new DomainException("Organization can not be null."); - - Id = warden.Id; - OrganizationId = organization.Id; - Name = warden.Name; - } - - public static WardenInfo Create(string name, Organization organization) - => new WardenInfo(name, organization); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/WardenIteration.cs b/src/Web/Warden.Web.Core/Domain/WardenIteration.cs deleted file mode 100644 index a722cfd..0000000 --- a/src/Web/Warden.Web.Core/Domain/WardenIteration.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Warden.Web.Core.Domain -{ - public class WardenIteration : Entity, ITimestampable, ICompletable, IValidatable - { - private HashSet _results = new HashSet(); - - public WardenInfo Warden { get; protected set; } - public long Ordinal { get; protected set; } - public DateTime CreatedAt { get; protected set; } - public DateTime StartedAt { get; protected set; } - public DateTime CompletedAt { get; protected set; } - public TimeSpan ExecutionTime { get; protected set; } - public bool IsValid { get; protected set; } - - public IEnumerable Results - { - get { return _results; } - protected set { _results = new HashSet(value); } - } - - protected WardenIteration() - { - } - - public WardenIteration(string wardenName, Organization organization, long ordinal, - DateTime startedAt, DateTime completedAt, bool isValid) - { - Warden = WardenInfo.Create(wardenName, organization); - Ordinal = ordinal; - StartedAt = startedAt; - CompletedAt = completedAt; - ExecutionTime = CompletedAt - StartedAt; - IsValid = isValid; - CreatedAt = DateTime.Now; - } - - public void AddResult(WardenCheckResult result) - { - if (result == null) - throw new DomainException("Can not add null warden check result."); - - if (Results.Contains(result)) - return; - - _results.Add(result); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/Watcher.cs b/src/Web/Warden.Web.Core/Domain/Watcher.cs deleted file mode 100644 index 196df73..0000000 --- a/src/Web/Warden.Web.Core/Domain/Watcher.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Domain -{ - public class Watcher - { - public string Name { get; protected set; } - public WatcherType Type { get; protected set; } - public string Group { get; protected set; } - - protected Watcher() - { - } - - protected Watcher(string name, WatcherType type, string group) - { - if (name.Empty()) - throw new DomainException("Watcher name not be empty."); - - Name = name; - Type = type; - Group = group; - } - - public static Watcher Create(string name, WatcherType type, string group = null) - => new Watcher(name, type, group); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/WatcherCheckResult.cs b/src/Web/Warden.Web.Core/Domain/WatcherCheckResult.cs deleted file mode 100644 index a1e80cb..0000000 --- a/src/Web/Warden.Web.Core/Domain/WatcherCheckResult.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace Warden.Web.Core.Domain -{ - public class WatcherCheckResult : IValidatable - { - public Watcher Watcher { get; protected set; } - public string Description { get; protected set; } - public bool IsValid { get; protected set; } - - protected WatcherCheckResult() - { - } - - protected WatcherCheckResult(Watcher watcher, string description, bool isValid) - { - if(watcher == null) - throw new DomainException("Watcher can not be null."); - - Watcher = watcher; - Description = description; - IsValid = isValid; - } - - public static WatcherCheckResult Valid(Watcher watcher, string description) - => new WatcherCheckResult(watcher, description, true); - - public static WatcherCheckResult Invalid(Watcher watcher, string description) - => new WatcherCheckResult(watcher, description, false); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Domain/WatcherType.cs b/src/Web/Warden.Web.Core/Domain/WatcherType.cs deleted file mode 100644 index 0258f8a..0000000 --- a/src/Web/Warden.Web.Core/Domain/WatcherType.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Warden.Web.Core.Domain -{ - public enum WatcherType - { - Custom = 0, - Disk = 1, - MongoDb = 2, - MsSql = 3, - Performance = 4, - Process = 5, - Redis = 6, - Server = 7, - Web = 8 - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/ExceptionDto.cs b/src/Web/Warden.Web.Core/Dto/ExceptionDto.cs deleted file mode 100644 index 1dd3df2..0000000 --- a/src/Web/Warden.Web.Core/Dto/ExceptionDto.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Newtonsoft.Json; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Dto -{ - public class ExceptionDto - { - public string Message { get; set; } - public string Source { get; set; } - - [JsonProperty("StackTraceString")] - public string StackTrace { get; set; } - - public ExceptionDto InnerException { get; set; } - - public ExceptionDto() - { - } - - public ExceptionDto(ExceptionInfo exception) - { - Message = exception.Message; - Source = exception.Source; - StackTrace = exception.StackTrace; - InnerException = exception.InnerException == null ? null : new ExceptionDto(exception.InnerException); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/OrganizationDto.cs b/src/Web/Warden.Web.Core/Dto/OrganizationDto.cs deleted file mode 100644 index c3446e6..0000000 --- a/src/Web/Warden.Web.Core/Dto/OrganizationDto.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Dto -{ - public class OrganizationDto - { - public Guid Id { get; set; } - public Guid OwnerId { get; set; } - public string Name { get; set; } - public bool AutoRegisterNewWarden { get; set; } - public IEnumerable Users { get; set; } - public IEnumerable Wardens { get; set; } - - public OrganizationDto() - { - } - - public OrganizationDto(Organization organization) - { - Id = organization.Id; - OwnerId = organization.OwnerId; - Name = organization.Name; - AutoRegisterNewWarden = organization.AutoRegisterNewWarden; - Users = organization.Users.Select(x => new UserInOrganizationDto(x)); - Wardens = organization.Wardens.Select(x => new WardenDto(x)); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/StatsDto.cs b/src/Web/Warden.Web.Core/Dto/StatsDto.cs deleted file mode 100644 index 5df6f17..0000000 --- a/src/Web/Warden.Web.Core/Dto/StatsDto.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Warden.Web.Core.Dto -{ - public class StatsDto - { - public double TotalUptime { get; set; } - public double TotalDowntime { get; set; } - public double TotalResults { get; set; } - public double TotalValidResults { get; set; } - public double TotalInvalidResults { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/UserDto.cs b/src/Web/Warden.Web.Core/Dto/UserDto.cs deleted file mode 100644 index 4322274..0000000 --- a/src/Web/Warden.Web.Core/Dto/UserDto.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Dto -{ - public class UserDto - { - public Guid Id { get; set; } - public string Email { get; set; } - public Role Role { get; set; } - public Guid RecentlyViewedOrganizationId { get; set; } - public Guid RecentlyViewedWardenId { get; set; } - public IEnumerable ApiKeys { get; set; } - - public UserDto() - { - } - - public UserDto(User user) - { - Id = user.Id; - Email = user.Email; - Role = user.Role; - RecentlyViewedOrganizationId = user.RecentlyViewedOrganizationId; - RecentlyViewedWardenId = user.RecentlyViewedWardenId; - ApiKeys = Enumerable.Empty(); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/UserInOrganizationDto.cs b/src/Web/Warden.Web.Core/Dto/UserInOrganizationDto.cs deleted file mode 100644 index ff2d8a9..0000000 --- a/src/Web/Warden.Web.Core/Dto/UserInOrganizationDto.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Dto -{ - public class UserInOrganizationDto - { - public Guid Id { get; set; } - public string Email { get; set; } - public OrganizationRole Role { get; set; } - public DateTime CreatedAt { get; set; } - - public UserInOrganizationDto() - { - } - - public UserInOrganizationDto(UserInOrganization user) - { - Id = user.Id; - Email = user.Email; - Role = user.Role; - CreatedAt = user.CreatedAt; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/WardenCheckResultDto.cs b/src/Web/Warden.Web.Core/Dto/WardenCheckResultDto.cs deleted file mode 100644 index f41280e..0000000 --- a/src/Web/Warden.Web.Core/Dto/WardenCheckResultDto.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Dto -{ - public class WardenCheckResultDto - { - public Guid IterationId { get; set; } - public bool IsValid { get; set; } - public WatcherCheckResultDto WatcherCheckResult { get; set; } - public DateTime StartedAt { get; set; } - public DateTime CompletedAt { get; set; } - public TimeSpan ExecutionTime { get; set; } - public ExceptionDto Exception { get; set; } - - public WardenCheckResultDto() - { - } - - public WardenCheckResultDto(WardenCheckResult result) - { - IsValid = result.IsValid; - WatcherCheckResult = new WatcherCheckResultDto(result.WatcherCheckResult); - StartedAt = result.StartedAt; - CompletedAt = result.CompletedAt; - ExecutionTime = result.ExecutionTime; - Exception = result.Exception == null ? null : new ExceptionDto(result.Exception); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/WardenDto.cs b/src/Web/Warden.Web.Core/Dto/WardenDto.cs deleted file mode 100644 index 4be110a..0000000 --- a/src/Web/Warden.Web.Core/Dto/WardenDto.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Warden.Web.Core.Dto -{ - public class WardenDto - { - public Guid Id { get; set; } - public string Name { get; set; } - public bool Enabled { get; set; } - public DateTime CreatedAt { get; set; } - public IEnumerable Watchers { get; set; } - - public WardenDto() - { - } - - public WardenDto(Domain.Warden warden) - { - Id = warden.Id; - Name = warden.Name; - Enabled = warden.Enabled; - CreatedAt = warden.CreatedAt; - Watchers = warden.Watchers.Select(x => new WatcherDto(x)); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/WardenIterationDto.cs b/src/Web/Warden.Web.Core/Dto/WardenIterationDto.cs deleted file mode 100644 index f736c27..0000000 --- a/src/Web/Warden.Web.Core/Dto/WardenIterationDto.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Dto -{ - public class WardenIterationDto - { - public Guid Id { get; set; } - public string WardenName { get; set; } - public long Ordinal { get; set; } - public DateTime StartedAt { get; set; } - public DateTime CompletedAt { get; set; } - public TimeSpan ExecutionTime { get; set; } - public bool IsValid { get; set; } - public IEnumerable Results { get; set; } - - public WardenIterationDto() - { - } - - public WardenIterationDto(WardenIteration iteration) - { - Id = iteration.Id; - WardenName = iteration.Warden.Name; - Ordinal = iteration.Ordinal; - StartedAt = iteration.StartedAt; - CompletedAt = iteration.CompletedAt; - ExecutionTime = iteration.ExecutionTime; - IsValid = iteration.IsValid; - Results = iteration.Results.Select(x => new WardenCheckResultDto(x) - { - IterationId = iteration.Id - }); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/WardenStatsDto.cs b/src/Web/Warden.Web.Core/Dto/WardenStatsDto.cs deleted file mode 100644 index f019dae..0000000 --- a/src/Web/Warden.Web.Core/Dto/WardenStatsDto.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Warden.Web.Core.Dto -{ - public class WardenStatsDto - { - public Guid OrganizationId { get; set; } - public string WardenName { get; set; } - public bool Enabled { get; set; } - public DateTime From { get; set; } - public DateTime To { get; set; } - public double TotalUptime { get; set; } - public double TotalDowntime { get; set; } - public double TotalIterations { get; set; } - public double TotalValidIterations { get; set; } - public double TotalInvalidIterations { get; set; } - public IEnumerable Watchers { get; set; } = new List(); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/WatcherCheckResultDto.cs b/src/Web/Warden.Web.Core/Dto/WatcherCheckResultDto.cs deleted file mode 100644 index 3107ca9..0000000 --- a/src/Web/Warden.Web.Core/Dto/WatcherCheckResultDto.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Dto -{ - public class WatcherCheckResultDto - { - public string WatcherName { get; set; } - public string WatcherGroup { get; set; } - public string WatcherType { get; set; } - public string Description { get; set; } - public bool IsValid { get; set; } - - public WatcherCheckResultDto() - { - } - - public WatcherCheckResultDto(WatcherCheckResult result) - { - WatcherName = result.Watcher.Name; - WatcherType = result.Watcher.Type.ToString().ToLowerInvariant(); - WatcherGroup = result.Watcher.Group; - Description = result.Description; - IsValid = result.IsValid; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/WatcherDto.cs b/src/Web/Warden.Web.Core/Dto/WatcherDto.cs deleted file mode 100644 index a46ad99..0000000 --- a/src/Web/Warden.Web.Core/Dto/WatcherDto.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Dto -{ - public class WatcherDto - { - public string Name { get; set; } - public string Type { get; set; } - - public WatcherDto() - { - } - - public WatcherDto(Watcher watcher) - { - Name = watcher.Name; - Type = watcher.Type.ToString().ToLowerInvariant(); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Dto/WatcherStatsDto.cs b/src/Web/Warden.Web.Core/Dto/WatcherStatsDto.cs deleted file mode 100644 index f274a0b..0000000 --- a/src/Web/Warden.Web.Core/Dto/WatcherStatsDto.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace Warden.Web.Core.Dto -{ - public class WatcherStatsDto : WatcherDto - { - public double TotalUptime { get; set; } - public double TotalDowntime { get; set; } - public double TotalChecks { get; set; } - public double TotalValidChecks { get; set; } - public double TotalInvalidChecks { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Extensions/ObjectExtensions.cs b/src/Web/Warden.Web.Core/Extensions/ObjectExtensions.cs deleted file mode 100644 index 6ad2d10..0000000 --- a/src/Web/Warden.Web.Core/Extensions/ObjectExtensions.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Serialization; - -namespace Warden.Web.Core.Extensions -{ - public static class ObjectExtensions - { - public static readonly JsonSerializerSettings DefaultJsonSerializerSettings = new JsonSerializerSettings - { - ReferenceLoopHandling = ReferenceLoopHandling.Ignore, - ContractResolver = new CamelCasePropertyNamesContractResolver(), - DateFormatString = "yyyy-MM-dd H:mm:ss", - Formatting = Formatting.Indented, - DefaultValueHandling = DefaultValueHandling.Populate, - NullValueHandling = NullValueHandling.Include, - Converters = new List - { - new StringEnumConverter - { - AllowIntegerValues = true, - CamelCaseText = true - } - } - }; - - public static string ToJson(this T value, JsonSerializerSettings serializerSettings = null) - { - return JsonConvert.SerializeObject(value, serializerSettings ?? DefaultJsonSerializerSettings); - } - - public static T FromJson(this string value, JsonSerializerSettings serializerSettings = null) - { - return JsonConvert.DeserializeObject(value, serializerSettings ?? DefaultJsonSerializerSettings); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Extensions/StringExtensions.cs b/src/Web/Warden.Web.Core/Extensions/StringExtensions.cs deleted file mode 100644 index 081d49f..0000000 --- a/src/Web/Warden.Web.Core/Extensions/StringExtensions.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; - -namespace Warden.Web.Core.Extensions -{ - public static class StringExtensions - { - private static readonly Regex EmailRegex = new Regex( - @"^(?("")("".+?(? string.IsNullOrWhiteSpace(target); - - public static bool NotEmpty(this string target) => !target.Empty(); - - public static string TrimToUpper(this string value) - { - return value.OrEmpty().Trim().ToUpperInvariant(); - } - - public static string TrimToLower(this string value) - { - return value.OrEmpty().Trim().ToLowerInvariant(); - } - - public static string OrEmpty(this string value) - { - return value.Empty() ? "" : value; - } - - public static bool EqualsCaseInvariant(this string value, string valueToCompare) - { - if (value.Empty()) - return valueToCompare.Empty(); - if (valueToCompare.Empty()) - return false; - - var fixedValue = value.TrimToUpper(); - var fixedValueToCompare = valueToCompare.TrimToUpper(); - - return fixedValue == fixedValueToCompare; - } - - public static bool Like(this string value, string valueToCompare) - { - if (value.Empty()) - return valueToCompare.Empty(); - - var fixedValue = value.TrimToUpper(); - var fixedValueToCompare = valueToCompare.TrimToUpper(); - - return fixedValue.Contains(fixedValueToCompare); - } - - public static string AggregateLines(this IEnumerable values) - => values.Aggregate((x, y) => $"{x.Trim()}\n{y.Trim()}"); - - public static bool IsEmail(this string value) => value.NotEmpty() && EmailRegex.IsMatch(value); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Factories/ISecuredOperationFactory.cs b/src/Web/Warden.Web.Core/Factories/ISecuredOperationFactory.cs deleted file mode 100644 index 3758a9e..0000000 --- a/src/Web/Warden.Web.Core/Factories/ISecuredOperationFactory.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Linq; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Factories -{ - public interface ISecuredOperationFactory - { - SecuredOperation Create(SecuredOperationType operationType, DateTime expiry, - Guid? userId = null, string email = null, - string ipAddress = null, string userAgent = null); - } - - public class SecuredOperationFactory : ISecuredOperationFactory - { - private const string Chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - private static readonly Random Random = new Random(); - - public SecuredOperation Create(SecuredOperationType operationType, DateTime expiry, - Guid? userId = null, string email = null, - string ipAddress = null, string userAgent = null) - { - var token = new string(Enumerable.Repeat(Chars, Random.Next(80, 120)) - .Select(s => s[Random.Next(s.Length)]).ToArray()); - - var operation = new SecuredOperation(operationType, token, expiry, - userId, email, ipAddress, userAgent); - - return operation; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Mongo/MongoConfigurator.cs b/src/Web/Warden.Web.Core/Mongo/MongoConfigurator.cs deleted file mode 100644 index abf39b9..0000000 --- a/src/Web/Warden.Web.Core/Mongo/MongoConfigurator.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Collections.Generic; -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Conventions; - -namespace Warden.Web.Core.Mongo -{ - public static class MongoConfigurator - { - private static bool _initialized; - - public static void Initialize() - { - if (_initialized) - return; - - RegisterConventions(); - } - - private static void RegisterConventions() - { - ConventionRegistry.Register("WardenConventions", new MongoConvention(), x => true); - _initialized = true; - } - - private class MongoConvention : IConventionPack - { - public IEnumerable Conventions => new List - { - new IgnoreExtraElementsConvention(true), - new EnumRepresentationConvention(BsonType.String), - }; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Mongo/Pagination.cs b/src/Web/Warden.Web.Core/Mongo/Pagination.cs deleted file mode 100644 index fc91642..0000000 --- a/src/Web/Warden.Web.Core/Mongo/Pagination.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Threading.Tasks; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Mongo -{ - public static class Pagination - { - public static async Task> PaginateAsync(this IMongoQueryable collection, PagedQueryBase query) - => await collection.PaginateAsync(query.Page, query.Results); - - public static async Task> PaginateAsync(this IMongoQueryable collection, - int page = 1, int resultsPerPage = 10) - { - if (page <= 0) - page = 1; - - if (resultsPerPage <= 0) - resultsPerPage = 10; - - var isEmpty = await collection.AnyAsync() == false; - if (isEmpty) - return PagedResult.Empty; - - var totalResults = await collection.CountAsync(); - var totalPages = (int)Math.Ceiling((double)totalResults / resultsPerPage); - var data = await collection.Limit(page, resultsPerPage).ToListAsync(); - - return PagedResult.Create(data, page, resultsPerPage, totalPages, totalResults); - } - - public static IMongoQueryable Limit(this IMongoQueryable collection, PagedQueryBase query) - => collection.Limit(query.Page, query.Results); - - public static IMongoQueryable Limit(this IMongoQueryable collection, - int page = 1, int resultsPerPage = 10) - { - if (page <= 0) - page = 1; - - if (resultsPerPage <= 0) - resultsPerPage = 10; - - var skip = (page - 1) * resultsPerPage; - var data = collection.Skip(skip) - .Take(resultsPerPage); - - return data; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Mongo/Queries/ApiKeyQueries.cs b/src/Web/Warden.Web.Core/Mongo/Queries/ApiKeyQueries.cs deleted file mode 100644 index 706846f..0000000 --- a/src/Web/Warden.Web.Core/Mongo/Queries/ApiKeyQueries.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Mongo.Queries -{ - public static class ApiKeyQueries - { - public static IMongoCollection ApiKeys(this IMongoDatabase database) - => database.GetCollection("ApiKeys"); - - public static async Task GetByKeyAsync(this IMongoCollection keys, - string key) - { - if (key.Empty()) - return null; - - return await keys.AsQueryable().FirstOrDefaultAsync(x => x.Key == key); - } - - public static async Task> GetAllForUserAsync(this IMongoCollection keys, - Guid userId) - { - if (userId == Guid.Empty) - return Enumerable.Empty(); - - return await keys.AsQueryable() - .Where(x => x.UserId == userId) - .ToListAsync(); - } - - public static async Task ExistsAsync(this IMongoCollection keys, - string key) => await keys.AsQueryable().AnyAsync(x => x.Key == key); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Mongo/Queries/OrganizationQueries.cs b/src/Web/Warden.Web.Core/Mongo/Queries/OrganizationQueries.cs deleted file mode 100644 index a5ce120..0000000 --- a/src/Web/Warden.Web.Core/Mongo/Queries/OrganizationQueries.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Extensions; -using Warden.Web.Core.Queries; - -namespace Warden.Web.Core.Mongo.Queries -{ - public static class OrganizationQueries - { - public static IMongoCollection Organizations(this IMongoDatabase database) - => database.GetCollection("Organizations"); - - public static async Task GetByIdAsync(this IMongoCollection organizations, - Guid id) - { - if (id == Guid.Empty) - return null; - - return await organizations.AsQueryable().FirstOrDefaultAsync(x => x.Id == id); - } - - public static async Task GetWardenByIdAsync(this IMongoCollection organizations, - Guid organizationId, Guid wardenId) - { - if (organizationId == Guid.Empty || wardenId == Guid.Empty) - return null; - - return await organizations.AsQueryable() - .Where(x => x.Id == organizationId) - .SelectMany(x => x.Wardens) - .FirstOrDefaultAsync(x => x.Id == wardenId); - } - - public static async Task GetWardenByNameAsync(this IMongoCollection organizations, - Guid organizationId, string wardenName) - { - if (organizationId == Guid.Empty || wardenName.Empty()) - return null; - - return await organizations.AsQueryable() - .Where(x => x.Id == organizationId) - .SelectMany(x => x.Wardens) - .FirstOrDefaultAsync(x => x.Name == wardenName); - } - - public static async Task GetByNameForOwnerAsync(this IMongoCollection organizations, - string name, Guid ownerId) - { - if (name.Empty() || ownerId == Guid.Empty) - return null; - - var fixedName = name.TrimToLower(); - return await organizations.AsQueryable().FirstOrDefaultAsync(x => x.Name.ToLower() == fixedName && x.OwnerId == ownerId); - } - - public static IMongoQueryable Query(this IMongoCollection organizations, - BrowseOrganizations query) - { - var values = organizations.AsQueryable(); - if (query.UserId != Guid.Empty) - values = values.Where(x => x.Users.Any(u => u.Id == query.UserId)); - if (query.OwnerId != Guid.Empty) - values = values.Where(x => x.OwnerId == query.OwnerId); - - return values; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Mongo/Queries/SecuredOperationQueries.cs b/src/Web/Warden.Web.Core/Mongo/Queries/SecuredOperationQueries.cs deleted file mode 100644 index 36f1b36..0000000 --- a/src/Web/Warden.Web.Core/Mongo/Queries/SecuredOperationQueries.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Threading.Tasks; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Mongo.Queries -{ - public static class SecuredOperationQueries - { - public static IMongoCollection SecuredOperations(this IMongoDatabase database) - => database.GetCollection("SecuredOperations"); - - public static async Task GetByUserIdAndTokenAsync( - this IMongoCollection operations, - Guid userId, string token) - { - if (userId == Guid.Empty) - return null; - - if (token.Empty()) - return null; - - var operation = await operations.AsQueryable() - .FirstOrDefaultAsync(x => x.UserId == userId && x.Token.Equals(token)); - - return operation; - } - - public static async Task GetByEmailAndTokenAsync( - this IMongoCollection operations, - string email, string token) - { - if (email.Empty()) - return null; - - if (token.Empty()) - return null; - - var fixedEmail = email.ToLowerInvariant(); - var operation = - await operations.AsQueryable() - .FirstOrDefaultAsync(x => x.Email.Equals(fixedEmail) && x.Token.Equals(token)); - - return operation; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Mongo/Queries/UserQueries.cs b/src/Web/Warden.Web.Core/Mongo/Queries/UserQueries.cs deleted file mode 100644 index 107e61b..0000000 --- a/src/Web/Warden.Web.Core/Mongo/Queries/UserQueries.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Threading.Tasks; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Mongo.Queries -{ - public static class UserQueries - { - public static IMongoCollection Users(this IMongoDatabase database) - => database.GetCollection("Users"); - - public static async Task GetByIdAsync(this IMongoCollection users, Guid id) - { - if (id == Guid.Empty) - return null; - - return await users.AsQueryable().FirstOrDefaultAsync(x => x.Id == id); - } - - public static async Task GetByEmailAsync(this IMongoCollection users, string email) - { - if (!email.IsEmail()) - return null; - - var fixedEmail = email.TrimToLower(); - return await users.AsQueryable().FirstOrDefaultAsync(x => x.Email == fixedEmail); - } - - public static async Task ExistsAsync(this IMongoCollection users, string email) - { - var fixedEmail = email.TrimToLower(); - return await users.AsQueryable().AnyAsync(x => x.Email == fixedEmail); - } - - public static async Task IsActiveAsync(this IMongoCollection users, Guid id) - { - if (id == Guid.Empty) - return false; - - return await users.AsQueryable().AnyAsync(x => x.Id == id && x.State == State.Active); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Mongo/Queries/UserSessionQueries.cs b/src/Web/Warden.Web.Core/Mongo/Queries/UserSessionQueries.cs deleted file mode 100644 index 7a0066e..0000000 --- a/src/Web/Warden.Web.Core/Mongo/Queries/UserSessionQueries.cs +++ /dev/null @@ -1,11 +0,0 @@ -using MongoDB.Driver; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Mongo.Queries -{ - public static class UserSessionQueries - { - public static IMongoCollection UserSessions(this IMongoDatabase database) - => database.GetCollection("UserSessions"); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Mongo/Queries/WardenIterationQueries.cs b/src/Web/Warden.Web.Core/Mongo/Queries/WardenIterationQueries.cs deleted file mode 100644 index 00026c4..0000000 --- a/src/Web/Warden.Web.Core/Mongo/Queries/WardenIterationQueries.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Linq; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Extensions; -using Warden.Web.Core.Queries; - -namespace Warden.Web.Core.Mongo.Queries -{ - public static class WardenIterationQueries - { - public static IMongoCollection WardenIterations(this IMongoDatabase database) - => database.GetCollection("WardenIterations"); - - public static async Task GetByIdAsync(this IMongoCollection iterations, - Guid id) - { - if (id == Guid.Empty) - return null; - - return await iterations.AsQueryable().FirstOrDefaultAsync(x => x.Id == id); - } - - - public static async Task> GetForWardenAsync(this IMongoCollection iterations, - Guid organizationId, string wardenName) - { - if (organizationId == Guid.Empty || wardenName.Empty()) - return Enumerable.Empty(); - - wardenName = wardenName.Trim(); - - return await iterations.AsQueryable() - .Where(x => x.Warden.OrganizationId == organizationId && x.Warden.Name == wardenName) - .ToListAsync(); - } - - public static async Task> GetForWatcherAsync( - this IMongoCollection iterations, - Guid organizationId, Guid wardenId, string watcherName) - { - if (organizationId == Guid.Empty || wardenId == Guid.Empty || watcherName.Empty()) - return Enumerable.Empty(); - - watcherName = watcherName.Trim(); - - return await iterations.AsQueryable() - .Where(x => x.Warden.OrganizationId == organizationId && x.Warden.Id == wardenId && - x.Results.Any(r => r.WatcherCheckResult.Watcher.Name == watcherName)) - .ToListAsync(); - } - - public static IMongoQueryable Query(this IMongoCollection iterations, - BrowseWardenIterations query) - { - var values = iterations.AsQueryable(); - if (query.OrganizationId != Guid.Empty) - values = values.Where(x => x.Warden.OrganizationId == query.OrganizationId); - if (query.WardenName.NotEmpty()) - { - var fixedWardenName = query.WardenName.TrimToLower(); - values = values.Where(x => x.Warden.Name.ToLower() == fixedWardenName); - } - if (query.WardenId != Guid.Empty) - { - values = values.Where(x => x.Warden.Id == query.WardenId); - } - switch (query.ResultType) - { - case ResultType.Valid: - values = values.Where(x => x.IsValid); - break; - case ResultType.Invalid: - values = values.Where(x => !x.IsValid); - break; - } - - var watcherName = query.WatcherName?.Trim() ?? string.Empty; - if (!string.IsNullOrWhiteSpace(watcherName)) - { - values = values.Where(x => - x.Results.Any(r => r.WatcherCheckResult.Watcher.Name == watcherName)); - } - - if (query.WatcherType.HasValue) - { - values = values.Where(x => - x.Results.Any(r => r.WatcherCheckResult.Watcher.Type == query.WatcherType)); - } - - if (query.From.HasValue) - values = values.Where(x => x.CompletedAt >= query.From); - if (query.To.HasValue) - values = values.Where(x => x.CompletedAt <= query.To); - - return values.OrderByDescending(x => x.CompletedAt); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Properties/AssemblyInfo.cs b/src/Web/Warden.Web.Core/Properties/AssemblyInfo.cs deleted file mode 100644 index 8a7314d..0000000 --- a/src/Web/Warden.Web.Core/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -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("Warden.Web.Core")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Warden.Web.Core")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[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("b2f4058c-e459-492e-b40f-1bb92c63cc95")] diff --git a/src/Web/Warden.Web.Core/Properties/launchSettings.json b/src/Web/Warden.Web.Core/Properties/launchSettings.json deleted file mode 100644 index 5558127..0000000 --- a/src/Web/Warden.Web.Core/Properties/launchSettings.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:46795/", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Queries/BrowseOrganizations.cs b/src/Web/Warden.Web.Core/Queries/BrowseOrganizations.cs deleted file mode 100644 index 6b72c9c..0000000 --- a/src/Web/Warden.Web.Core/Queries/BrowseOrganizations.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using Newtonsoft.Json; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Queries -{ - public class BrowseOrganizations : PagedQueryBase - { - [JsonIgnore] - public Guid UserId { get; set; } - - [JsonIgnore] - public Guid OwnerId { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Queries/BrowseWardenCheckResults.cs b/src/Web/Warden.Web.Core/Queries/BrowseWardenCheckResults.cs deleted file mode 100644 index 173efd6..0000000 --- a/src/Web/Warden.Web.Core/Queries/BrowseWardenCheckResults.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using Newtonsoft.Json; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Queries -{ - public class BrowseWardenCheckResults : PagedQueryBase - { - public Guid OrganizationId { get; set; } - public string WardenName { get; set; } - public Guid WardenId { get; set; } - public string WatcherName { get; set; } - public WatcherType? WatcherType { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Queries/BrowseWardenIterations.cs b/src/Web/Warden.Web.Core/Queries/BrowseWardenIterations.cs deleted file mode 100644 index cc8139c..0000000 --- a/src/Web/Warden.Web.Core/Queries/BrowseWardenIterations.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Queries -{ - public class BrowseWardenIterations : PagedQueryBase - { - public Guid OrganizationId { get; set; } - public string WardenName { get; set; } - public Guid WardenId { get; set; } - public string WatcherName { get; set; } - public WatcherType? WatcherType { get; set; } - public DateTime? From { get; set; } - public DateTime? To { get; set; } - public ResultType ResultType { get; set; } - } - - public enum ResultType - { - All = 0, - Valid = 1, - Invalid = 2 - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Queries/BrowseWatchers.cs b/src/Web/Warden.Web.Core/Queries/BrowseWatchers.cs deleted file mode 100644 index af05e66..0000000 --- a/src/Web/Warden.Web.Core/Queries/BrowseWatchers.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Queries -{ - public class BrowseWatchers: PagedQueryBase - { - public Guid OrganizationId { get; set; } - public Guid WardenId { get; set; } - public WatcherType? WatcherType { get; set; } - public DateTime? From { get; set; } - public DateTime? To { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Queries/GetWardenStats.cs b/src/Web/Warden.Web.Core/Queries/GetWardenStats.cs deleted file mode 100644 index bc22a66..0000000 --- a/src/Web/Warden.Web.Core/Queries/GetWardenStats.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Queries -{ - public class GetWardenStats : PagedQueryBase - { - public Guid OrganizationId { get; set; } - public string WardenName { get; set; } - public DateTime? From { get; set; } - public DateTime? To { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Queries/GetWatcherStats.cs b/src/Web/Warden.Web.Core/Queries/GetWatcherStats.cs deleted file mode 100644 index ac83c08..0000000 --- a/src/Web/Warden.Web.Core/Queries/GetWatcherStats.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Core.Queries -{ - public class GetWatcherStats : PagedQueryBase - { - public Guid OrganizationId { get; set; } - public Guid WardenId { get; set; } - public string WatcherName { get; set; } - public DateTime? From { get; set; } - public DateTime? To { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Services/IApiKeyService.cs b/src/Web/Warden.Web.Core/Services/IApiKeyService.cs deleted file mode 100644 index 249a3e3..0000000 --- a/src/Web/Warden.Web.Core/Services/IApiKeyService.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Threading.Tasks; -using MongoDB.Driver; -using NLog; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Mongo.Queries; -using Warden.Web.Core.Settings; - -namespace Warden.Web.Core.Services -{ - public interface IApiKeyService - { - Task GetAsync(string key); - Task CreateAsync(Guid userId); - Task CreateAsync(string email); - Task DeleteAsync(string key); - } - - public class ApiKeyService : IApiKeyService - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private readonly IMongoDatabase _database; - private readonly IEncrypter _encrypter; - private readonly FeatureSettings _featureSettings; - private readonly int RetryTimes = 5; - - public ApiKeyService(IMongoDatabase database, IEncrypter encrypter, FeatureSettings featureSettings) - { - _database = database; - _encrypter = encrypter; - _featureSettings = featureSettings; - } - - public async Task GetAsync(string key) - { - var apiKey = await _database.ApiKeys().GetByKeyAsync(key); - - return apiKey; - } - - public async Task CreateAsync(Guid userId) - { - var user = await _database.Users().GetByIdAsync(userId); - if (user == null) - throw new ServiceException($"User has not been found for id: '{userId}'."); - - await CreateAsync(user); - } - - public async Task CreateAsync(string email) - { - var user = await _database.Users().GetByEmailAsync(email); - if (user == null) - throw new ServiceException($"User has not been found for email: '{email}'."); - - await CreateAsync(user); - } - - private async Task CreateAsync(User user) - { - var apiKeysCount = await _database.ApiKeys().CountAsync(x => x.UserId == user.Id); - if (apiKeysCount >= _featureSettings.MaxApiKeys) - { - throw new ServiceException($"Limit of {_featureSettings.MaxApiKeys} " + - "API keys has been reached."); - } - - var isValid = false; - var currentTry = 0; - var key = string.Empty; - while (currentTry < RetryTimes) - { - key = _encrypter.GetRandomSecureKey(); - isValid = await _database.ApiKeys().ExistsAsync(key) == false; - if (isValid) - break; - - currentTry++; - } - - if (!isValid) - throw new ServiceException("Could not create an API key, please try again."); - - var apiKey = new ApiKey(key, user); - await _database.ApiKeys().InsertOneAsync(apiKey); - Logger.Info($"New API key with id: '{apiKey.Id}' was created by user: '{user.Id}'."); - } - - public async Task DeleteAsync(string key) - { - var apiKey = await _database.ApiKeys().GetByKeyAsync(key); - if (apiKey == null) - throw new ServiceException($"API key has not been found for key: '{key}'."); - - await _database.ApiKeys().DeleteOneAsync(x => x.Id == apiKey.Id); - Logger.Info($"API key with id: '{apiKey.Id}' was deleted'."); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Services/IEmailSender.cs b/src/Web/Warden.Web.Core/Services/IEmailSender.cs deleted file mode 100644 index 71b3fa7..0000000 --- a/src/Web/Warden.Web.Core/Services/IEmailSender.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Mail; -using System.Threading.Tasks; -using NLog; -using SendGrid; -using Warden.Web.Core.Extensions; -using Warden.Web.Core.Settings; - -namespace Warden.Web.Core.Services -{ - public interface IEmailSender - { - Task SendEmailAsync(string sender, string receiver, string subject, - string message); - - Task SendTemplatedEmailAsync(string templateName, string sender, - string receiver, IDictionary> parameters = null); - - Task SendAccountCreatedEmailAsync(string receiver); - Task SendResetPasswordEmailAsync(string receiver, string token); - Task SendPasswordChangedEmailAsync(string receiver); - } - - public class SendGridEmailSender : IEmailSender - { - private readonly EmailSettings _emailSettings; - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private const string AccountCreatedTemplateName = "account-created"; - private const string ResetPasswordTemplateName = "reset-password"; - private const string ResetPasswordParameterUrlName = "url"; - private const string PasswordChangedTemplateName = "password-changed"; - - public SendGridEmailSender(EmailSettings emailSettings) - { - _emailSettings = emailSettings; - } - - public async Task SendEmailAsync(string sender, string receiver, string subject, string message) - { - if (IsSenderDisabled()) - return; - - var emailMessage = CreateMessage(receiver, sender, subject, message); - await SendMessageAsync(emailMessage); - Logger.Trace($"Email message has been sent -> sender: {sender}, receiver: {receiver}"); - } - - public async Task SendAccountCreatedEmailAsync(string receiver) - { - await SendTemplatedEmailAsync(AccountCreatedTemplateName, _emailSettings.NoReplyAccount, receiver); - } - - public async Task SendResetPasswordEmailAsync(string receiver, string token) - { - var template = GetTemplate(ResetPasswordTemplateName); - var urlParameter = template?.Parameters - .FirstOrDefault(x => x.Name.EqualsCaseInvariant(ResetPasswordParameterUrlName)); - if (urlParameter == null) - return; - - var baseUrl = urlParameter.Values.FirstOrDefault(); - if(baseUrl.Empty()) - return; - - var resetPasswordUrl = $"{baseUrl}?token={token}&email={receiver}"; - await SendTemplatedEmailAsync(ResetPasswordTemplateName, _emailSettings.NoReplyAccount, receiver, - new Dictionary> - { - [urlParameter.Name] = new List {resetPasswordUrl} - }); - } - - public async Task SendPasswordChangedEmailAsync(string receiver) - { - await SendTemplatedEmailAsync(PasswordChangedTemplateName, _emailSettings.NoReplyAccount, receiver); - } - - public async Task SendTemplatedEmailAsync(string templateName, string sender, string receiver, - IDictionary> parameters = null) - { - if (IsSenderDisabled()) - return; - - var template = GetTemplate(templateName); - if (template == null) - return; - - var emailMessage = CreateMessage(receiver, sender, template.Subject); - emailMessage.Html = ""; - emailMessage.EnableTemplateEngine(template.Id); - var templateParameters = GetTemplateParameters(template, parameters); - foreach (var parameter in templateParameters) - { - emailMessage.AddSubstitution($"-{parameter.Key}-", parameter.Value.ToList()); - } - await SendMessageAsync(emailMessage); - Logger.Trace($"Templated email message has been sent -> template: {template.Name}, " + - $"sender: {sender}, receiver: {receiver}"); - } - - private EmailTemplateSettings GetTemplate(string name) - { - var template = _emailSettings.Templates?.FirstOrDefault(x => x.Name.EqualsCaseInvariant(name)); - if (template == null) - Logger.Error($"Email template: {name} has not been found. Message will not be sent."); - - return template; - } - - private static IDictionary> GetTemplateParameters(EmailTemplateSettings template, - IDictionary> parameters) - => (parameters?.Any() == true - ? parameters.ToDictionary(x => x.Key, x => x.Value) - : template.Parameters?.ToDictionary(x => x.Name, x => x.Values.AsEnumerable())) ?? - new Dictionary>(); - - private bool IsSenderDisabled() - { - var cannotSendMessage = !_emailSettings.Enabled; - if (cannotSendMessage) - Logger.Trace("Email sender is disabled. Message will not be sent."); - - return cannotSendMessage; - } - - private SendGridMessage CreateMessage(string receiver, string sender, - string subject, string message = null) - { - var emailMessage = new SendGridMessage(); - emailMessage.AddTo(receiver); - emailMessage.From = new MailAddress(sender); - emailMessage.Subject = subject; - emailMessage.Text = message.Empty() ? " " : message; - - return emailMessage; - } - - private async Task SendMessageAsync(SendGridMessage message) - { - var transportWeb = new SendGrid.Web(_emailSettings.ApiKey); - await transportWeb.DeliverAsync(message); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Services/IEncrypter.cs b/src/Web/Warden.Web.Core/Services/IEncrypter.cs deleted file mode 100644 index 4e4f3c5..0000000 --- a/src/Web/Warden.Web.Core/Services/IEncrypter.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Services -{ - public interface IEncrypter - { - string GetRandomSecureKey(); - string GetSalt(string data); - string GetHash(string data, string salt); - string Encrypt(string text, string salt); - string Decrypt(string text, string salt); - } - - public class Encrypter : IEncrypter - { - private readonly string _key; - private const int DeriveBytesIterationsCount = 10000; - private const int MinSaltSize = 10; - private const int MaxSaltSize = 20; - private const int MinSecureKeySize = 40; - private const int MaxSecureKeySize = 60; - private static readonly Random Random = new Random(); - - public Encrypter(string key) - { - if (key.Empty()) - throw new DomainException("Encrypter key can not be empty."); - - _key = key; - } - - public string GetRandomSecureKey() - { - var size = Random.Next(MinSecureKeySize, MaxSecureKeySize); - var bytes = new byte[size]; - var rng = new RNGCryptoServiceProvider(); - rng.GetNonZeroBytes(bytes); - - return Convert.ToBase64String(bytes); - } - - public string GetSalt(string data) - { - var saltSize = Random.Next(MinSaltSize, MaxSaltSize); - var saltBytes = new byte[saltSize]; - var rng = new RNGCryptoServiceProvider(); - rng.GetNonZeroBytes(saltBytes); - - return Convert.ToBase64String(saltBytes); - } - - public string GetHash(string data, string salt) - { - using (var sha512 = SHA512.Create()) - { - var bytes = Encoding.Unicode.GetBytes(data + salt); - var hash = sha512.ComputeHash(bytes); - - return Convert.ToBase64String(hash); - } - } - - public string Encrypt(string text, string salt) - => Encrypt(text, _key, salt); - - public string Decrypt(string text, string salt) - => Decrypt(text, _key, salt); - - private static string Encrypt(string text, string passwordKey, string salt) where T : SymmetricAlgorithm, new() - { - var transform = GetCryptoTransform(passwordKey, salt); - var buffer = new MemoryStream(); - using (var writer = new StreamWriter(new CryptoStream(buffer, transform, CryptoStreamMode.Write), Encoding.Unicode)) - { - writer.Write(text); - } - - return Convert.ToBase64String(buffer.ToArray()); - } - - private static string Decrypt(string text, string passwordKey, string salt) where T : SymmetricAlgorithm, new() - { - var transform = GetCryptoTransform(passwordKey, salt); - var buffer = new MemoryStream(Convert.FromBase64String(text)); - using (var reader = new StreamReader(new CryptoStream(buffer, transform, CryptoStreamMode.Read), Encoding.Unicode)) - { - return reader.ReadToEnd(); - } - } - - private static ICryptoTransform GetCryptoTransform(string passwordKey, string salt) - where T : SymmetricAlgorithm, new() - { - var rgb = new Rfc2898DeriveBytes(passwordKey, Convert.FromBase64String(salt), DeriveBytesIterationsCount); - var algorithm = new T(); - var rgbKey = rgb.GetBytes(algorithm.KeySize >> 3); - var rgbIv = rgb.GetBytes(algorithm.BlockSize >> 3); - - return algorithm.CreateEncryptor(rgbKey, rgbIv); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Services/IOrganizationService.cs b/src/Web/Warden.Web.Core/Services/IOrganizationService.cs deleted file mode 100644 index 596dd79..0000000 --- a/src/Web/Warden.Web.Core/Services/IOrganizationService.cs +++ /dev/null @@ -1,256 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using NLog; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Extensions; -using Warden.Web.Core.Mongo; -using Warden.Web.Core.Mongo.Queries; -using Warden.Web.Core.Queries; -using Warden.Web.Core.Settings; - -namespace Warden.Web.Core.Services -{ - public interface IOrganizationService - { - Task GetAsync(Guid organizationId); - Task GetAsync(string name, Guid ownerId); - Task GetDefaultAsync(Guid ownerId); - Task CreateDefaultAsync(Guid ownerId); - Task CreateAsync(string name, Guid ownerId, bool autoRegisterNewWarden = true); - Task EditAsync(Guid id, string name); - Task AddWardenAsync(Guid organizationId, string name, bool enabled = true); - Task AddUserAsync(Guid organizationId, string email, OrganizationRole role = OrganizationRole.User); - Task EnableWardenAsync(Guid organizationId, string name); - Task DisableWardenAsync(Guid organizationId, string name); - Task IsUserInOrganizationAsync(Guid organizationId, Guid userId); - Task> BrowseAsync(BrowseOrganizations query); - Task DeleteAsync(Guid organizationId, bool removeAllIterations = true); - Task DeleteUserAsync(Guid organizationId, Guid userId); - Task DeleteWardenAsync(Guid organizationId, Guid wardenId); - Task EnableAutoRegisterNewWardenAsync(Guid organizationId); - Task DisableAutoRegisterNewWardenAsync(Guid organizationId); - } - - public class OrganizationService : IOrganizationService - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private readonly IMongoDatabase _database; - private readonly FeatureSettings _featureSettings; - private const string DefaultName = "My organization"; - - public OrganizationService(IMongoDatabase database, FeatureSettings featureSettings) - { - _database = database; - _featureSettings = featureSettings; - } - - public async Task GetAsync(Guid organizationId) - { - var organization = await _database.Organizations().GetByIdAsync(organizationId); - - return GetOrganizationDto(organization); - } - - public async Task GetDefaultAsync(Guid ownerId) - => await GetAsync(DefaultName, ownerId); - - - public async Task GetAsync(string name, Guid ownerId) - { - var organization = await _database.Organizations().GetByNameForOwnerAsync(name, ownerId); - - return GetOrganizationDto(organization); - } - - private OrganizationDto GetOrganizationDto(Organization organization) - { - return organization == null ? null : new OrganizationDto(organization); - } - - public async Task> BrowseAsync(BrowseOrganizations query) - { - if (query == null) - return PagedResult.Empty; - - var organizations = await _database.Organizations() - .Query(query) - .OrderBy(x => x.Name) - .PaginateAsync(query); - - return PagedResult.From(organizations, - organizations.Items.Select(x => new OrganizationDto(x))); - } - - public async Task CreateDefaultAsync(Guid ownerId) - { - await CreateAsync(DefaultName, ownerId); - } - - public async Task CreateAsync(string name, Guid ownerId, bool autoRegisterNewWarden = true) - { - if (name.Empty()) - throw new ServiceException("Organization name can not be empty."); - - var owner = await _database.Users().GetByIdAsync(ownerId); - if (owner == null) - throw new ServiceException($"User has not been found for given id: '{ownerId}'."); - - var organization = await _database.Organizations().GetByNameForOwnerAsync(name, ownerId); - if (organization != null) - { - throw new ServiceException($"There's already an organization with name: '{name}' " + - $"for owner with id: '{ownerId}'."); - } - - var existingOrganizationsCount = await _database.Organizations().CountAsync(x => x.OwnerId == ownerId); - if (existingOrganizationsCount >= _featureSettings.MaxOrganizations) - { - throw new ServiceException($"Limit of {_featureSettings.MaxOrganizations} " + - "organizations has been reached."); - } - - organization = new Organization(name, owner, autoRegisterNewWarden); - await _database.Organizations().InsertOneAsync(organization); - Logger.Info($"New organization: '{name}' with id: '{organization}' " + - $"was created by user: '{ownerId}'."); - } - - public async Task EditAsync(Guid id, string name) - { - var organization = await GetByIdOrFailAsync(id); - var ownerId = organization.OwnerId; - var existingOrganization = await _database.Organizations().GetByNameForOwnerAsync(name, ownerId); - if(existingOrganization != null && existingOrganization.Id != organization.Id) - { - throw new ServiceException($"There's already an organization with name: '{name}' " + - $"for owner with id: '{ownerId}'."); - } - - organization.SetName(name); - await _database.Organizations().ReplaceOneAsync(x => x.Id == id, organization); - } - - public async Task AddWardenAsync(Guid organizationId, string name, bool enabled = true) - { - var organization = await GetByIdOrFailAsync(organizationId); - if (organization.Wardens.Count() >= _featureSettings.MaxWardensInOrganization) - { - throw new ServiceException($"Limit of {_featureSettings.MaxWardensInOrganization} " + - "wardens in organization has been reached."); - } - - organization.AddWarden(name, enabled); - await _database.Organizations().ReplaceOneAsync(x => x.Id == organization.Id, organization); - Logger.Info($"Warden '{name}' was added to organization: " + - $"'{organization.Name}' with id: '{organization.Id}'."); - } - - public async Task AddUserAsync(Guid organizationId, string email, OrganizationRole role = OrganizationRole.User) - { - var organization = await GetByIdOrFailAsync(organizationId); - var user = await _database.Users().GetByEmailAsync(email); - if (user == null) - throw new ServiceException($"User has not been found for email: '{email}'."); - - if (organization.Users.Count() >= _featureSettings.MaxUsersInOrganization) - { - throw new ServiceException($"Limit of {_featureSettings.MaxUsersInOrganization} " + - "users in organization has been reached."); - } - - organization.AddUser(user, role); - await _database.Organizations().ReplaceOneAsync(x => x.Id == organization.Id, organization); - Logger.Info($"User '{user.Id}' was added to organization: " + - $"'{organization.Name}' with id: '{organization.Id}'."); - } - - public async Task EnableWardenAsync(Guid organizationId, string name) - { - var organization = await GetByIdOrFailAsync(organizationId); - var warden = organization.GetWardenByNameOrFail(name); - warden.Enable(); - await _database.Organizations().ReplaceOneAsync(x => x.Id == organization.Id, organization); - Logger.Info($"Warden '{name}' was enabled in organization: " + - $"'{organization.Name}' with id: '{organization.Id}'."); - } - - public async Task DisableWardenAsync(Guid organizationId, string name) - { - var organization = await GetByIdOrFailAsync(organizationId); - var warden = organization.GetWardenByNameOrFail(name); - warden.Disable(); - await _database.Organizations().ReplaceOneAsync(x => x.Id == organization.Id, organization); - Logger.Info($"Warden '{name}' was disabled in organization: " + - $"'{organization.Name}' with id: '{organization.Id}'."); - } - - public async Task IsUserInOrganizationAsync(Guid organizationId, Guid userId) - { - var organization = await GetByIdOrFailAsync(organizationId); - - return organization.Users.Any(x => x.Id == userId); - } - - public async Task DeleteAsync(Guid organizationId, bool removeAllIterations = true) - { - var organization = await GetByIdOrFailAsync(organizationId); - await _database.Organizations().DeleteOneAsync(x => x.Id == organizationId); - if (!removeAllIterations) - return; - - await _database.WardenIterations().DeleteManyAsync(x => x.Warden.OrganizationId == organizationId); - } - - public async Task DeleteUserAsync(Guid organizationId, Guid userId) - { - var organization = await GetByIdOrFailAsync(organizationId); - organization.RemoveUser(userId); - await _database.Organizations().ReplaceOneAsync(x => x.Id == organizationId, organization); - Logger.Info($"Organization: '{organization.Name}' with id: '{organization.Id}' was deleted."); - } - - public async Task DeleteWardenAsync(Guid organizationId, Guid wardenId) - { - var organization = await GetByIdOrFailAsync(organizationId); - var warden = organization.Wardens.FirstOrDefault(x => x.Id == wardenId); - if (warden == null) - throw new ServiceException($"Warden has not been found for id: '{wardenId}'."); - - organization.RemoveWarden(warden.Name); - await _database.Organizations().ReplaceOneAsync(x => x.Id == organizationId, organization); - Logger.Info($"Warden '{warden.Name}' was deleted from organization: " + - $"'{organization.Name}' with id: '{organization.Id}'."); - } - - public async Task EnableAutoRegisterNewWardenAsync(Guid organizationId) - { - var organization = await GetByIdOrFailAsync(organizationId); - organization.EnableAutoRegisterNewWarden(); - await _database.Organizations().ReplaceOneAsync(x => x.Id == organizationId, organization); - Logger.Info("Automatic registration of new Wardens was enabled in organization: " + - $"'{organization.Name}' with id: '{organization.Id}'"); - } - - public async Task DisableAutoRegisterNewWardenAsync(Guid organizationId) - { - var organization = await GetByIdOrFailAsync(organizationId); - organization.DisableAutoRegisterNewWarden(); - await _database.Organizations().ReplaceOneAsync(x => x.Id == organizationId, organization); - Logger.Info("Automatic registration of new Wardens was disabled in organization: " + - $"'{organization.Name}' with id: '{organization.Id}'"); - } - - private async Task GetByIdOrFailAsync(Guid id) - { - var organization = await _database.Organizations().GetByIdAsync(id); - if (organization == null) - throw new ServiceException($"Organization has not been found for given id: '{id}'."); - - return organization; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Services/ISignalRService.cs b/src/Web/Warden.Web.Core/Services/ISignalRService.cs deleted file mode 100644 index 160a02c..0000000 --- a/src/Web/Warden.Web.Core/Services/ISignalRService.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using Microsoft.AspNet.SignalR; -using NLog; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Core.Services -{ - public interface ISignalRService - { - void SendIterationCreated(Guid organizationId, WardenIterationDto iteration); - } - - public class SignalRService : ISignalRService - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private readonly IHubContext _hub; - - public SignalRService(IHubContext hub) - { - _hub = hub; - } - - public void SendIterationCreated(Guid organizationId, WardenIterationDto iteration) - { - var groupName = GetWardenGroupName(organizationId, iteration.WardenName); - _hub.Clients.Group(groupName).iterationCreated(iteration); - } - - private static string GetWardenGroupName(Guid organizationId, string wardenName) - => $"{organizationId}::{wardenName}".TrimToLower(); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Services/IStatsCalculator.cs b/src/Web/Warden.Web.Core/Services/IStatsCalculator.cs deleted file mode 100644 index 7f69541..0000000 --- a/src/Web/Warden.Web.Core/Services/IStatsCalculator.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Dto; - -namespace Warden.Web.Core.Services -{ - public interface IStatsCalculator - { - StatsDto Calculate(IEnumerable values) where T : IValidatable; - } - - public class StatsCalculator : IStatsCalculator - { - public StatsDto Calculate(IEnumerable values) where T : IValidatable - { - var results = values?.ToList() ?? new List(); - if (!results.Any()) - return new StatsDto(); - - var totalResults = (double)results.Count; - var totalValidResults = (double)results.Count(r => r.IsValid); - var totalInvalidResults = totalResults - totalValidResults; - var totalUptime = totalValidResults * 100 / totalResults; - var totalDowntime = totalInvalidResults * 100 / totalResults; - - return new StatsDto - { - TotalUptime = totalUptime, - TotalDowntime = totalDowntime, - TotalResults = totalResults, - TotalValidResults = totalValidResults, - TotalInvalidResults = totalInvalidResults, - }; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Services/IUserService.cs b/src/Web/Warden.Web.Core/Services/IUserService.cs deleted file mode 100644 index 9d57b5d..0000000 --- a/src/Web/Warden.Web.Core/Services/IUserService.cs +++ /dev/null @@ -1,203 +0,0 @@ -using System; -using System.Threading.Tasks; -using MongoDB.Driver; -using System.Linq; -using NLog; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Extensions; -using Warden.Web.Core.Factories; -using Warden.Web.Core.Mongo.Queries; -using Warden.Web.Core.Settings; - -namespace Warden.Web.Core.Services -{ - public interface IUserService - { - Task GetAsync(string email); - Task GetAsync(Guid id); - Task IsActiveAsync(Guid id); - Task RegisterAsync(string email, string password, Role role = Role.User); - - Task LoginAsync(string email, string password, string ipAddress, - string userAgent = null, string referrer = null); - - Task SetRecentlyViewedWardenInOrganizationAsync(Guid userId, Guid organizationId, Guid wardenId); - Task SetNewPasswordAsync(Guid userId, string actualPassword, string newPassword); - Task InitiatePasswordResetAsync(string email, string ipAddress = null, string userAgent = null); - Task ValidatePasswordResetTokenAsync(string email, string token); - - Task CompletePasswordResetAsync(string email, string token, string password, - string ipAddress = null, string userAgent = null); - } - - public class UserService : IUserService - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private readonly IMongoDatabase _database; - private readonly IEncrypter _encrypter; - private readonly IEmailSender _emailSender; - private readonly ISecuredOperationFactory _securedOperationFactory; - private readonly AccountSettings _accountSettings; - - public UserService(IMongoDatabase database, IEncrypter encrypter, - IEmailSender emailSender, ISecuredOperationFactory securedOperationFactory, - AccountSettings accountSettings) - { - _database = database; - _encrypter = encrypter; - _emailSender = emailSender; - _securedOperationFactory = securedOperationFactory; - _accountSettings = accountSettings; - } - - public async Task GetAsync(string email) - { - var user = await _database.Users().GetByEmailAsync(email); - - return await GetUserWithApiKeysAsync(user); - } - - public async Task GetAsync(Guid id) - { - var user = await _database.Users().GetByIdAsync(id); - - return await GetUserWithApiKeysAsync(user); - } - - public async Task IsActiveAsync(Guid id) => await _database.Users().IsActiveAsync(id); - - private async Task GetUserWithApiKeysAsync(User user) - { - if (user == null) - return null; - - var apiKeys = await _database.ApiKeys().GetAllForUserAsync(user.Id); - - return new UserDto(user) - { - ApiKeys = apiKeys.Select(x => x.Key) - }; - } - - public async Task RegisterAsync(string email, string password, Role role = Role.User) - { - if(!email.IsEmail()) - throw new ServiceException($"Invalid email: '{email}'."); - if (password.Empty()) - throw new ServiceException("Password can not be empty."); - - var userExists = await _database.Users().ExistsAsync(email); - if(userExists) - throw new ServiceException($"User with email: '{email}' is already registered."); - - var user = new User(email, password, _encrypter, role); - if(_accountSettings.AutoActivation) - user.Activate(); - - await _database.Users().InsertOneAsync(user); - Logger.Info($"New user account: '{email}' was created with id: '{user.Id}'"); - await _emailSender.SendAccountCreatedEmailAsync(email); - } - - public async Task LoginAsync(string email, string password, string ipAddress, - string userAgent = null, string referrer = null) - { - if (!email.IsEmail()) - throw new ServiceException($"Invalid email: '{email}."); - if (password.Empty()) - throw new ServiceException("Password can not be empty."); - - var user = await _database.Users().GetByEmailAsync(email); - if (user == null) - throw new ServiceException($"User has not been found for email: '{email}'."); - if (user.State == State.Inactive) - throw new ServiceException("User account has not been activated."); - if (user.State == State.Locked) - throw new ServiceException("User account has been locked."); - if (user.State == State.Deleted) - throw new ServiceException("User account has been deleted."); - - if (!user.ValidatePassword(password, _encrypter)) - throw new ServiceException("Invalid credentials."); - - var session = new UserSession(user, userAgent, ipAddress, referrer); - await _database.UserSessions().InsertOneAsync(session); - Logger.Info($"New user session: '{session.Id}' was created " + - $"for user: '{user.Email}' with id: '{user.Id}'."); - } - - public async Task SetRecentlyViewedWardenInOrganizationAsync(Guid userId, Guid organizationId, Guid wardenId) - { - var user = await _database.Users().GetByIdAsync(userId); - var organization = await _database.Organizations().GetByIdAsync(organizationId); - user.SetRecentlyViewedWardenInOrganization(organization, wardenId); - await _database.Users().ReplaceOneAsync(x => x.Id == userId, user); - } - - public async Task SetNewPasswordAsync(Guid userId, string actualPassword, string newPassword) - { - var user = await _database.Users().GetByIdAsync(userId); - if (user == null) - throw new ServiceException($"User has not been found for id: '{userId}'."); - - if (!user.ValidatePassword(actualPassword, _encrypter)) - throw new ServiceException("Invalid actual password."); - - user.SetPassword(newPassword, _encrypter); - await _database.Users().ReplaceOneAsync(x => x.Id == userId, user); - Logger.Info($"User: '{user.Email}' with: '{user.Id}' has changed password."); - } - - public async Task InitiatePasswordResetAsync(string email, string ipAddress = null, string userAgent = null) - { - var user = await _database.Users().GetByEmailAsync(email); - if (user == null) - throw new ServiceException($"User has not been found for email: '{email}'."); - - var securedOperation = _securedOperationFactory.Create(SecuredOperationType.ResetPassword, - DateTime.UtcNow.AddDays(1), user.Id, email, ipAddress, userAgent); - - await _database.SecuredOperations().InsertOneAsync(securedOperation); - await _emailSender.SendResetPasswordEmailAsync(email, securedOperation.Token); - Logger.Info($"User '{user.Email}' [id: '{user.Id}'] has initiated password reset."); - } - - public async Task ValidatePasswordResetTokenAsync(string email, string token) - { - var user = await _database.Users().GetByEmailAsync(email); - if (user == null) - throw new ServiceException($"User has not been found for email: '{email}'."); - - var securedOperation = await _database.SecuredOperations() - .GetByUserIdAndTokenAsync(user.Id, token); - if (securedOperation == null) - throw new ServiceException("Invalid token."); - - securedOperation.CheckIfCanBeConsumedOrFail(); - } - - public async Task CompletePasswordResetAsync(string email, string token, string password, string ipAddress = null, - string userAgent = null) - { - var user = await _database.Users().GetByEmailAsync(email); - if (user == null) - throw new ServiceException($"User has not been found for email: '{email}'."); - - var securedOperation = await _database.SecuredOperations() - .GetByUserIdAndTokenAsync(user.Id, token); - - if (securedOperation == null) - throw new ServiceException("Invalid token."); - - user.SetPassword(password, _encrypter); - securedOperation.Consume(ipAddress, userAgent); - - await _database.Users().ReplaceOneAsync(x => x.Id == user.Id, user); - await _database.SecuredOperations().ReplaceOneAsync(x => x.Id == securedOperation.Id, securedOperation); - await _emailSender.SendPasswordChangedEmailAsync(email); - - Logger.Info($"User '{user.Email}' [id: '{user.Id}'] has completed password reset."); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Services/IWardenService.cs b/src/Web/Warden.Web.Core/Services/IWardenService.cs deleted file mode 100644 index 8e397f1..0000000 --- a/src/Web/Warden.Web.Core/Services/IWardenService.cs +++ /dev/null @@ -1,228 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Queries; -using MongoDB.Driver; -using System.Linq; -using NLog; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Mongo; -using Warden.Web.Core.Mongo.Queries; -using Warden.Web.Core.Settings; - -namespace Warden.Web.Core.Services -{ - public interface IWardenService - { - Task SaveIterationAsync(WardenIterationDto iteration, Guid organizationId); - Task> BrowseIterationsAsync(BrowseWardenIterations query); - Task GetIterationAsync(Guid id); - Task GetStatsAsync(GetWardenStats query); - Task EditAsync(Guid organizationId, Guid wardenId, string name); - } - - public class WardenService : IWardenService - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private const string WatcherNameSuffix = "watcher"; - private readonly IMongoDatabase _database; - private readonly IStatsCalculator _statsCalculator; - private readonly FeatureSettings _featureSettings; - - public WardenService(IMongoDatabase database, IStatsCalculator statsCalculator, FeatureSettings featureSettings) - { - _database = database; - _statsCalculator = statsCalculator; - _featureSettings = featureSettings; - } - - public async Task SaveIterationAsync(WardenIterationDto iteration, Guid organizationId) - { - if (iteration == null) - return null; - - var wardenCheckResults = (iteration.Results ?? Enumerable.Empty()).ToList(); - var watcherCheckResults = wardenCheckResults.Select(x => x.WatcherCheckResult).ToList(); - watcherCheckResults.ForEach(SetWatcherTypeFromFullNamespace); - - var organization = await _database.Organizations().GetByIdAsync(organizationId); - if (organization == null) - throw new ServiceException($"Organization has not been found for given id: '{organizationId}'."); - - var warden = organization.GetWardenByName(iteration.WardenName); - if (warden == null && !organization.AutoRegisterNewWarden) - throw new ServiceException($"Warden with name: '{iteration.WardenName}' has not been registered."); - - var updateOrganization = false; - if (warden == null) - { - if (organization.Wardens.Count() >= _featureSettings.MaxWardensInOrganization) - { - throw new ServiceException($"Limit of {_featureSettings.MaxWardensInOrganization} " + - "wardens in organization has been reached."); - } - - updateOrganization = true; - organization.AddWarden(iteration.WardenName); - warden = organization.GetWardenByName(iteration.WardenName); - } - else if(!warden.Enabled) - throw new ServiceException($"Warden with name: '{iteration.WardenName}' is disabled."); - - var wardenIteration = new WardenIteration(warden.Name, organization, - iteration.Ordinal, iteration.StartedAt, iteration.CompletedAt, iteration.IsValid); - - foreach (var result in wardenCheckResults) - { - WatcherType watcherType; - var watcherName = result.WatcherCheckResult.WatcherName; - if(!Enum.TryParse(result.WatcherCheckResult.WatcherType, true, out watcherType)) - watcherType = WatcherType.Custom; - - var watcher = warden.GetWatcherByName(watcherName); - if (watcher == null) - { - if (warden.Watchers.Count() >= _featureSettings.MaxWatchersInWarden) - { - throw new ServiceException($"Limit of {_featureSettings.MaxWatchersInWarden} " + - "watchers in Warden has been reached."); - } - - updateOrganization = true; - warden.AddWatcher(watcherName, watcherType, result.WatcherCheckResult.WatcherGroup); - watcher = warden.GetWatcherByName(watcherName); - } - - var watcherCheckResult = result.WatcherCheckResult.IsValid - ? WatcherCheckResult.Valid(watcher, result.WatcherCheckResult.Description) - : WatcherCheckResult.Invalid(watcher, result.WatcherCheckResult.Description); - - var checkResult = result.IsValid - ? WardenCheckResult.Valid(watcherCheckResult, result.StartedAt, result.CompletedAt) - : WardenCheckResult.Invalid(watcherCheckResult, result.StartedAt, result.CompletedAt, - CreatExceptionInfo(result.Exception)); - - wardenIteration.AddResult(checkResult); - } - - if (updateOrganization) - await _database.Organizations().ReplaceOneAsync(x => x.Id == organizationId, organization); - - await _database.WardenIterations().InsertOneAsync(wardenIteration); - Logger.Info($"Warden iteration: '{wardenIteration.Id}' was created " + - $"for organization: '{organization.Name}' with id: '{organization.Id}'."); - - return new WardenIterationDto(wardenIteration); - } - - private static void SetWatcherTypeFromFullNamespace(WatcherCheckResultDto watcherCheck) - { - watcherCheck.WatcherType = (string.IsNullOrWhiteSpace(watcherCheck.WatcherType) - ? string.Empty - : watcherCheck.WatcherType.Contains(",") - ? watcherCheck.WatcherType.Split(',').FirstOrDefault()?.Split('.').LastOrDefault() ?? - string.Empty - : watcherCheck.WatcherType).Trim().ToLowerInvariant().Replace(WatcherNameSuffix, string.Empty); - } - - private static ExceptionInfo CreatExceptionInfo(ExceptionDto dto) - { - return dto == null - ? null - : ExceptionInfo.Create(dto.Message, dto.Source, - dto.StackTrace, CreatExceptionInfo(dto.InnerException)); - } - - public async Task> BrowseIterationsAsync(BrowseWardenIterations query) - { - if (query == null) - return PagedResult.Empty; - if (query.OrganizationId == Guid.Empty) - return PagedResult.Empty; - - var iterations = await _database.WardenIterations() - .Query(query) - .PaginateAsync(query); - - return PagedResult.From(iterations, - iterations.Items.Select(x => new WardenIterationDto(x))); - } - - public async Task GetIterationAsync(Guid id) - { - var iteration = await _database.WardenIterations().GetByIdAsync(id); - - return iteration == null ? null : new WardenIterationDto(iteration); - } - - public async Task EditAsync(Guid organizationId, Guid wardenId, string name) - { - var organization = await _database.Organizations().GetByIdAsync(organizationId); - if (organization == null) - throw new ServiceException($"Organization has not been found for given id: '{organizationId}'."); - - var warden = organization.Wardens.FirstOrDefault(x => x.Id == wardenId); - if (warden == null) - throw new ServiceException($"Warden has not been found for given id: '{wardenId}'."); - - organization.EditWarden(warden.Name, name); - await _database.Organizations().ReplaceOneAsync(x => x.Id == organizationId, organization); - } - - public async Task GetStatsAsync(GetWardenStats query) - { - var warden = await _database.Organizations() - .GetWardenByNameAsync(query.OrganizationId, query.WardenName); - if (warden == null) - return new WardenStatsDto(); - - var iterations = await _database.WardenIterations() - .GetForWardenAsync(query.OrganizationId, query.WardenName); - var stats = GetWardenStats(iterations.ToList()); - stats.OrganizationId = query.OrganizationId; - stats.WardenName = warden.Name; - stats.Enabled = warden.Enabled; - - Logger.Trace($"Statistics for for Warden: '{warden.Name}' with id: '{warden.Id}' " + - $"in organization: '{query.OrganizationId}' were created."); - - return stats; - } - - private WardenStatsDto GetWardenStats(IList iterations) - { - var wardenStats = _statsCalculator.Calculate(iterations); - var stats = new WardenStatsDto - { - TotalUptime = wardenStats.TotalUptime, - TotalDowntime = wardenStats.TotalDowntime, - TotalIterations = wardenStats.TotalResults, - TotalValidIterations = wardenStats.TotalValidResults, - TotalInvalidIterations = wardenStats.TotalInvalidResults - }; - - var watcherCheckResults = iterations.SelectMany(x => x.Results) - .Select(x => x.WatcherCheckResult) - .GroupBy(x => x.Watcher.Name, x => x) - .ToList(); - - stats.Watchers = (from watcherGroup in watcherCheckResults - let watcher = watcherGroup.First().Watcher - let watcherStats = _statsCalculator.Calculate(watcherGroup) - select new WatcherStatsDto - { - Name = watcher.Name, - Type = watcher.Type.ToString().ToLowerInvariant(), - TotalUptime = watcherStats.TotalUptime, - TotalDowntime = watcherStats.TotalDowntime, - TotalChecks = watcherStats.TotalResults, - TotalValidChecks = watcherStats.TotalValidResults, - TotalInvalidChecks = watcherStats.TotalInvalidResults, - }) - .OrderBy(x => x.Type); - - return stats; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Services/IWatcherService.cs b/src/Web/Warden.Web.Core/Services/IWatcherService.cs deleted file mode 100644 index 026104b..0000000 --- a/src/Web/Warden.Web.Core/Services/IWatcherService.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using MongoDB.Driver; -using NLog; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Extensions; -using Warden.Web.Core.Mongo; -using Warden.Web.Core.Mongo.Queries; -using Warden.Web.Core.Queries; - -namespace Warden.Web.Core.Services -{ - public interface IWatcherService - { - Task> GetAllAsync(Guid organizationId, Guid wardenId); - Task GetAsync(Guid organizationId, Guid wardenId, string name); - Task GetStatsAsync(GetWatcherStats query); - Task> BrowseChecksAsync(BrowseWardenCheckResults query); - } - - public class WatcherService : IWatcherService - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private readonly IMongoDatabase _database; - private readonly IStatsCalculator _statsCalculator; - - public WatcherService(IMongoDatabase database, IStatsCalculator statsCalculator) - { - _database = database; - _statsCalculator = statsCalculator; - } - - public async Task> GetAllAsync(Guid organizationId, Guid wardenId) - { - if (organizationId == Guid.Empty || wardenId == Guid.Empty) - return Enumerable.Empty(); - - var warden = await _database.Organizations().GetWardenByIdAsync(organizationId, wardenId); - if (warden == null) - throw new ServiceException($"Warden has not been found for given id: '{wardenId}'."); - - return warden.Watchers.Select(x => new WatcherDto(x)); - } - - public async Task GetAsync(Guid organizationId, Guid wardenId, string name) - { - var warden = await _database.Organizations().GetWardenByIdAsync(organizationId, wardenId); - var watcher = warden?.GetWatcherByName(name); - - return watcher == null ? null : new WatcherDto(watcher); - } - - public async Task GetStatsAsync(GetWatcherStats query) - { - var watcher = await GetAsync(query.OrganizationId, query.WardenId, query.WatcherName); - if (watcher == null) - return null; - - var iterations = await _database.WardenIterations() - .GetForWatcherAsync(query.OrganizationId, query.WardenId, query.WatcherName); - var results = iterations.SelectMany(x => x.Results) - .Select(x => x.WatcherCheckResult) - .Where(x => x.Watcher.Name.EqualsCaseInvariant(query.WatcherName)) - .ToList(); - var stats = _statsCalculator.Calculate(results); - Logger.Trace($"Statistics for watcher {watcher.Name} for Warden: '{query.WardenId}' " + - $"in organization: '{query.OrganizationId}' were created."); - - return new WatcherStatsDto - { - Name = watcher.Name, - Type = watcher.Type, - TotalUptime = stats.TotalUptime, - TotalDowntime = stats.TotalDowntime, - TotalChecks = stats.TotalResults, - TotalValidChecks = stats.TotalValidResults, - TotalInvalidChecks = stats.TotalInvalidResults - }; - } - - public async Task> BrowseChecksAsync(BrowseWardenCheckResults query) - { - var iterations = await _database.WardenIterations().Query(new BrowseWardenIterations - { - OrganizationId = query.OrganizationId, - WardenName = query.WardenName, - WatcherName = query.WatcherName, - Page = query.Page, - Results = query.Results - }).PaginateAsync(query); - - var checkResults = new List(); - foreach (var iteration in iterations.Items) - { - var checks = iteration.Results.Where(r => - r.WatcherCheckResult.Watcher.Name.EqualsCaseInvariant(query.WatcherName)) - .Select(x => new WardenCheckResultDto(x) - { - IterationId = iteration.Id - }); - checkResults.AddRange(checks); - } - - return PagedResult.From(iterations, checkResults); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Settings/AccountSettings.cs b/src/Web/Warden.Web.Core/Settings/AccountSettings.cs deleted file mode 100644 index 3c5bb81..0000000 --- a/src/Web/Warden.Web.Core/Settings/AccountSettings.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Warden.Web.Core.Settings -{ - public class AccountSettings - { - public bool AutoActivation { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Settings/EmailSettings.cs b/src/Web/Warden.Web.Core/Settings/EmailSettings.cs deleted file mode 100644 index 224143e..0000000 --- a/src/Web/Warden.Web.Core/Settings/EmailSettings.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections.Generic; - -namespace Warden.Web.Core.Settings -{ - public class EmailSettings - { - public bool Enabled { get; set; } - public string ApiKey { get; set; } - public string NoReplyAccount { get; set; } - public List Templates { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Settings/EmailTemplateParameterSettings.cs b/src/Web/Warden.Web.Core/Settings/EmailTemplateParameterSettings.cs deleted file mode 100644 index be566a8..0000000 --- a/src/Web/Warden.Web.Core/Settings/EmailTemplateParameterSettings.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; - -namespace Warden.Web.Core.Settings -{ - public class EmailTemplateParameterSettings - { - public string Name { get; set; } - public List Values { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Settings/EmailTemplateSettings.cs b/src/Web/Warden.Web.Core/Settings/EmailTemplateSettings.cs deleted file mode 100644 index 13a3af1..0000000 --- a/src/Web/Warden.Web.Core/Settings/EmailTemplateSettings.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections.Generic; - -namespace Warden.Web.Core.Settings -{ - public class EmailTemplateSettings - { - public string Id { get; set; } - public string Name { get; set; } - public string Subject { get; set; } - public List Parameters { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Settings/FeatureSettings.cs b/src/Web/Warden.Web.Core/Settings/FeatureSettings.cs deleted file mode 100644 index 527212c..0000000 --- a/src/Web/Warden.Web.Core/Settings/FeatureSettings.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Warden.Web.Core.Settings -{ - public class FeatureSettings - { - public int MaxApiKeys { get; set; } - public int MaxOrganizations { get; set; } - public int MaxUsersInOrganization { get; set; } - public int MaxWardensInOrganization { get; set; } - public int MaxWatchersInWarden { get; set; } - public int RetainWardenIterationDataDays { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web.Core/Warden.Web.Core.csproj b/src/Web/Warden.Web.Core/Warden.Web.Core.csproj deleted file mode 100644 index c36096c..0000000 --- a/src/Web/Warden.Web.Core/Warden.Web.Core.csproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - Warden.Web.Core library - 1.3.1 - Piotr Gankiewicz - net461 - Warden.Web.Core - Warden.Web.Core - 1.6.0 - false - false - false - false - false - false - - - - - - - - - - - - - - - - - diff --git a/src/Web/Warden.Web/.bowerrc b/src/Web/Warden.Web/.bowerrc deleted file mode 100644 index 5e90076..0000000 --- a/src/Web/Warden.Web/.bowerrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "directory": "wwwroot/content/lib" -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Api/ApiController.cs b/src/Web/Warden.Web/Api/ApiController.cs deleted file mode 100644 index d57dcc4..0000000 --- a/src/Web/Warden.Web/Api/ApiController.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Warden.Web.Core.Extensions; -using Warden.Web.Core.Services; - -namespace Warden.Web.Api -{ - public abstract class ApiController : Controller - { - protected readonly IApiKeyService ApiKeyService; - protected readonly IUserService UserService; - protected Guid UserId { get; private set; } - - protected ApiController(IApiKeyService apiKeyService, IUserService userService) - { - ApiKeyService = apiKeyService; - UserService = userService; - } - - //Improve performance e.g. by storing API keys in cache - public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) - { - var apiKeyHeader = context.HttpContext.Request.Headers.FirstOrDefault(x => x.Key == "X-Api-Key"); - if (apiKeyHeader.Key.Empty()) - { - context.HttpContext.Response.StatusCode = 401; - return; - } - var apiKey = await ApiKeyService.GetAsync(apiKeyHeader.Value); - if (apiKey == null) - { - context.HttpContext.Response.StatusCode = 401; - return; - } - var isActive = await UserService.IsActiveAsync(apiKey.UserId); - if (!isActive) - { - context.HttpContext.Response.StatusCode = 401; - return; - } - - UserId = apiKey.UserId; - await next(); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Api/OrganizationController.cs b/src/Web/Warden.Web/Api/OrganizationController.cs deleted file mode 100644 index 73421ec..0000000 --- a/src/Web/Warden.Web/Api/OrganizationController.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Queries; -using Warden.Web.Core.Services; - -namespace Warden.Web.Api -{ - [Route("api/organizations")] - public class OrganizationController : ApiController - { - private readonly IOrganizationService _organizationService; - - public OrganizationController(IOrganizationService organizationService, - IApiKeyService apiKeyService, - IUserService userService) - : base(apiKeyService, userService) - { - _organizationService = organizationService; - } - - [HttpGet] - [Route("")] - public async Task> GetAll() - { - var organizations = await _organizationService.BrowseAsync(new BrowseOrganizations - { - UserId = UserId - }); - - return organizations.Items; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Api/WardenController.cs b/src/Web/Warden.Web/Api/WardenController.cs deleted file mode 100644 index ea3c9d8..0000000 --- a/src/Web/Warden.Web/Api/WardenController.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Threading.Tasks; -using System.Web.Http; -using Microsoft.AspNetCore.Mvc; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Queries; -using Warden.Web.Core.Services; - -namespace Warden.Web.Api -{ - [Route("api/organizations/{organizationId}/wardens/")] - public class WardenController : ApiController - { - private readonly IWardenService _wardenService; - private readonly IOrganizationService _organizationService; - - public WardenController(IWardenService wardenService, - IOrganizationService organizationService, - IApiKeyService apiKeyService, - IUserService userService) - : base(apiKeyService, userService) - { - _wardenService = wardenService; - _organizationService = organizationService; - } - - [HttpGet] - [Route("{wardenName}/stats")] - public async Task GetStats(Guid organizationId, string wardenName, [FromUri] GetWardenStats query) - { - var isAuthorized = await _organizationService.IsUserInOrganizationAsync(organizationId, UserId); - if (!isAuthorized) - { - Response.StatusCode = 401; - - return null; - } - - var stats = await _wardenService.GetStatsAsync(query); - - return stats; - } - } -} diff --git a/src/Web/Warden.Web/Api/WardenIterationController.cs b/src/Web/Warden.Web/Api/WardenIterationController.cs deleted file mode 100644 index be98136..0000000 --- a/src/Web/Warden.Web/Api/WardenIterationController.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Web.Http; -using Microsoft.AspNetCore.Mvc; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Queries; -using Warden.Web.Core.Services; - -namespace Warden.Web.Api -{ - [Route("api/organizations/{organizationId}/wardens/{wardenName}/iterations")] - public class WardenIterationController : ApiController - { - private readonly IWardenService _wardenService; - private readonly IOrganizationService _organizationService; - private readonly ISignalRService _signalRService; - - public WardenIterationController(IWardenService wardenService, - IOrganizationService organizationService, - IApiKeyService apiKeyService, - IUserService userService, - ISignalRService signalRService) - : base(apiKeyService, userService) - { - _wardenService = wardenService; - _organizationService = organizationService; - _signalRService = signalRService; - } - - [HttpPost] - public async Task Create(Guid organizationId, string wardenName, [FromBody] WardenIterationDto iteration) - { - var isAuthorized = await _organizationService.IsUserInOrganizationAsync(organizationId, UserId); - if (!isAuthorized) - return Unauthorized(); - - var createdIteration = await _wardenService.SaveIterationAsync(iteration, organizationId); - _signalRService.SendIterationCreated(organizationId, createdIteration); - - return new StatusCodeResult(204); - } - - [HttpGet] - public async Task> GetAll(Guid organizationId, string wardenName, [FromUri] BrowseWardenIterations query) - { - var isAuthorized = await _organizationService.IsUserInOrganizationAsync(organizationId, UserId); - if (!isAuthorized) - { - Response.StatusCode = 401; - - return null; - } - - var iterations = await _wardenService.BrowseIterationsAsync(query); - - return iterations.Items; - } - } -} diff --git a/src/Web/Warden.Web/Bower.json b/src/Web/Warden.Web/Bower.json deleted file mode 100644 index cc18edc..0000000 --- a/src/Web/Warden.Web/Bower.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "Warden.Web", - "private": true, - "dependencies": { - "jquery": "^2.2.3", - "jquery-validation": "^1.15.0", - "jquery-validation-unobtrusive": "^3.2.6", - "materialize": "^0.97.6", - "knockout": "^3.4.0", - "signalr": "^2.2.0", - "Chart.js": "1.3.1" - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Controllers/AccountController.cs b/src/Web/Warden.Web/Controllers/AccountController.cs deleted file mode 100644 index 8c18951..0000000 --- a/src/Web/Warden.Web/Controllers/AccountController.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.Security.Claims; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http.Authentication; -using Microsoft.AspNetCore.Mvc; -using NLog; -using Warden.Web.Core.Services; -using Warden.Web.Extensions; -using Warden.Web.Framework; -using Warden.Web.Framework.Filters; -using Warden.Web.ViewModels; - -namespace Warden.Web.Controllers -{ - public class AccountController : ControllerBase - { - private readonly IUserService _userService; - private readonly IOrganizationService _organizationService; - private readonly IApiKeyService _apiKeyService; - - public AccountController(IUserService userService, - IOrganizationService organizationService, - IApiKeyService apiKeyService) - { - _userService = userService; - _organizationService = organizationService; - _apiKeyService = apiKeyService; - } - - [HttpGet] - [AllowAnonymous] - [Route("login")] - [ImportModelStateFromTempData] - public IActionResult Login() - { - Logger.Log(LogLevel.Error, "in login"); - return View(); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [ExportModelStateToTempData] - [AllowAnonymous] - [Route("login")] - public async Task Login(LoginViewModel viewModel) - { - if (!ModelState.IsValid) - { - Notify(FlashNotificationType.Error, "Invalid credentials."); - - return RedirectToAction("Login"); - } - - var ipAddress = Request.HttpContext?.Connection?.RemoteIpAddress?.ToString(); - var userAgent = Request.Headers["User-Agent"]; - - return await _userService.LoginAsync(viewModel.Email, - viewModel.Password, ipAddress, userAgent) - .ExecuteAsync( - onSuccess: async () => - { - var user = await _userService.GetAsync(viewModel.Email); - var claims = new[] - {new Claim(ClaimTypes.Name, user.Id.ToString("N")), new Claim(ClaimTypes.NameIdentifier, ""),}; - var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); - await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, - new ClaimsPrincipal(identity), new AuthenticationProperties - { - IsPersistent = viewModel.RememberMe - }); - - return RedirectToAction("Index", "Home"); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - - return RedirectToAction("Login"); - }); - } - - [HttpGet] - [AllowAnonymous] - [Route("register")] - [ImportModelStateFromTempData] - public IActionResult Register() - { - return View(); - } - - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - [ExportModelStateToTempData] - [Route("register")] - public async Task Register(RegisterViewModel viewModel) - { - if (!ModelState.IsValid) - { - Notify(FlashNotificationType.Error, "Invalid credentials."); - - return RedirectToAction("Register"); - } - - return await _userService.RegisterAsync(viewModel.Email, viewModel.Password) - .ExecuteAsync( - onSuccess: async () => - { - Notify(FlashNotificationType.Success, "Your account has been created."); - try - { - var user = await _userService.GetAsync(viewModel.Email); - await _apiKeyService.CreateAsync(viewModel.Email); - await _organizationService.CreateDefaultAsync(user.Id); - } - catch (Exception exception) - { - //Not important - Logger.Error(exception); - } - - return RedirectToAction("Login"); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Register"); - }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [Route("logout")] - public async Task Logout() - { - Logger.Info($"User '{UserId}' has logged out."); - await HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); - Notify(FlashNotificationType.Info, "You have been logged out."); - - return RedirectToAction("Index", "Home"); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Controllers/ControllerBase.cs b/src/Web/Warden.Web/Controllers/ControllerBase.cs deleted file mode 100644 index f44e39e..0000000 --- a/src/Web/Warden.Web/Controllers/ControllerBase.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using NLog; -using Warden.Web.Core.Extensions; -using Warden.Web.Framework; - -namespace Warden.Web.Controllers -{ - [Authorize] - public abstract class ControllerBase : Controller - { - private const string NotificationKey = "Notifications"; - protected static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - - protected Guid UserId - => HttpContext.User.Identity.IsAuthenticated ? Guid.Parse(HttpContext.User.Identity.Name) : Guid.Empty; - - protected void Notify(FlashNotificationType type, string message, params object[] args) - { - var notifications = FetchTempData>>(NotificationKey) ?? - new List>(); - notifications.Add(new KeyValuePair(type, string.Format(message, args))); - TempData[NotificationKey] = notifications.ToJson(); - } - - protected T FetchTempData(string key) - { - var result = default(T); - var data = TempData[key]; - if (data == null) - return result; - - try - { - result = (T)Convert.ChangeType(data, typeof(T)); - } - catch (Exception) - { - // ignored - } - - return result; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Controllers/DashboardController.cs b/src/Web/Warden.Web/Controllers/DashboardController.cs deleted file mode 100644 index 68a9b8f..0000000 --- a/src/Web/Warden.Web/Controllers/DashboardController.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Warden.Web.Core.Services; -using Warden.Web.ViewModels; - -namespace Warden.Web.Controllers -{ - [Route("dashboards")] - public class DashboardController : ControllerBase - { - private readonly IOrganizationService _organizationService; - private readonly IUserService _userService; - - public DashboardController(IOrganizationService organizationService, - IUserService userService) - { - _organizationService = organizationService; - _userService = userService; - } - - [HttpGet] - [Route("unavailable")] - public IActionResult Unavailable() - { - return View(); - } - - [HttpGet] - [Route("default")] - public async Task Default() - { - var user = await _userService.GetAsync(UserId); - if (user.RecentlyViewedOrganizationId == Guid.Empty && user.RecentlyViewedWardenId == Guid.Empty) - return RedirectToAction("Unavailable"); - - var organization = await _organizationService.GetAsync(user.RecentlyViewedOrganizationId); - if (organization == null) - return RedirectToAction("Unavailable"); - - if(!organization.Wardens.Any()) - return RedirectToAction("Unavailable"); - - var wardenId = organization.Wardens.FirstOrDefault(x => x.Id == user.RecentlyViewedWardenId)?.Id ?? - organization.Wardens.First().Id; - - return RedirectToAction("Details", new - { - organizationId = user.RecentlyViewedOrganizationId, wardenId - }); - } - - [HttpGet] - [Route("organizations/{organizationId}/wardens/{wardenId}")] - public async Task Details(Guid organizationId, Guid wardenId) - { - if (organizationId == Guid.Empty) - return NotFound(); - var isUserInOrganization = await _organizationService.IsUserInOrganizationAsync(organizationId, UserId); - if (!isUserInOrganization) - return NotFound(); - var organization = await _organizationService.GetAsync(organizationId); - if (organization == null) - return NotFound(); - var warden = organization.Wardens.FirstOrDefault(x => x.Id == wardenId); - if (warden == null) - return NotFound(); - - var user = await _userService.GetAsync(UserId); - if(!user.ApiKeys.Any()) - return NotFound(); - - await _userService.SetRecentlyViewedWardenInOrganizationAsync(UserId, organizationId, wardenId); - var viewModel = new DashboardViewModel - { - OrganizationId = organizationId, - OrganizationName = organization.Name, - WardenId = warden.Id, - WardenName = warden.Name, - TotalWatchers = warden.Watchers.Count(), - ApiKey = user.ApiKeys.First() - }; - - return View(viewModel); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Controllers/HomeController.cs b/src/Web/Warden.Web/Controllers/HomeController.cs deleted file mode 100644 index 6a332a4..0000000 --- a/src/Web/Warden.Web/Controllers/HomeController.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Warden.Web.Core.Services; - -namespace Warden.Web.Controllers -{ - public class HomeController : ControllerBase - { - private readonly IUserService _userService; - private readonly IOrganizationService _organizationService; - - public HomeController(IUserService userService, - IOrganizationService organizationService) - { - _userService = userService; - _organizationService = organizationService; - } - - [HttpGet] - [AllowAnonymous] - [Route("")] - public async Task Index() - { - if (!User.Identity.IsAuthenticated) - return RedirectToAction("Login", "Account"); - - var user = await _userService.GetAsync(UserId); - if (user.RecentlyViewedOrganizationId == Guid.Empty && user.RecentlyViewedWardenId == Guid.Empty) - return RedirectToAction("Index", "Organization"); - - var organization = await _organizationService.GetAsync(user.RecentlyViewedOrganizationId); - if (organization == null) - return RedirectToAction("Index", "Organization"); - - return organization.Wardens.Any(x => x.Id == user.RecentlyViewedWardenId) - ? RedirectToAction("Details", "Dashboard", new - { - organizationId = user.RecentlyViewedOrganizationId, - wardenId = user.RecentlyViewedWardenId - }) - : RedirectToAction("Details", "Organization", new {id = user.RecentlyViewedOrganizationId}); - } - - [HttpGet] - [AllowAnonymous] - [Route("about")] - public IActionResult About() - { - return View(); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Controllers/OrganizationController.cs b/src/Web/Warden.Web/Controllers/OrganizationController.cs deleted file mode 100644 index 9c12d6a..0000000 --- a/src/Web/Warden.Web/Controllers/OrganizationController.cs +++ /dev/null @@ -1,347 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Queries; -using Warden.Web.Core.Services; -using Warden.Web.Extensions; -using Warden.Web.Framework; -using Warden.Web.Framework.Filters; -using Warden.Web.ViewModels; - -namespace Warden.Web.Controllers -{ - [Route("organizations")] - public class OrganizationController : ControllerBase - { - private readonly IOrganizationService _organizationService; - private readonly IUserService _userService; - private readonly IApiKeyService _apiKeyService; - - public OrganizationController(IOrganizationService organizationService, - IUserService userService, IApiKeyService apiKeyService) - { - _organizationService = organizationService; - _userService = userService; - _apiKeyService = apiKeyService; - } - - [HttpGet] - [Route("")] - public async Task Index() - { - var organizations = await _organizationService.BrowseAsync(new BrowseOrganizations - { - UserId = UserId - }); - - return View(organizations); - } - - [HttpGet] - [Route("{id}")] - public async Task Details(Guid id) - { - var organization = await GetOrganizationForUserAsync(id); - if (organization == null) - return NotFound(); - - var viewModel = new OrganizationViewModel - { - Organization = organization - }; - - return View(viewModel); - } - - [HttpGet] - [Route("create")] - [ImportModelStateFromTempData] - public IActionResult Create() - { - return View(); - } - - [HttpPost] - [Route("create")] - [ExportModelStateToTempData] - public async Task Create(CreateOrganizationViewModel viewModel) - { - if (!ModelState.IsValid) - return RedirectToAction("Create"); - - return await _organizationService.CreateAsync(viewModel.Name, UserId) - .ExecuteAsync( - onSuccess: async () => - { - var organization = await _organizationService.GetAsync(viewModel.Name, UserId); - Notify(FlashNotificationType.Success, "Organization has been created."); - return RedirectToAction("Details", new {id = organization.Id}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Create"); - }); - } - - [HttpGet] - [Route("{id}/edit")] - [ImportModelStateFromTempData] - public async Task Edit(Guid id) - { - if (!await IsOrganizationOwnerAsync(id)) - return new UnauthorizedResult(); - - var organization = await _organizationService.GetAsync(id); - var viewModel = new EditOrganizationViewModel - { - Name = organization.Name - }; - - return View(viewModel); - } - - [HttpPost] - [Route("{id}/edit")] - [ExportModelStateToTempData] - public async Task Edit(Guid id, EditOrganizationViewModel viewModel) - { - if (!await IsOrganizationOwnerAsync(id)) - return new UnauthorizedResult(); - - if (!ModelState.IsValid) - return RedirectToAction("Edit", new {id}); - - return await _organizationService.EditAsync(id, viewModel.Name) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Success, "Organization has been updated."); - return RedirectToAction("Details", new {id}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Edit", new {id}); - }); - } - - [HttpGet] - [Route("{id}/users")] - [ImportModelStateFromTempData] - public async Task AddUser(Guid id) - { - if (!await IsOrganizationOwnerAsync(id)) - return new UnauthorizedResult(); - - var organization = await GetOrganizationForUserAsync(id); - if (organization == null) - return BadRequest($"Invalid organization id: '{id}'."); - - return View(); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [ExportModelStateToTempData] - [Route("{id}/users")] - public async Task AddUser(Guid id, AddUserToOrganizationViewModel viewModel) - { - if (!await IsOrganizationOwnerAsync(id)) - return new UnauthorizedResult(); - - if (!ModelState.IsValid) - return RedirectToAction("AddUser"); - - var organization = await GetOrganizationForUserAsync(id); - if (organization == null) - return BadRequest($"Invalid organization id: '{id}'."); - - return await _organizationService.AddUserAsync(id, viewModel.Email) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Success, "User has been added to the organization."); - return RedirectToAction("Details", new {id = organization.Id}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("AddUser"); - }); - } - - [HttpGet] - [Route("{id}/wardens")] - [ImportModelStateFromTempData] - public async Task AddWarden(Guid id) - { - var organization = await GetOrganizationForUserAsync(id); - if (organization == null) - return BadRequest($"Invalid organization id: '{id}'."); - - return View(); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [ExportModelStateToTempData] - [Route("{id}/wardens")] - public async Task AddWarden(Guid id, AddWardenToOrganizationViewModel viewModel) - { - if (!ModelState.IsValid) - return RedirectToAction("AddWarden"); - - var organization = await GetOrganizationForUserAsync(id); - if (organization == null) - return BadRequest($"Invalid organization id: '{id}'."); - - return await _organizationService.AddWardenAsync(id, viewModel.Name) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Success, "Warden has been added to the organization."); - return RedirectToAction("Details", new {id = organization.Id}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("AddWarden"); - }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [Route("{id}/delete")] - public async Task Delete(Guid id) - { - if (!await IsOrganizationOwnerAsync(id)) - return new UnauthorizedResult(); - - return await _organizationService.DeleteAsync(id) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Info, "Organization has been removed."); - return RedirectToAction("Index"); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Index"); - }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [Route("{id}/users/delete")] - public async Task DeleteUser(Guid id, Guid userId) - { - if (!await IsOrganizationOwnerAsync(id)) - return new UnauthorizedResult(); - - return await _organizationService.DeleteUserAsync(id, userId) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Info, "User has been removed from the organization."); - return RedirectToAction("Details", new {id}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Details", new {id}); - }); - } - - [HttpGet] - [Route("{id}/users/{userId}")] - public async Task UserDetails(Guid id, Guid userId) - { - var organization = await GetOrganizationForUserAsync(id); - if (organization == null) - return BadRequest($"Invalid organization id: '{id}'."); - - var user = organization.Users.FirstOrDefault(x => x.Id == userId); - if (user == null) - return NotFound(); - - var viewModel = new UserInOrganizationViewModel - { - OrganizationId = organization.Id, - OwnerId = organization.OwnerId, - User = user - }; - - return View(viewModel); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [Route("{id}/auto-register-new-warden/enable")] - public async Task EnableAutoRegisterNewWarden(Guid id) - { - if (!await IsOrganizationOwnerAsync(id)) - return new UnauthorizedResult(); - - return await _organizationService.EnableAutoRegisterNewWardenAsync(id) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Info, "Automatic registration of new Wardens has been enabled."); - return RedirectToAction("Details", new {id}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Details", new {id}); - }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [Route("{id}/auto-register-new-warden/disable")] - public async Task DisableAutoRegisterNewWarden(Guid id) - { - if (!await IsOrganizationOwnerAsync(id)) - return new UnauthorizedResult(); - - return await _organizationService.DisableAutoRegisterNewWardenAsync(id) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Info, "Automatic registration of new Wardens has been disabled."); - return RedirectToAction("Details", new {id}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Details", new {id}); - }); - } - - private async Task GetOrganizationForUserAsync(Guid id) - { - if (id == Guid.Empty) - return null; - var isUserInOrganization = await _organizationService.IsUserInOrganizationAsync(id, UserId); - if (!isUserInOrganization) - return null; - var organization = await _organizationService.GetAsync(id); - - return organization; - } - - private async Task IsOrganizationOwnerAsync(Guid id) - { - var organization = await GetOrganizationForUserAsync(id); - if (organization == null) - return false; - - return organization.OwnerId == UserId; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Controllers/ResetPasswordController.cs b/src/Web/Warden.Web/Controllers/ResetPasswordController.cs deleted file mode 100644 index 9269a53..0000000 --- a/src/Web/Warden.Web/Controllers/ResetPasswordController.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Warden.Web.Core.Services; -using Warden.Web.Extensions; -using Warden.Web.Framework; -using Warden.Web.Framework.Filters; -using Warden.Web.ViewModels; - -namespace Warden.Web.Controllers -{ - [AllowAnonymous] - [Route("reset-password")] - public class ResetPasswordController : ControllerBase - { - private readonly IUserService _userService; - private const string ResetPasswordAccessKey = "reset-password"; - private const string SetNewPasswordAccessKey = "set-new-password"; - - public ResetPasswordController(IUserService userService) - { - _userService = userService; - } - - [HttpGet] - [ImportModelStateFromTempData] - [Route("")] - public IActionResult Initiate() - { - if (User.Identity.IsAuthenticated) - return RedirectToAction("Index", "Home"); - - return View(); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [ExportModelStateToTempData] - [Route("")] - public async Task Initiate(ResetPasswordViewModel viewModel) - { - if (!ModelState.IsValid) - return RedirectToAction("Initiate"); - - var ipAddress = Request.HttpContext?.Connection?.RemoteIpAddress?.ToString(); - var userAgent = Request.Headers["User-Agent"]; - - return await _userService.InitiatePasswordResetAsync(viewModel.Email, - ipAddress, userAgent) - .Execute( - onSuccess: () => - { - SetAccess(ResetPasswordAccessKey); - - return RedirectToAction("Status"); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - - return RedirectToAction("Initiate"); - }); - } - - [HttpGet] - [Route("status")] - public IActionResult Status() - { - var hasAccess = HasAccess(ResetPasswordAccessKey); - if (!hasAccess) - return RedirectToAction("Initiate"); - - SetAccess(ResetPasswordAccessKey); - - return View(); - } - - [HttpGet] - [Route("set-new")] - public async Task SetNew(string email, string token) - { - return await _userService.ValidatePasswordResetTokenAsync(email, token) - .Execute( - onSuccess: () => - { - SetAccess(SetNewPasswordAccessKey); - var viewModel = new SetNewPasswordViewModel - { - Email = email, - Token = token - }; - - return View(viewModel); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - - return RedirectToAction("Initiate"); - }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [ExportModelStateToTempData] - [Route("set-new")] - public async Task SetNew(SetNewPasswordViewModel viewModel) - { - if (!HasAccess(SetNewPasswordAccessKey)) - return RedirectToAction("Initiate"); - if (!ModelState.IsValid) - return RedirectToAction("SetNew"); - - var ipAddress = Request.HttpContext?.Connection?.RemoteIpAddress?.ToString(); - var userAgent = Request.Headers["User-Agent"]; - - return await _userService.CompletePasswordResetAsync(viewModel.Email, - viewModel.Token, viewModel.Password, ipAddress, userAgent) - .Execute( - onSuccess: () => - { - SetAccess(ResetPasswordAccessKey); - - return RedirectToAction("Complete"); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - - return RedirectToAction("SetNew", new {email = viewModel.Email, token = viewModel.Token}); - }); - } - - [HttpGet] - [Route("complete")] - public IActionResult Complete() - { - var hasAccess = HasAccess(SetNewPasswordAccessKey); - if (!hasAccess) - return RedirectToAction("Initiate"); - - SetAccess(SetNewPasswordAccessKey); - - return View(); - } - - private void SetAccess(string key) - { - TempData[key] = key; - } - - private bool HasAccess(string key) => TempData[key] as string == key; - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Controllers/SettingsController.cs b/src/Web/Warden.Web/Controllers/SettingsController.cs deleted file mode 100644 index 15307c9..0000000 --- a/src/Web/Warden.Web/Controllers/SettingsController.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Services; -using Warden.Web.Extensions; -using Warden.Web.Framework; -using Warden.Web.Framework.Filters; -using Warden.Web.ViewModels; - -namespace Warden.Web.Controllers -{ - [Route("settings")] - public class SettingsController : ControllerBase - { - private readonly IUserService _userService; - private readonly IApiKeyService _apiKeyService; - - public SettingsController(IUserService userService, IApiKeyService apiKeyService) - { - _userService = userService; - _apiKeyService = apiKeyService; - } - - [HttpGet] - [Route("")] - public async Task Index() - { - var user = await _userService.GetAsync(UserId); - - return View(user); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [ExportModelStateToTempData] - [Route("api-keys")] - public async Task CreateApiKey() - { - await _apiKeyService.CreateAsync(UserId).Execute( - onSuccess: () => Notify(FlashNotificationType.Success, "API key has been created."), - onFailure: ex => Notify(FlashNotificationType.Error, ex.Message)); - - return RedirectToAction("Index"); - } - - [HttpGet] - [ImportModelStateFromTempData] - [Route("password")] - public IActionResult Password() - { - return View(); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [ExportModelStateToTempData] - [Route("password")] - public async Task Password(ChangePasswordViewModel viewModel) - { - if (!ModelState.IsValid) - return RedirectToAction("Password"); - - return await _userService.SetNewPasswordAsync(UserId, viewModel.ActualPassword, viewModel.NewPassword) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Success, "Password has been changed."); - return RedirectToAction("Index"); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Password"); - }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [Route("api-keys/delete")] - public async Task DeleteApiKey(string key) - { - var apiKey = await _apiKeyService.GetAsync(key); - if (apiKey?.UserId != UserId) - return BadRequest("Invalid API key."); - - await _apiKeyService.DeleteAsync(key); - - Notify(FlashNotificationType.Info, "API key has been removed."); - return RedirectToAction("Index"); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Controllers/WardenController.cs b/src/Web/Warden.Web/Controllers/WardenController.cs deleted file mode 100644 index 78e8822..0000000 --- a/src/Web/Warden.Web/Controllers/WardenController.cs +++ /dev/null @@ -1,210 +0,0 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Linq; -using Warden.Web.Core.Dto; -using Warden.Web.Core.Queries; -using Warden.Web.Core.Services; -using Warden.Web.Extensions; -using Warden.Web.Framework; -using Warden.Web.Framework.Filters; -using Warden.Web.ViewModels; - -namespace Warden.Web.Controllers -{ - [Route("organizations/{organizationId}/wardens")] - public class WardenController : ControllerBase - { - private readonly IOrganizationService _organizationService; - private readonly IWardenService _wardenService; - private readonly IWatcherService _watcherService; - - public WardenController(IOrganizationService organizationService, - IWardenService wardenService, IWatcherService watcherService) - { - _organizationService = organizationService; - _wardenService = wardenService; - _watcherService = watcherService; - } - - [HttpGet] - [Route("{wardenId}")] - public async Task Details(Guid organizationId, Guid wardenId, - int page = 1, int results = 10) - { - var warden = await GetWardenForUserAsync(organizationId, wardenId); - if (warden == null) - return NotFound(); - - var stats = await _wardenService.GetStatsAsync(new GetWardenStats - { - OrganizationId = organizationId, - WardenName = warden.Name - }); - var watchers = await _watcherService.GetAllAsync(organizationId, wardenId); - var iterations = await _wardenService.BrowseIterationsAsync(new BrowseWardenIterations - { - OrganizationId = organizationId, - WardenName = warden.Name, - Page = page, - Results = results - }); - var viewModel = new WardenViewModel - { - Id = wardenId, - OrganizationId = organizationId, - Stats = stats, - CreatedAt = warden.CreatedAt, - Iterations = iterations, - Watchers = watchers - }; - - return View(viewModel); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [Route("{wardenId}/disable")] - public async Task Disable(Guid organizationId, Guid wardenId) - { - if (!ModelState.IsValid) - return RedirectToAction("Details", new {organizationId, wardenId}); - - var warden = await GetWardenForUserAsync(organizationId, wardenId); - if (warden == null) - return NotFound(); - - return await _organizationService.DisableWardenAsync(organizationId, warden.Name) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Info, "Warden has been disabled."); - return RedirectToAction("Details", new {organizationId, wardenId}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Details", new {organizationId, wardenId}); - }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [Route("{wardenId}/enable")] - public async Task Enable(Guid organizationId, Guid wardenId) - { - if (!ModelState.IsValid) - return RedirectToAction("Details", new {organizationId, wardenId}); - - var warden = await GetWardenForUserAsync(organizationId, wardenId); - if (warden == null) - return NotFound(); - - return await _organizationService.EnableWardenAsync(organizationId, warden.Name) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Success, "Warden has been enabled."); - return RedirectToAction("Details", new {organizationId, wardenId}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Details", new {organizationId, wardenId}); - }); - } - - [HttpGet] - [Route("{wardenId}/iterations/{iterationId}")] - public async Task Iteration(Guid organizationId, Guid wardenId, Guid iterationId) - { - var warden = await GetWardenForUserAsync(organizationId, wardenId); - if (warden == null) - return NotFound(); - var iteration = await _wardenService.GetIterationAsync(iterationId); - if (iteration == null) - return NotFound(); - - var viewModel = new WardenIterationViewModel - { - OrganizationId = organizationId, - WardenId = wardenId, - Iteration = iteration - }; - - return View(viewModel); - } - - [HttpGet] - [Route("{wardenId}/edit")] - [ImportModelStateFromTempData] - public async Task Edit(Guid organizationId, Guid wardenId) - { - var warden = await GetWardenForUserAsync(organizationId, wardenId); - if (warden == null) - return NotFound(); - - var viewModel = new EditWardenViewModel - { - Name = warden.Name - }; - - return View(viewModel); - } - - [HttpPost] - [Route("{wardenId}/edit")] - [ExportModelStateToTempData] - public async Task Edit(Guid organizationId, Guid wardenId, EditWardenViewModel viewModel) - { - if (!ModelState.IsValid) - return RedirectToAction("Edit", new {organizationId, wardenId}); - - return await _wardenService.EditAsync(organizationId, wardenId, viewModel.Name) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Success, "Warden has been updated."); - return RedirectToAction("Details", new {organizationId, wardenId}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Edit", new {organizationId, wardenId}); - }); - } - - - [HttpPost] - [ValidateAntiForgeryToken] - [Route("{wardenId}/delete")] - public async Task Delete(Guid organizationId, Guid wardenId) - { - return await _organizationService.DeleteWardenAsync(organizationId, wardenId) - .Execute( - onSuccess: () => - { - Notify(FlashNotificationType.Info, "Warden has been removed."); - return RedirectToAction("Details", "Organization", new {id = organizationId}); - }, - onFailure: ex => - { - Notify(FlashNotificationType.Error, ex.Message); - return RedirectToAction("Details", new {organizationId, wardenId}); - }); - } - - private async Task GetWardenForUserAsync(Guid organizationId, Guid wardenId) - { - if (organizationId == Guid.Empty) - return null; - var isUserInOrganization = await _organizationService.IsUserInOrganizationAsync(organizationId, UserId); - if (!isUserInOrganization) - return null; - var organization = await _organizationService.GetAsync(organizationId); - var warden = organization?.Wardens.FirstOrDefault(x => x.Id == wardenId); - - return warden; - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Controllers/WatcherController.cs b/src/Web/Warden.Web/Controllers/WatcherController.cs deleted file mode 100644 index ad5027b..0000000 --- a/src/Web/Warden.Web/Controllers/WatcherController.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Warden.Web.Core.Queries; -using Warden.Web.Core.Services; -using Warden.Web.ViewModels; - -namespace Warden.Web.Controllers -{ - [Route("organizations/{organizationId}/wardens/{wardenId}/watchers")] - public class WatcherController : ControllerBase - { - private readonly IWatcherService _watcherService; - private readonly IOrganizationService _organizationService; - - public WatcherController(IWatcherService watcherService, IOrganizationService organizationService) - { - _watcherService = watcherService; - _organizationService = organizationService; - } - - [HttpGet] - [Route("{watcherName}")] - public async Task Details(Guid organizationId, Guid wardenId, string watcherName, - int page = 1, int results = 10) - { - var hasAccess = await _organizationService.IsUserInOrganizationAsync(organizationId, UserId); - if (!hasAccess) - return Unauthorized(); - - var stats = await _watcherService.GetStatsAsync(new GetWatcherStats - { - OrganizationId = organizationId, - WardenId = wardenId, - WatcherName = watcherName - }); - - if (stats == null) - return NotFound(); - - var checks = await _watcherService.BrowseChecksAsync(new BrowseWardenCheckResults - { - OrganizationId = organizationId, - WardenId = wardenId, - WatcherName = watcherName, - Page = page, - Results = results - }); - - var viewModel = new WatcherViewModel - { - OrganizationId = organizationId, - WardenId = wardenId, - Stats = stats, - Checks = checks - }; - - return View(viewModel); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Extensions/AspNetExtensions.cs b/src/Web/Warden.Web/Extensions/AspNetExtensions.cs deleted file mode 100644 index 7c391d2..0000000 --- a/src/Web/Warden.Web/Extensions/AspNetExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.IO; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using NLog; -using NLog.Config; -using NLog.Extensions.Logging; -using System.Reflection; -using Microsoft.Extensions.DependencyInjection; - -namespace Warden.Web.Extensions -{ - public static class AspNetExtensions - { - public static ILoggerFactory AddNLog(this ILoggerFactory factory, IConfigurationRoot configuration) - { - //ignore this - LogManager.AddHiddenAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly); - - using (var provider = new NLogLoggerProvider()) - { - factory.AddProvider(provider); - } - - var configFilePath = "nlog.config"; - if (string.IsNullOrEmpty(configFilePath)) - throw new NLogConfigurationException("Not found NLog config path. Did you add NLog config?"); - ConfigureNLog(configFilePath); - - return factory; - } - - private static void ConfigureNLog(string fileName) - { - LogManager.Configuration = new XmlLoggingConfiguration(fileName, true); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Extensions/TaskExtensions.cs b/src/Web/Warden.Web/Extensions/TaskExtensions.cs deleted file mode 100644 index 727b260..0000000 --- a/src/Web/Warden.Web/Extensions/TaskExtensions.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using NLog; -using Warden.Web.Core.Domain; - -namespace Warden.Web.Extensions -{ - public static class TaskExtensions - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - - public static async Task Execute(this Task task, - Action onSuccess, - Action onFailure = null) - { - try - { - await task; - onSuccess(); - } - catch (DomainException exception) - { - Logger.Error(exception); - onFailure?.Invoke(exception); - } - catch (ServiceException exception) - { - Logger.Error(exception); - onFailure?.Invoke(exception); - } - } - - public static async Task Execute(this Task task, - Func onSuccess, - Func onFailure = null) - { - try - { - await task; - return onSuccess(); - } - catch (DomainException exception) - { - Logger.Error(exception); - return onFailure?.Invoke(exception); - } - catch (ServiceException exception) - { - Logger.Error(exception); - return onFailure?.Invoke(exception); - } - } - - public static async Task ExecuteAsync(this Task task, - Func> onSuccess, - Func onFailure = null) - { - try - { - await task; - return await onSuccess(); - } - catch (DomainException exception) - { - Logger.Error(exception); - return onFailure?.Invoke(exception); - } - catch (ServiceException exception) - { - Logger.Error(exception); - return onFailure?.Invoke(exception); - } - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Extensions/UrlHelperExtensions.cs b/src/Web/Warden.Web/Extensions/UrlHelperExtensions.cs deleted file mode 100644 index e2fc4a0..0000000 --- a/src/Web/Warden.Web/Extensions/UrlHelperExtensions.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System.Collections.Generic; -using Microsoft.AspNetCore.Html; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Rendering; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Extensions -{ - public static class UrlHelperExtensions - { - public static IHtmlContent Paginate(this IUrlHelper urlHelper, PagedResultBase viewModel, - string action) => urlHelper.Paginate(viewModel, action, string.Empty); - - public static IHtmlContent Paginate(this IUrlHelper urlHelper, PagedResultBase viewModel, - string action, string controller) - { - var listTag = new TagBuilder("ul"); - listTag.AddCssClass("pagination"); - var previousPageTag = GetPreviousPageTag(urlHelper, viewModel, action, controller); - listTag.InnerHtml.Append(previousPageTag.ToString()); - var pageTags = GetPageTags(urlHelper, viewModel, action, controller); - foreach (var pageTag in pageTags) - { - listTag.InnerHtml.Append(pageTag.ToString()); - } - var nextPageTag = GetNextPageTag(urlHelper, viewModel, action, controller); - listTag.InnerHtml.Append(nextPageTag.ToString()); - - return listTag; - } - - private static TagBuilder GetPreviousPageTag(this IUrlHelper urlHelper, PagedResultBase viewModel, - string action, string controller) - { - var listItemTag = new TagBuilder("li"); - var linkTag = new TagBuilder("a"); - var iconTag = new TagBuilder("i"); - iconTag.AddCssClass("material-icons"); - iconTag.InnerHtml.Append("chevron_left"); - if (viewModel.CurrentPage > 1) - { - linkTag.MergeAttribute("href", GetUrl(urlHelper, action, controller, - viewModel.CurrentPage - 1, viewModel.ResultsPerPage)); - } - else - { - listItemTag.AddCssClass("disabled"); - } - - linkTag.InnerHtml.Append(iconTag.ToString()); - listItemTag.InnerHtml.Append(linkTag.ToString()); - - return listItemTag; - } - - private static IEnumerable GetPageTags(this IUrlHelper urlHelper, PagedResultBase viewModel, - string action, string controller) - { - var totalPages = viewModel.TotalPages <= 0 ? 1 : viewModel.TotalPages; - var currentPage = viewModel.CurrentPage <= 0 ? 1 : viewModel.CurrentPage; - for (var i = 1; i <= totalPages; i++) - { - var isCurrentPage = currentPage == i; - var listItemTag = new TagBuilder("li"); - var linkTag = new TagBuilder("a"); - linkTag.MergeAttribute("href", GetUrl(urlHelper, action, controller, i, viewModel.ResultsPerPage)); - linkTag.AddCssClass("item"); - if (isCurrentPage) - linkTag.AddCssClass("white-text"); - - var pageClass = isCurrentPage ? "custom" : "waves-effect"; - listItemTag.AddCssClass(pageClass); - - linkTag.InnerHtml.Append(i.ToString()); - listItemTag.InnerHtml.Append(linkTag.ToString()); - - yield return listItemTag; - } - } - - private static TagBuilder GetNextPageTag(this IUrlHelper urlHelper, PagedResultBase viewModel, - string action, string controller) - { - var totalPages = viewModel.TotalPages <= 0 ? 1 : viewModel.TotalPages; - var currentPage = viewModel.CurrentPage <= 0 ? 1 : viewModel.CurrentPage; - var listItemTag = new TagBuilder("li"); - var linkTag = new TagBuilder("a"); - var iconTag = new TagBuilder("i"); - iconTag.AddCssClass("material-icons"); - iconTag.InnerHtml.Append("chevron_right"); - if (currentPage < totalPages) - { - linkTag.MergeAttribute("href", GetUrl(urlHelper, action, controller, - currentPage + 1, viewModel.ResultsPerPage)); - } - else - { - listItemTag.AddCssClass("disabled"); - } - - linkTag.InnerHtml.Append(iconTag.ToString()); - listItemTag.InnerHtml.Append(linkTag.ToString()); - - return listItemTag; - } - - private static string GetUrl(IUrlHelper urlHelper, string action, string controller, - int page, int results) => controller.Empty() - ? urlHelper.Action(action, new {page, results}) - : urlHelper.Action(action, controller, new {page, results}); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Framework/Filters/ExceptionFilter.cs b/src/Web/Warden.Web/Framework/Filters/ExceptionFilter.cs deleted file mode 100644 index 05972c4..0000000 --- a/src/Web/Warden.Web/Framework/Filters/ExceptionFilter.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Microsoft.AspNetCore.Mvc.Filters; -using NLog; - -namespace Warden.Web.Framework.Filters -{ - public class ExceptionFilter : ActionFilterAttribute, IExceptionFilter - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - - public void OnException(ExceptionContext context) - { - Logger.Error(context.Exception); - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Framework/Filters/ExportModelStateToTempData.cs b/src/Web/Warden.Web/Framework/Filters/ExportModelStateToTempData.cs deleted file mode 100644 index d5ee77d..0000000 --- a/src/Web/Warden.Web/Framework/Filters/ExportModelStateToTempData.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Mvc.ViewFeatures; -using Microsoft.Extensions.DependencyInjection; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Framework.Filters -{ - public class ExportModelStateToTempData : ModelStateTempDataTransfer - { - public override void OnActionExecuted(ActionExecutedContext filterContext) - { - // TODO: Why are we doing this?? - /* - var tempData = filterContext.HttpContext.RequestServices.GetService(); - if (filterContext.ModelState.IsValid) - return; - if (IsInvalidResult(filterContext)) - return; - - var values = filterContext.ModelState.ToList() - .Select(item => new KeyValuePair(item.Key, new Entry(item.Value))) - .ToDictionary(x => x.Key, x => x.Value); - tempData[ModelEntriesKey] = values.ToJson(); - - base.OnActionExecuted(filterContext); - */ - } - - private static bool IsInvalidResult(ActionExecutedContext context) - => !(context.Result is RedirectToActionResult) && - !(context.Result is RedirectResult) && - !(context.Result is RedirectToRouteResult); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Framework/Filters/ImportModelStateFromTempData.cs b/src/Web/Warden.Web/Framework/Filters/ImportModelStateFromTempData.cs deleted file mode 100644 index 61cfd8f..0000000 --- a/src/Web/Warden.Web/Framework/Filters/ImportModelStateFromTempData.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.Mvc.ViewFeatures; -using Microsoft.Extensions.DependencyInjection; -using Warden.Web.Core.Extensions; - -namespace Warden.Web.Framework.Filters -{ - public class ImportModelStateFromTempData : ModelStateTempDataTransfer - { - public override void OnActionExecuted(ActionExecutedContext filterContext) - { - // TODO: Why are we doing this?? - /* - var tempData = filterContext.HttpContext.RequestServices.GetService(); - if (tempData == null || !tempData.ContainsKey(ModelEntriesKey)) - return; - - var modelEntries = tempData[ModelEntriesKey].ToString().FromJson>(); - if (modelEntries == null) - return; - - foreach (var modelEntry in modelEntries) - { - filterContext.ModelState.Add(modelEntry.Key, new ModelStateEntry - { - AttemptedValue = modelEntry.Value.AttemptedValue, - RawValue = modelEntry.Value.RawValue, - ValidationState = modelEntry.Value.State - }); - - foreach (var error in modelEntry.Value.Errors) - { - filterContext.ModelState.AddModelError(modelEntry.Key, error); - } - } - - tempData.Remove(ModelEntriesKey); - base.OnActionExecuted(filterContext); - */ - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Framework/Filters/ModelStateTempDataTransfer.cs b/src/Web/Warden.Web/Framework/Filters/ModelStateTempDataTransfer.cs deleted file mode 100644 index 21e16aa..0000000 --- a/src/Web/Warden.Web/Framework/Filters/ModelStateTempDataTransfer.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Mvc.ModelBinding; - -namespace Warden.Web.Framework.Filters -{ - public abstract class ModelStateTempDataTransfer : ActionFilterAttribute - { - protected static readonly string ModelEntriesKey = typeof(ModelStateTempDataTransfer).FullName; - - protected internal class Entry - { - public object RawValue { get; set; } - public string AttemptedValue { get; set; } - public ModelValidationState State { get; set; } - public IEnumerable Errors { get; set; } - - public Entry() - { - } - - public Entry(ModelStateEntry entry) - { - RawValue = entry.RawValue; - AttemptedValue = entry.AttemptedValue; - State = entry.ValidationState; - Errors = entry.Errors?.Select(x => x.ErrorMessage) ?? Enumerable.Empty(); - } - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Framework/FlashNotificationType.cs b/src/Web/Warden.Web/Framework/FlashNotificationType.cs deleted file mode 100644 index 6c58940..0000000 --- a/src/Web/Warden.Web/Framework/FlashNotificationType.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Warden.Web.Framework -{ - public enum FlashNotificationType - { - Error = 0, - Info = 1, - Success = 2 - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Framework/GeneralSettings.cs b/src/Web/Warden.Web/Framework/GeneralSettings.cs deleted file mode 100644 index f4be2fc..0000000 --- a/src/Web/Warden.Web/Framework/GeneralSettings.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Warden.Web.Framework -{ - public class GeneralSettings - { - public string ConnectionString { get; set; } - public string Database { get; set; } - public string EncrypterKey { get; set; } - public string JsonFormatDate { get; set; } - public string AuthCookieName { get; set; } - public string LoginPath { get; set; } - public string LogoutPath { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Hubs/WardenHub.cs b/src/Web/Warden.Web/Hubs/WardenHub.cs deleted file mode 100644 index 2d2f335..0000000 --- a/src/Web/Warden.Web/Hubs/WardenHub.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNet.SignalR; -using Warden.Web.Core.Extensions; -using Warden.Web.Core.Services; - -namespace Warden.Web.Hubs -{ - [Authorize] - public class WardenHub : Hub - { - private readonly IUserService _userService; - private readonly IOrganizationService _organizationService; - - public WardenHub(IUserService userService, IOrganizationService organizationService) - { - _userService = userService; - _organizationService = organizationService; - } - - public override async Task OnConnected() - { - var groupName = await ParseRequestAndGetWardenGroupNameOrFailAsync(); - await Groups.Add(Context.ConnectionId, groupName); - await base.OnConnected(); - } - - public override async Task OnReconnected() - { - var groupName = await ParseRequestAndGetWardenGroupNameOrFailAsync(); - await Groups.Add(Context.ConnectionId, groupName); - await base.OnReconnected(); - } - - public override async Task OnDisconnected(bool stopCalled) - { - var groupName = await ParseRequestAndGetWardenGroupNameOrFailAsync(); - await Groups.Remove(Context.ConnectionId, groupName); - await base.OnDisconnected(stopCalled); - } - - private async Task ParseRequestAndGetWardenGroupNameOrFailAsync() - { - var organizationIdValue = Context.QueryString["organizationId"]; - var wardenName = Context.QueryString["wardenName"]; - if (organizationIdValue.Empty() || wardenName.Empty()) - throw new InvalidOperationException("Empty organization id and/or warden name."); - - Guid organizationId; - if (!Guid.TryParse(organizationIdValue, out organizationId)) - throw new InvalidOperationException("Invalid organization id."); - - var hasAccess = await _organizationService.IsUserInOrganizationAsync(organizationId, - Guid.Parse(Context.User.Identity.Name)); - if (!hasAccess) - throw new InvalidOperationException("No access to the selected organization and warden."); - - return GetWardenGroupName(organizationId, wardenName); - } - - private static string GetWardenGroupName(Guid organizationId, string wardenName) - => $"{organizationId}::{wardenName}".TrimToLower(); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Properties/launchSettings.json b/src/Web/Warden.Web/Properties/launchSettings.json deleted file mode 100644 index d2364dd..0000000 --- a/src/Web/Warden.Web/Properties/launchSettings.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:11223/", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "Hosting:Environment": "Development" - } - }, - "web": { - "commandName": "web", - "environmentVariables": { - "Hosting:Environment": "Development" - } - } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Startup.cs b/src/Web/Warden.Web/Startup.cs deleted file mode 100644 index 4d5351a..0000000 --- a/src/Web/Warden.Web/Startup.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.IO; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; -using MongoDB.Driver; -using Newtonsoft.Json.Serialization; -using Warden.Web.Core.Mongo; -using Warden.Web.Core.Services; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNet.SignalR; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.PlatformAbstractions; -using Microsoft.Extensions.Caching.Memory; -using Microsoft.AspNetCore.Server.IISIntegration; -using Microsoft.Owin.Builder; -using Newtonsoft.Json; -using NLog; -using NLog.Extensions.Logging; -using Owin; -using Warden.Web.Core.Factories; -using Warden.Web.Core.Settings; -using Warden.Web.Extensions; -using Warden.Web.Framework; -using Warden.Web.Framework.Filters; -using Warden.Web.Hubs; - -namespace Warden.Web -{ - public class Startup - { - protected static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private IConfigurationRoot Configuration { get; } - - public Startup(IHostingEnvironment env) - { - Configuration = new ConfigurationBuilder() - .SetBasePath(env.ContentRootPath) - .AddJsonFile("config.json") - .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true) - .AddEnvironmentVariables() - .Build(); - - env.ConfigureNLog("nlog.config"); - } - - public void ConfigureServices(IServiceCollection services) - { - GeneralSettings settings = GetConfigurationValue("general"); - - services.AddOptions(); - - services.Configure(Configuration.GetSection("feature")); - services.Configure(Configuration.GetSection("general")); - services.Configure(Configuration.GetSection("email")); - services.Configure(Configuration.GetSection("account")); - services.AddMvc(options => - { - options.Filters.Add(new ExceptionFilter()); - }); - services.AddMvcCore().AddJsonFormatters(formatter => - { - formatter.DateFormatString = settings.JsonFormatDate; - formatter.Formatting = Formatting.Indented; - formatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); - }); - services.AddMemoryCache(); - services.AddSession(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(provider => GetConfigurationValue("feature")); - services.AddSingleton(provider => GetConfigurationValue("general")); - services.AddSingleton(provider => GetConfigurationValue("email")); - services.AddSingleton(provider => GetConfigurationValue("account")); - services.AddSingleton(provider => new Encrypter(settings.EncrypterKey)); - services.AddSingleton(provider => new MongoClient(settings.ConnectionString)); - services.AddScoped(provider => provider.GetService().GetDatabase(settings.Database)); - services.AddScoped(provider => - new SignalRService(GlobalHost.ConnectionManager.GetHubContext())); - } - - private T GetConfigurationValue(string section) where T : new() - { - T val = new T(); - Configuration.GetSection(section).Bind(val); - return val; - } - - public void Configure(IApplicationBuilder app, IHostingEnvironment env, - ILoggerFactory loggerFactory, IServiceProvider serviceProvider, GeneralSettings settings) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - loggerFactory.AddNLog(Configuration); - app.UseStaticFiles(); - app.UseCookieAuthentication(new CookieAuthenticationOptions() - { - AutomaticAuthenticate = true, - AutomaticChallenge = true, - CookieName = settings.AuthCookieName, - LoginPath = settings.LoginPath, - LogoutPath = settings.LogoutPath - }); - app.UseSession(); - app.UseMvcWithDefaultRoute(); - app.UseDeveloperExceptionPage(); - MapSignalR(app, serviceProvider); - MongoConfigurator.Initialize(); - Logger.Info("Application has started."); - } - - //Issues with Signalr 3 groups - using the version 2 for now. - private void MapSignalR(IApplicationBuilder app, IServiceProvider serviceProvider) - { - app.UseOwin(addToPipeline => - { - addToPipeline(next => - { - var appBuilder = new AppBuilder(); - appBuilder.Properties["builder.DefaultApp"] = next; - - appBuilder.MapSignalR(); - - return appBuilder.Build(); - }); - }); - - GlobalHost.DependencyResolver.Register(typeof(WardenHub), () => - new WardenHub(serviceProvider.GetService(), - serviceProvider.GetService())); - - //SignalR camelCase JSON resolver does not seem to be working. - } - - public static void Main(string[] args) - { - var host = new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup() - .Build(); - - host.Run(); - } - } -} diff --git a/src/Web/Warden.Web/ViewModels/AddUserToOrganizationViewModel.cs b/src/Web/Warden.Web/ViewModels/AddUserToOrganizationViewModel.cs deleted file mode 100644 index be6279e..0000000 --- a/src/Web/Warden.Web/ViewModels/AddUserToOrganizationViewModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class AddUserToOrganizationViewModel - { - [Required(ErrorMessage = "Email address is required.")] - [EmailAddress(ErrorMessage = "Invalid email address.")] - [DataType(DataType.EmailAddress)] - [Display(Name = "Email")] - public string Email { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/AddWardenToOrganizationViewModel.cs b/src/Web/Warden.Web/ViewModels/AddWardenToOrganizationViewModel.cs deleted file mode 100644 index c908b44..0000000 --- a/src/Web/Warden.Web/ViewModels/AddWardenToOrganizationViewModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class AddWardenToOrganizationViewModel - { - [Required(ErrorMessage = "Name is required.")] - [DataType(DataType.Text)] - [Display(Name = "Name")] - [StringLength(100, ErrorMessage = "Name can not have more than 100 characters.")] - public string Name { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/ChangePasswordViewModel.cs b/src/Web/Warden.Web/ViewModels/ChangePasswordViewModel.cs deleted file mode 100644 index a73f1d9..0000000 --- a/src/Web/Warden.Web/ViewModels/ChangePasswordViewModel.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class ChangePasswordViewModel - { - [Required(ErrorMessage = "Actual password is required.")] - [StringLength(100, MinimumLength = 4, ErrorMessage = "Actual password must contain between 4-100 characters.")] - [DataType(DataType.Password)] - [Display(Name = "Actual password")] - public string ActualPassword { get; set; } - - [Required(ErrorMessage = "New password is required.")] - [StringLength(100, MinimumLength = 4, ErrorMessage = "New password must contain between 4-100 characters.")] - [DataType(DataType.Password)] - [Display(Name = "New password")] - public string NewPassword { get; set; } - - [DataType(DataType.Password)] - [Compare("NewPassword", ErrorMessage = "New password and its confirmation do not match.")] - [Display(Name = "Confirm new password")] - public string ConfirmNewPassword { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/CreateOrganizationViewModel.cs b/src/Web/Warden.Web/ViewModels/CreateOrganizationViewModel.cs deleted file mode 100644 index 8766af7..0000000 --- a/src/Web/Warden.Web/ViewModels/CreateOrganizationViewModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class CreateOrganizationViewModel - { - [Required(ErrorMessage = "Name is required.")] - [DataType(DataType.Text)] - [Display(Name = "Name")] - [StringLength(100, ErrorMessage = "Name can not have more than 100 characters.")] - public string Name { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/DashboardViewModel.cs b/src/Web/Warden.Web/ViewModels/DashboardViewModel.cs deleted file mode 100644 index f61d1fd..0000000 --- a/src/Web/Warden.Web/ViewModels/DashboardViewModel.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace Warden.Web.ViewModels -{ - public class DashboardViewModel - { - public Guid OrganizationId { get; set; } - public string OrganizationName { get; set; } - public Guid WardenId { get; set; } - public string WardenName { get; set; } - public string ApiKey { get; set; } - public int TotalWatchers { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/EditOrganizationViewModel.cs b/src/Web/Warden.Web/ViewModels/EditOrganizationViewModel.cs deleted file mode 100644 index 9aa41ff..0000000 --- a/src/Web/Warden.Web/ViewModels/EditOrganizationViewModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class EditOrganizationViewModel - { - [Required(ErrorMessage = "Name is required.")] - [DataType(DataType.Text)] - [Display(Name = "Name")] - [StringLength(100, ErrorMessage = "Name can not have more than 100 characters.")] - public string Name { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/EditWardenViewModel.cs b/src/Web/Warden.Web/ViewModels/EditWardenViewModel.cs deleted file mode 100644 index b8a926c..0000000 --- a/src/Web/Warden.Web/ViewModels/EditWardenViewModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class EditWardenViewModel - { - [Required(ErrorMessage = "Name is required.")] - [DataType(DataType.Text)] - [Display(Name = "Name")] - [StringLength(100, ErrorMessage = "Name can not have more than 100 characters.")] - public string Name { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/LoginViewModel.cs b/src/Web/Warden.Web/ViewModels/LoginViewModel.cs deleted file mode 100644 index 258d1d5..0000000 --- a/src/Web/Warden.Web/ViewModels/LoginViewModel.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class LoginViewModel - { - [Required(ErrorMessage = "Email address is required.")] - [EmailAddress(ErrorMessage = "Invalid email address.")] - [DataType(DataType.EmailAddress)] - [Display(Name = "Email")] - public string Email { get; set; } - - [Required(ErrorMessage = "Password is required.")] - [StringLength(100, MinimumLength = 4, ErrorMessage = "Password must contain between 4-100 characters.")] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } - - [Display(Name = "Remember me")] - public bool RememberMe { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/OrganizationViewModel.cs b/src/Web/Warden.Web/ViewModels/OrganizationViewModel.cs deleted file mode 100644 index cbaf249..0000000 --- a/src/Web/Warden.Web/ViewModels/OrganizationViewModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Dto; - -namespace Warden.Web.ViewModels -{ - public class OrganizationViewModel - { - public OrganizationDto Organization { get; set; } - public UserInOrganizationDto Owner => Organization.Users.First(x => x.Role == OrganizationRole.Owner); - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/RegisterViewModel.cs b/src/Web/Warden.Web/ViewModels/RegisterViewModel.cs deleted file mode 100644 index b2c36c4..0000000 --- a/src/Web/Warden.Web/ViewModels/RegisterViewModel.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class RegisterViewModel - { - [Required(ErrorMessage = "Email address is required.")] - [EmailAddress(ErrorMessage = "Invalid email address.")] - [DataType(DataType.EmailAddress)] - [Display(Name = "Email")] - public string Email { get; set; } - - [Required(ErrorMessage = "Password is required.")] - [StringLength(100, MinimumLength = 4, ErrorMessage = "Password must contain between 4-100 characters.")] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } - - [DataType(DataType.Password)] - [Compare("Password", ErrorMessage = "Password and its confirmation do not match.")] - [Display(Name = "ConfirmPassword")] - public string ConfirmPassword { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/ResetPasswordViewModel.cs b/src/Web/Warden.Web/ViewModels/ResetPasswordViewModel.cs deleted file mode 100644 index 462720d..0000000 --- a/src/Web/Warden.Web/ViewModels/ResetPasswordViewModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class ResetPasswordViewModel - { - [Required(ErrorMessage = "Email address is required.")] - [EmailAddress(ErrorMessage = "Invalid email address.")] - [DataType(DataType.EmailAddress)] - [Display(Name = "Email")] - public string Email { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/SetNewPasswordViewModel.cs b/src/Web/Warden.Web/ViewModels/SetNewPasswordViewModel.cs deleted file mode 100644 index bd89ff1..0000000 --- a/src/Web/Warden.Web/ViewModels/SetNewPasswordViewModel.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Warden.Web.ViewModels -{ - public class SetNewPasswordViewModel - { - [Required(ErrorMessage = "Email address is required.")] - [EmailAddress(ErrorMessage = "Invalid email address.")] - [DataType(DataType.EmailAddress)] - [Display(Name = "Email")] - public string Email { get; set; } - - [Required(ErrorMessage = "Token is required.")] - [Display(Name = "Token")] - public string Token { get; set; } - - [Required(ErrorMessage = "Password is required.")] - [StringLength(100, MinimumLength = 4, ErrorMessage = "Password must contain between 4-100 characters.")] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } - - [DataType(DataType.Password)] - [Compare("Password", ErrorMessage = "Password and its confirmation do not match.")] - [Display(Name = "Confirm password")] - public string ConfirmPassword { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/UserInOrganizationViewModel.cs b/src/Web/Warden.Web/ViewModels/UserInOrganizationViewModel.cs deleted file mode 100644 index dead4ee..0000000 --- a/src/Web/Warden.Web/ViewModels/UserInOrganizationViewModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using Warden.Web.Core.Dto; - -namespace Warden.Web.ViewModels -{ - public class UserInOrganizationViewModel - { - public Guid OrganizationId { get; set; } - public Guid OwnerId { get; set; } - public UserInOrganizationDto User { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/WardenIterationViewModel.cs b/src/Web/Warden.Web/ViewModels/WardenIterationViewModel.cs deleted file mode 100644 index d72b67f..0000000 --- a/src/Web/Warden.Web/ViewModels/WardenIterationViewModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using Warden.Web.Core.Dto; - -namespace Warden.Web.ViewModels -{ - public class WardenIterationViewModel - { - public Guid OrganizationId { get; set; } - public Guid WardenId { get; set; } - public WardenIterationDto Iteration { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/WardenViewModel.cs b/src/Web/Warden.Web/ViewModels/WardenViewModel.cs deleted file mode 100644 index 7709adf..0000000 --- a/src/Web/Warden.Web/ViewModels/WardenViewModel.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Dto; - -namespace Warden.Web.ViewModels -{ - public class WardenViewModel - { - public Guid Id { get; set; } - public Guid OrganizationId { get; set; } - public DateTime CreatedAt { get; set; } - public WardenStatsDto Stats { get; set; } - public PagedResult Iterations { get; set; } - public IEnumerable Watchers { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/ViewModels/WatcherViewModel.cs b/src/Web/Warden.Web/ViewModels/WatcherViewModel.cs deleted file mode 100644 index bb1f176..0000000 --- a/src/Web/Warden.Web/ViewModels/WatcherViewModel.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using Warden.Web.Core.Domain; -using Warden.Web.Core.Dto; - -namespace Warden.Web.ViewModels -{ - public class WatcherViewModel - { - public Guid OrganizationId { get; set; } - public Guid WardenId { get; set; } - public WatcherStatsDto Stats { get; set; } - public PagedResult Checks { get; set; } - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Account/Login.cshtml b/src/Web/Warden.Web/Views/Account/Login.cshtml deleted file mode 100644 index 19f286c..0000000 --- a/src/Web/Warden.Web/Views/Account/Login.cshtml +++ /dev/null @@ -1,44 +0,0 @@ -@using System.Security.Policy -@model Warden.Web.ViewModels.LoginViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
Sign in
-
-
-
- - - -
-
-
-
- - - -
-
-

- - -

-
-
-
-
-
- -
-
-
- -
-
-
-
-
diff --git a/src/Web/Warden.Web/Views/Account/Register.cshtml b/src/Web/Warden.Web/Views/Account/Register.cshtml deleted file mode 100644 index 213d6cf..0000000 --- a/src/Web/Warden.Web/Views/Account/Register.cshtml +++ /dev/null @@ -1,37 +0,0 @@ -@model Warden.Web.ViewModels.RegisterViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
Sign up
-
-
-
- - - -
-
-
-
- - - -
-
- - - -
-
-
-
-
- -
-
-
-
-
-
diff --git a/src/Web/Warden.Web/Views/Dashboard/Details.cshtml b/src/Web/Warden.Web/Views/Dashboard/Details.cshtml deleted file mode 100644 index 74d69a2..0000000 --- a/src/Web/Warden.Web/Views/Dashboard/Details.cshtml +++ /dev/null @@ -1,150 +0,0 @@ -@model Warden.Web.ViewModels.DashboardViewModel -
-
-
-
-
Preparing Dashboard...
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -
-
- - -
-
- launch -
-
-
-
-
-
-
- -
    -
  • -
-
-
- -
    -
  • -
-
-
- -
    -
  • -
  • -
-
-
- -
- -
-
-
- -
    -
  • -
-
-
-
- -
-
-
-
-
- -
- -
-
-
- -
    -
  • -
-
-
- -
    -
  • -
-
-
- -
    -
  • -
-
-
- -
    -
  • -
-
-
- -
    -
  • -
-
-
-
-
- - - -
- - -
-
-
-
- - -@section scripts { - - -} diff --git a/src/Web/Warden.Web/Views/Dashboard/Unavailable.cshtml b/src/Web/Warden.Web/Views/Dashboard/Unavailable.cshtml deleted file mode 100644 index 75efd8e..0000000 --- a/src/Web/Warden.Web/Views/Dashboard/Unavailable.cshtml +++ /dev/null @@ -1,8 +0,0 @@ -
-
-

Dashboard is unavailable.

-
- No Warden iterations data have been found for the recently viewed organization. -
-
-
\ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Home/About.cshtml b/src/Web/Warden.Web/Views/Home/About.cshtml deleted file mode 100644 index 03d6cba..0000000 --- a/src/Web/Warden.Web/Views/Home/About.cshtml +++ /dev/null @@ -1,5 +0,0 @@ -
-
-

About

-
-
\ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Organization/AddUser.cshtml b/src/Web/Warden.Web/Views/Organization/AddUser.cshtml deleted file mode 100644 index 8d47405..0000000 --- a/src/Web/Warden.Web/Views/Organization/AddUser.cshtml +++ /dev/null @@ -1,24 +0,0 @@ -@model Warden.Web.ViewModels.AddUserToOrganizationViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
Add user to organization
-
-
-
- - - -
-
-
-
- -
-
-
-
-
-
diff --git a/src/Web/Warden.Web/Views/Organization/AddWarden.cshtml b/src/Web/Warden.Web/Views/Organization/AddWarden.cshtml deleted file mode 100644 index 77e851c..0000000 --- a/src/Web/Warden.Web/Views/Organization/AddWarden.cshtml +++ /dev/null @@ -1,24 +0,0 @@ -@model Warden.Web.ViewModels.AddWardenToOrganizationViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
Add warden to organization
-
-
-
- - - -
-
-
-
- -
-
-
-
-
-
diff --git a/src/Web/Warden.Web/Views/Organization/Create.cshtml b/src/Web/Warden.Web/Views/Organization/Create.cshtml deleted file mode 100644 index 5668858..0000000 --- a/src/Web/Warden.Web/Views/Organization/Create.cshtml +++ /dev/null @@ -1,24 +0,0 @@ -@model Warden.Web.ViewModels.CreateOrganizationViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
New organization
-
-
-
- - - -
-
-
-
- -
-
-
-
-
-
diff --git a/src/Web/Warden.Web/Views/Organization/Details.cshtml b/src/Web/Warden.Web/Views/Organization/Details.cshtml deleted file mode 100644 index 445f3dc..0000000 --- a/src/Web/Warden.Web/Views/Organization/Details.cshtml +++ /dev/null @@ -1,116 +0,0 @@ -@using Warden.Web.Core.Domain -@model global::Warden.Web.ViewModels.OrganizationViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" -@{ - var isOwner = Model.Owner.Id == Guid.Parse(User.Identity.Name); -} - -
-
-

Organization

-
-
- -
    -
  • @Model.Organization.Name
  • -
-
-
- -
    -
  • - @Model.Organization.Id -
  • -
-
-
- -
    -
  • @Model.Owner.Email
  • -
-
-
- -
    -
  • - @Model.Organization.AutoRegisterNewWarden -
  • -
-
-
-
-
-
Users (@Model.Organization.Users.Count())
-
- @foreach (var user in Model.Organization.Users) - { - - @user.Email [@user.Role] - - } -
-
-
-
-
-
Wardens (@Model.Organization.Wardens.Count())
-
- @foreach (var warden in Model.Organization.Wardens) - { - - @warden.Name - - } -
-
-
-
- - mode_edit - - -
-@Html.Partial("_DeleteOrganizationModal", Model.Organization.Id) - diff --git a/src/Web/Warden.Web/Views/Organization/Edit.cshtml b/src/Web/Warden.Web/Views/Organization/Edit.cshtml deleted file mode 100644 index cdcdd77..0000000 --- a/src/Web/Warden.Web/Views/Organization/Edit.cshtml +++ /dev/null @@ -1,24 +0,0 @@ -@model Warden.Web.ViewModels.EditOrganizationViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
Edit organization
-
-
-
- - - -
-
-
-
- -
-
-
-
-
-
diff --git a/src/Web/Warden.Web/Views/Organization/Index.cshtml b/src/Web/Warden.Web/Views/Organization/Index.cshtml deleted file mode 100644 index e421cb0..0000000 --- a/src/Web/Warden.Web/Views/Organization/Index.cshtml +++ /dev/null @@ -1,20 +0,0 @@ -@model Warden.Web.Core.Domain.PagedResult - -
-
-

Organizations (@Model.Items.Count())

-
-
- Create -
-
-
- @foreach (var organization in Model.Items) - { - - @organization.Name - - } -
-
-
\ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Organization/UserDetails.cshtml b/src/Web/Warden.Web/Views/Organization/UserDetails.cshtml deleted file mode 100644 index 3466a60..0000000 --- a/src/Web/Warden.Web/Views/Organization/UserDetails.cshtml +++ /dev/null @@ -1,45 +0,0 @@ -@using System.Threading.Tasks -@using Warden.Web.Core.Domain -@using Warden.Web.ViewModels -@model UserInOrganizationViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" -@{ - var isOwner = Model.OwnerId == Guid.Parse(User.Identity.Name); -} - -
-
-

User

-
-
-
- -
    -
  • @Model.User.Email
  • -
-
-
- -
    -
  • @Model.User.Id
  • -
-
-
- -
    -
  • @Model.User.Role
  • -
-
-
- @if (isOwner && Model.User.Role != OrganizationRole.Owner) - { - - } -
- -@Html.Partial("_DeleteUserModal", Model.OrganizationId) diff --git a/src/Web/Warden.Web/Views/Organization/_DeleteOrganizationModal.cshtml b/src/Web/Warden.Web/Views/Organization/_DeleteOrganizationModal.cshtml deleted file mode 100644 index 332aeeb..0000000 --- a/src/Web/Warden.Web/Views/Organization/_DeleteOrganizationModal.cshtml +++ /dev/null @@ -1,15 +0,0 @@ -@model Guid -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - - \ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Organization/_DeleteUserModal.cshtml b/src/Web/Warden.Web/Views/Organization/_DeleteUserModal.cshtml deleted file mode 100644 index 6921e58..0000000 --- a/src/Web/Warden.Web/Views/Organization/_DeleteUserModal.cshtml +++ /dev/null @@ -1,16 +0,0 @@ -@model Guid -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - - \ No newline at end of file diff --git a/src/Web/Warden.Web/Views/ResetPassword/Complete.cshtml b/src/Web/Warden.Web/Views/ResetPassword/Complete.cshtml deleted file mode 100644 index e80e2da..0000000 --- a/src/Web/Warden.Web/Views/ResetPassword/Complete.cshtml +++ /dev/null @@ -1,7 +0,0 @@ -
-
-
- Your password has been changed. -
-
-
\ No newline at end of file diff --git a/src/Web/Warden.Web/Views/ResetPassword/Initiate.cshtml b/src/Web/Warden.Web/Views/ResetPassword/Initiate.cshtml deleted file mode 100644 index dcc94be..0000000 --- a/src/Web/Warden.Web/Views/ResetPassword/Initiate.cshtml +++ /dev/null @@ -1,24 +0,0 @@ -@model Warden.Web.ViewModels.ResetPasswordViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
Reset password
-
-
-
- - - -
-
-
-
- -
-
-
-
-
-
diff --git a/src/Web/Warden.Web/Views/ResetPassword/SetNew.cshtml b/src/Web/Warden.Web/Views/ResetPassword/SetNew.cshtml deleted file mode 100644 index fcd232d..0000000 --- a/src/Web/Warden.Web/Views/ResetPassword/SetNew.cshtml +++ /dev/null @@ -1,32 +0,0 @@ -@model Warden.Web.ViewModels.SetNewPasswordViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
New password
-
-
- - -
- - - -
-
- - - -
-
-
-
-
- -
-
-
-
-
-
\ No newline at end of file diff --git a/src/Web/Warden.Web/Views/ResetPassword/Status.cshtml b/src/Web/Warden.Web/Views/ResetPassword/Status.cshtml deleted file mode 100644 index 8e57622..0000000 --- a/src/Web/Warden.Web/Views/ResetPassword/Status.cshtml +++ /dev/null @@ -1,7 +0,0 @@ -
-
-
- If the provided email address has been correct, we have sent you the instructions how to reset your password. -
-
-
\ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Settings/Index.cshtml b/src/Web/Warden.Web/Views/Settings/Index.cshtml deleted file mode 100644 index 00deb70..0000000 --- a/src/Web/Warden.Web/Views/Settings/Index.cshtml +++ /dev/null @@ -1,73 +0,0 @@ -@model Warden.Web.Core.Dto.UserDto -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-

Settings

-
-
- -
    -
  • @Model.Email
  • -
-
-
- -
    -
  • @Model.Id
  • -
-
-
- -
    -
  • @Model.Role
  • -
-
-
- - mode_edit - -
    -
  • https
  • -
  • -
    - -
    -
  • -
  • -
    - -
    -
  • -
-
-
-
-
-
API keys (@Model.ApiKeys.Count())
-
    - @foreach (var apiKey in Model.ApiKeys) - { -
  • -
    -
    - @apiKey -
    -
    - -
    - -
    -
  • - } -
-
-
-@Html.Partial("_DeletApiKeyModal") diff --git a/src/Web/Warden.Web/Views/Settings/Password.cshtml b/src/Web/Warden.Web/Views/Settings/Password.cshtml deleted file mode 100644 index 8d6e258..0000000 --- a/src/Web/Warden.Web/Views/Settings/Password.cshtml +++ /dev/null @@ -1,35 +0,0 @@ -@model Warden.Web.ViewModels.ChangePasswordViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
Change password
-
-
-
- - - -
-
- - - -
-
- - - -
-
-
-
-
- -
-
-
-
-
-
diff --git a/src/Web/Warden.Web/Views/Settings/_DeletApiKeyModal.cshtml b/src/Web/Warden.Web/Views/Settings/_DeletApiKeyModal.cshtml deleted file mode 100644 index e0c1ede..0000000 --- a/src/Web/Warden.Web/Views/Settings/_DeletApiKeyModal.cshtml +++ /dev/null @@ -1,15 +0,0 @@ -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - - \ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Shared/_Layout.cshtml b/src/Web/Warden.Web/Views/Shared/_Layout.cshtml deleted file mode 100644 index f11310f..0000000 --- a/src/Web/Warden.Web/Views/Shared/_Layout.cshtml +++ /dev/null @@ -1,55 +0,0 @@ -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" -@{ - var url = Context.Request.Path; -} - - - - Warden Web Panel - - - - - - - - - - - - - - - - - - - - - - - - - - - @RenderSection("head", false) - - - -@Html.Partial("_Nav") -
- @RenderBody() -
-@Html.Partial("_Notifications") - -@RenderSection("scripts", false) - - \ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Shared/_Nav.cshtml b/src/Web/Warden.Web/Views/Shared/_Nav.cshtml deleted file mode 100644 index eaede96..0000000 --- a/src/Web/Warden.Web/Views/Shared/_Nav.cshtml +++ /dev/null @@ -1,40 +0,0 @@ -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - - \ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Shared/_Notifications.cshtml b/src/Web/Warden.Web/Views/Shared/_Notifications.cshtml deleted file mode 100644 index 1fcbded..0000000 --- a/src/Web/Warden.Web/Views/Shared/_Notifications.cshtml +++ /dev/null @@ -1,38 +0,0 @@ -@using System.Threading.Tasks -@using Newtonsoft.Json -@using Warden.Web.Framework -@{ - var notificationsKey = "Notifications"; -} - - \ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Warden/Details.cshtml b/src/Web/Warden.Web/Views/Warden/Details.cshtml deleted file mode 100644 index 6d41768..0000000 --- a/src/Web/Warden.Web/Views/Warden/Details.cshtml +++ /dev/null @@ -1,118 +0,0 @@ -@using System.Threading.Tasks -@using Warden.Web.Extensions -@using Warden.Web.ViewModels -@model Warden.Web.ViewModels.WardenViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-

Warden

-
-
- -
    -
  • @Model.Stats.WardenName
  • -
-
-
- -
    -
  • @Model.Stats.TotalUptime.ToString("F")%
  • -
-
-
- -
    -
  • @Model.Stats.TotalDowntime.ToString("F")%
  • -
-
-
- -
    -
  • @Model.Stats.TotalValidIterations
  • -
-
-
- -
    -
  • @Model.Stats.TotalInvalidIterations
  • -
-
-
- Dashboard -
-
-
-
-
Watchers (@Model.Watchers.Count())
-
- @foreach (var watcher in Model.Watchers) - { - - @watcher.Name - - } -
-
-
- -
- - mode_edit - - -
-@Url.Paginate(Model.Iterations, "Details") -@Html.Partial("_DeleteWardenModal", Model.OrganizationId) diff --git a/src/Web/Warden.Web/Views/Warden/Edit.cshtml b/src/Web/Warden.Web/Views/Warden/Edit.cshtml deleted file mode 100644 index 66a7199..0000000 --- a/src/Web/Warden.Web/Views/Warden/Edit.cshtml +++ /dev/null @@ -1,24 +0,0 @@ -@model Warden.Web.ViewModels.EditWardenViewModel -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - -
-
-
-
Edit Warden
-
-
-
- - - -
-
-
-
- -
-
-
-
-
-
diff --git a/src/Web/Warden.Web/Views/Warden/Iteration.cshtml b/src/Web/Warden.Web/Views/Warden/Iteration.cshtml deleted file mode 100644 index aaabdad..0000000 --- a/src/Web/Warden.Web/Views/Warden/Iteration.cshtml +++ /dev/null @@ -1,109 +0,0 @@ -@using System.Threading.Tasks -@using Warden.Web.ViewModels -@model Warden.Web.ViewModels.WardenIterationViewModel - -
-
-
Iteration for @Model.Iteration.Results.Count() watchers by @Model.Iteration.WardenName
-
-
- -
    -
  • @Model.Iteration.CompletedAt
  • -
-
-
- -
    -
  • @Model.Iteration.Id
  • -
-
-
- -
    -
  • - @Model.Iteration.IsValid - @if (Model.Iteration.IsValid) - { - thumb_up - } - else - { - thumb_down - } -
  • -
-
-
- -
    -
  • @Model.Iteration.Results.Count(x => x.IsValid)
  • -
-
-
- -
    -
  • @Model.Iteration.Results.Count(x => !x.IsValid)
  • -
-
-
-@foreach (var result in Model.Iteration.Results.OrderBy(x => x.WatcherCheckResult.WatcherName)) -{ - var watcherName = result.WatcherCheckResult.WatcherName; -
-
- - - -
    -
  • @result.WatcherCheckResult.WatcherType
  • -
- -
    -
  • - @result.WatcherCheckResult.IsValid - @if (result.WatcherCheckResult.IsValid) - { - thumb_up - } - else - { - thumb_down - } -
  • -
- -
    -
  • @result.WatcherCheckResult.Description
  • -
- -
    -
  • @result.CompletedAt
  • -
- - @if (result.Exception == null) - { -
    -
  • ---
  • -
- } - else - { -
    -
  • -
    - info_outlineExpand -
    -
    @Html.Partial("_Exception", result.Exception)
    -
  • -
- } -
-
-} - - diff --git a/src/Web/Warden.Web/Views/Warden/_DeleteWardenModal.cshtml b/src/Web/Warden.Web/Views/Warden/_DeleteWardenModal.cshtml deleted file mode 100644 index 6d19d7c..0000000 --- a/src/Web/Warden.Web/Views/Warden/_DeleteWardenModal.cshtml +++ /dev/null @@ -1,16 +0,0 @@ -@model Guid -@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" - - \ No newline at end of file diff --git a/src/Web/Warden.Web/Views/Warden/_Exception.cshtml b/src/Web/Warden.Web/Views/Warden/_Exception.cshtml deleted file mode 100644 index bb7db4c..0000000 --- a/src/Web/Warden.Web/Views/Warden/_Exception.cshtml +++ /dev/null @@ -1,21 +0,0 @@ -@model Warden.Web.Core.Dto.ExceptionDto - - -
    -
  • @Model.Source
  • -
- -
    -
  • @Model.Message
  • -
- -
    -
  • @Model.StackTrace
  • -
-@if (Model.InnerException != null) -{ - -
    -
  • @Html.Partial("_Exception", Model.InnerException)
  • -
-} diff --git a/src/Web/Warden.Web/Views/Watcher/Details.cshtml b/src/Web/Warden.Web/Views/Watcher/Details.cshtml deleted file mode 100644 index f588b25..0000000 --- a/src/Web/Warden.Web/Views/Watcher/Details.cshtml +++ /dev/null @@ -1,65 +0,0 @@ -@using System.Threading.Tasks -@using Warden.Web.Extensions -@model Warden.Web.ViewModels.WatcherViewModel - -
-
-
Watcher: @Model.Stats.Name
-
-
-
- -
    -
  • @Model.Stats.Type
  • -
-
-
- -
    -
  • @Model.Stats.TotalUptime.ToString("F")%
  • -
-
-
- -
    -
  • @Model.Stats.TotalDowntime.ToString("F")%
  • -
-
-
- -
    -
  • @Model.Stats.TotalValidChecks
  • -
-
-
- -
    -
  • @Model.Stats.TotalInvalidChecks
  • -
-
-
-
-
-
Checks (@Model.Checks.TotalResults)
-
- @foreach (var check in Model.Checks.Items) - { - var watcherName = check.WatcherCheckResult.WatcherName; - - - Completed at: @check.CompletedAt - @if (check.IsValid) - { - thumb_up - } - else - { - thumb_down - } - - - } -
-
-
-@Url.Paginate(Model.Checks, "Details") \ No newline at end of file diff --git a/src/Web/Warden.Web/Views/_ViewStart.cshtml b/src/Web/Warden.Web/Views/_ViewStart.cshtml deleted file mode 100644 index efda124..0000000 --- a/src/Web/Warden.Web/Views/_ViewStart.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ - Layout = "~/Views/Shared/_Layout.cshtml"; -} \ No newline at end of file diff --git a/src/Web/Warden.Web/Warden.Web.csproj b/src/Web/Warden.Web/Warden.Web.csproj deleted file mode 100644 index f6d32a3..0000000 --- a/src/Web/Warden.Web/Warden.Web.csproj +++ /dev/null @@ -1,54 +0,0 @@ - - - - 1.3.1 - net461 - true - Warden.Web - Exe - Warden.Web - - - - - PreserveNewest - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Web/Warden.Web/config.development.json b/src/Web/Warden.Web/config.development.json deleted file mode 100644 index 7a73a41..0000000 --- a/src/Web/Warden.Web/config.development.json +++ /dev/null @@ -1,2 +0,0 @@ -{ -} \ No newline at end of file diff --git a/src/Web/Warden.Web/config.json b/src/Web/Warden.Web/config.json deleted file mode 100644 index 8597b89..0000000 --- a/src/Web/Warden.Web/config.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "account": { - "autoActivation": true - }, - "email": { - "enabled": false, - "apiKey": "", - "noReplyAccount": "", - "templates": [ - { - "id": "", - "name": "account-created", - "subject": "Account created" - }, - { - "id": "", - "name": "password-changed", - "subject": "Password changed" - }, - { - "id": "", - "name": "reset-password", - "subject": "Reset password", - "parameters": [ - { - "name": "url", - "values": [ "http://localhost:11223/reset-password/set-new" ] - } - ] - } - ] - }, - "feature": { - "maxApiKeys": 5, - "maxOrganizations": 3, - "maxUsersInOrganization": 5, - "maxWardensInOrganization": 5, - "maxWatchersInWarden": 10, - "retainWardenIterationDataDays": 1 - }, - "general": { - "connectionString": "mongodb://localhost:27017", - "database": "Warden", - "encrypterKey": "XYZ123", - "jsonFormatDate": "yyyy-MM-dd H:mm:ss", - "authCookieName": ".Warden", - "loginPath": "/login", - "logoutPath": "/logout" - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/config.production.json b/src/Web/Warden.Web/config.production.json deleted file mode 100644 index 9aa9f7b..0000000 --- a/src/Web/Warden.Web/config.production.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "general": { - "connectionString": "", - "database": "", - "encrypterKey": "" - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/config.staging.json b/src/Web/Warden.Web/config.staging.json deleted file mode 100644 index 9aa9f7b..0000000 --- a/src/Web/Warden.Web/config.staging.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "general": { - "connectionString": "", - "database": "", - "encrypterKey": "" - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/gulpfile.js b/src/Web/Warden.Web/gulpfile.js deleted file mode 100644 index 4f4ed17..0000000 --- a/src/Web/Warden.Web/gulpfile.js +++ /dev/null @@ -1,60 +0,0 @@ -/// -"use strict"; - -var gulp = require("gulp"), - sass = require('gulp-sass'), - rimraf = require("rimraf"), - concat = require("gulp-concat"), - cssmin = require("gulp-cssmin"), - uglify = require("gulp-uglify"), - ignore = require("gulp-ignore"), - util = require('gulp-util'); - -var paths = { - webroot: "./wwwroot/" -}; - -paths.js = paths.webroot + "content/js/*.js"; -paths.minJs = paths.webroot + "content/js/*.min.js"; -paths.css = paths.webroot + "content/css/*.css"; -paths.scss = paths.webroot + "content/css/*.scss"; -paths.minCss = paths.webroot + "content/css/*.min.css"; -paths.concatJsDest = paths.webroot + "content/js/site.min.js"; -paths.concatCssDest = paths.webroot + "content/css/site.min.css"; -paths.concatScssDest = paths.webroot + "content/css/"; - -gulp.task('sass-compile', function () { - gulp.src(paths.scss) - .pipe(sass()) - .pipe(gulp.dest(paths.concatScssDest)); -}); - -gulp.task("clean:js", function (cb) { - rimraf(paths.concatJsDest, cb); -}); - -gulp.task("clean:css", function (cb) { - rimraf(paths.concatCssDest, cb); -}); - -gulp.task("clean", ["clean:js", "clean:css"]); - -gulp.task("min:js", function () { - return gulp.src([paths.js, "!" + paths.minJs], { base: "." }) - .pipe(concat(paths.concatJsDest)) - .pipe(ignore.exclude(["**/*.map"])) - .pipe(uglify().on('error', util.log)) - .pipe(gulp.dest(".")); -}); - -gulp.task("min:css", function () { - return gulp.src([paths.css, "!" + paths.minCss]) - .pipe(concat(paths.concatCssDest)) - .pipe(cssmin()) - .pipe(gulp.dest(".")); -}); - -gulp.task("min", ["min:js", "min:css"]); - -gulp.task('default', ['sass-compile', 'clean', 'min'], function () { -}); \ No newline at end of file diff --git a/src/Web/Warden.Web/nlog.config b/src/Web/Warden.Web/nlog.config deleted file mode 100644 index 6610ecf..0000000 --- a/src/Web/Warden.Web/nlog.config +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/src/Web/Warden.Web/package.json b/src/Web/Warden.Web/package.json deleted file mode 100644 index 8ab6c7e..0000000 --- a/src/Web/Warden.Web/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "Warden.Web", - "version": "0.0.0", - "devDependencies": { - "gulp": "^3.9.1", - "gulp-concat": "^2.6.0", - "gulp-cssmin": "^0.1.7", - "gulp-uglify": "^1.5.3", - "gulp-sass": "^2.2.0", - "gulp-ignore": "^2.0.1", - "gulp-util": "^3.0.7", - "rimraf": "^2.5.2" - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/web.config b/src/Web/Warden.Web/web.config deleted file mode 100644 index e04a039..0000000 --- a/src/Web/Warden.Web/web.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/src/Web/Warden.Web/wwwroot/content/css/site.css b/src/Web/Warden.Web/wwwroot/content/css/site.css deleted file mode 100644 index 0226b87..0000000 --- a/src/Web/Warden.Web/wwwroot/content/css/site.css +++ /dev/null @@ -1,38 +0,0 @@ -body { - background-color: #FAFAFF; } - -nav { - color: #7272D8; - background-color: #7272D8; } - -.nav-wrapper > ul > li { - color: #7272D8; - background-color: #7272D8; } - -.custom { - background-color: #7272D8; } - -.custom-text { - color: #7272D8; } - -.collection .collection-item.active { - background-color: #ffffff; - color: #000000; } - -.field-validation-error { - color: #BF3131; } - -.progress { - background-color: #C8C8F7; } - -.progress .determinate { - background-color: #7272D8; } - -.progress .indeterminate { - background-color: #7272D8; } - -.btn:hover { - background-color: #9999E9; } - -.btn-floating:hover { - background-color: #9999E9; } diff --git a/src/Web/Warden.Web/wwwroot/content/css/site.min.css b/src/Web/Warden.Web/wwwroot/content/css/site.min.css deleted file mode 100644 index bbf2297..0000000 --- a/src/Web/Warden.Web/wwwroot/content/css/site.min.css +++ /dev/null @@ -1 +0,0 @@ -.custom-text,.nav-wrapper>ul>li,nav{color:#7272D8}body{background-color:#FAFAFF}.custom,.nav-wrapper>ul>li,nav{background-color:#7272D8}.collection .collection-item.active{background-color:#fff;color:#000}.field-validation-error{color:#BF3131}.progress{background-color:#C8C8F7}.progress .determinate,.progress .indeterminate{background-color:#7272D8}.btn-floating:hover,.btn:hover{background-color:#9999E9} \ No newline at end of file diff --git a/src/Web/Warden.Web/wwwroot/content/css/site.scss b/src/Web/Warden.Web/wwwroot/content/css/site.scss deleted file mode 100644 index d519626..0000000 --- a/src/Web/Warden.Web/wwwroot/content/css/site.scss +++ /dev/null @@ -1,60 +0,0 @@ -$primary-color: #7272D8; -$medium-color: #9999E9; -$light-color: #C8C8F7; -$background-color: #FAFAFF; -$error-color: #BF3131; - -body { - background-color: $background-color; -} - -nav { - color: $primary-color; - background-color: $primary-color; -} - -.nav-wrapper > ul > li { - color: $primary-color; - background-color: $primary-color; -} - -.custom { - background-color: $primary-color; -} - -.custom-text { - color: $primary-color; -} - -.collection .collection-item.active { - background-color: #ffffff; - color: #000000; -} - -.field-validation-error{ - color: $error-color; -} - -.progress { - background-color: $light-color; -} - -.progress .determinate { - background-color: $primary-color; -} - -.progress .indeterminate { - background-color: $primary-color; -} - -.btn { - &:hover { - background-color: $medium-color; - } -} - -.btn-floating { - &:hover { - background-color: $medium-color; - } -} \ No newline at end of file diff --git a/src/Web/Warden.Web/wwwroot/content/img/logo.png b/src/Web/Warden.Web/wwwroot/content/img/logo.png deleted file mode 100644 index 865d83f8c8ab4d3d9e319f064f5695c06efb490c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2972 zcmV;N3uE+&P)0021%1^@s6v8EuV00001b5ch_0Itp) z=>Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02p*dSaefwW^{L9 za%BK;VQFr3E^cLXAT%y8E;(#7eog=Y3k^v`K~#8N?VWwlR8<|veM3>xL_kA}9A9#@ zR4B_VoYK;oDa%TvGV`Tz6dRq4bWA71KQyq!HzX}8ErdczK_Y?-1;k2oQqnY1Brz>V zvV7NsKHuMd?`@WB?)ogx`OJLhob&tr&N=sa&e^?t-_G46k=Q6%w{G30YuB#b z3mr>-0_hEC3HoiBmZ90`GITO=Bhcn1c%}QLCW6C(#9Dhq$Xm;{Px)HfMsIf}V&O(c6#5mHkR9O7N%R*O^exe~nh38qOu|KIM{inUV}~)< zfyS>&!{0Yxd+tZOcoP#FD-7~hXrafwPr-IQgm(6(CN?%0W1ZXkX=%9I4}JX;-Rok# z+)bTry~&A<2?q8&53(l59q8vSwguXsN;1AwYKWQMIoKXS^U+o|#rZ+Xua&02hCw@bp_^O` zDC;Lc-4OpFZ(5=oVE`wg*)HZVwmKr#H{cs=3MdcPz_$WVwr5JEC_juYbFnUnU+PUu zbQ=ub_ULg`ae|kz9e^r+V-b5$jC_ls-IviBXe4^n=DHyMz23Y;H^IQ2iq3PfE{Ol6 z$Gzpywtg2r;9?_O>&;7a6Abpv3|^02Y;REKl+u{@9oVM-psl@$iEe-a8;UM;v2LjI z4Uc=Dg6+yrA0@f~2J9HLhl_PXohy)zntzX`BHgZaJi6U;;dO!juk!)_*#XbvXeCp?)NhPq?iOd`=7Oro!O zJ~hJ$ZYGgv4kq9=o=nYZS+T6V1aM+JQ;5 zwltj@hpPLysYIf2m_Rx=*c8;&3GE)|6cdTMVe;tS#D_hf8iu;d-Bcpc7)+j>(PGb~ zrl9^cZZ46i59ZBqCeB3C{I>iJV6>Y}Bx=K?I}pu44Lu871nuZ?()_8tM4|%bi5_w~ z0^M4gHm!p;Z*(__L{FF>T4CWcq<6<`X#<+r?kro?HV2e-mP5WtHnk5nQV$?4 zAniExt6R2ezUGUVSmT;>wN0|^DO)+%-fFl0rZ`f^w$i3Th?%C?49Z&PW}w}L5T`{s z3&B6%p;f_ug+r@?{}Ga!k3SGob9p`dJ2|um*mb!yzgdLr)piAx&$oTCP3?nD8d^lC zRnV_K?Y(}=iP5SLiZ7plU$sr2`gq|E>Av>qLH$_ui}doSPyqg2k$wV*2~JgSq(cfJ zChm76)i;;c!O_}???Zo#MoJ8Fcm>4GQvm66=wNgZIuy-{nm~S>!z;kOdnqd7^iBLF zbYhvl=+FxAjdaz3^1n#(4;|&$8zXv5fD~`D z?OYU(f0DjiKGM&rEXW@g6$-$Akwc#$za5J84M~r6NFl_;d-X^c*c4EnBD)}8_yNQB z7suRdQ-EnV*#*8CHdlb}qYhJCL#xbEWpt@#)V;@P{u~bZCAQsaQ+uF;_$KKj^tl?< zeZL=7;vFZdr!wha6dxMW15gYke9-G#coP-rlO$D-?6K?N|M=!5on>=Cd8q7y{4F+DfbYu=6Ae8@NZqfi5~(=T z`FVEBA7?;Fe`r&Cpo4F#qfSA8_o4i^T0Ibdwd-aRFzz)ZT}7hHf;xe%^2c3{JF!Wp zMFR!kAL}@g?Y@6$+szSF0RFctPLRI^X<3u6P@Gw^2In}u0(|AW&mIRol=rnuzUytS z0N3h?zd0b~6i(pVIfbhgW9q5OYH{+OuHF6d(jYQ-&7 zh44o_g?jx>RRndv<#u#_Qm2cab@?OqFLn7OlpUPBgbGiC;M2EdK>h`!ZIoWHt>%$1 z{&9*E)}=6};(dEwPw{4M+MU+T&MEtz-r`lZsz5^5^$WJEG8a5%ykiWgEyuB zu&XoBr*_A>y6}`Xpb@B}bq42>JpncRJFgbBdxra1gW@tF>G5{UALq?Tmpj$+z=bbE z#FrfVi+ z|84(GHuV6zc30VHpdQb!P|iL~Wys9bO1AH@Hd#_zM3A_|9^e zDE~j|Cq#UR1^M=#g6S6cM`*y0M!F|)EIOS3&l@vQ-W%!KuY5{%6qozgla`TFoOECn zzuNnP{bQ>6ktT7pL4H)Z51ZadpS7>64dwN+7+tB+2Uj0(?Qt%#CL+CEVE^^&6lf5! zdO?tmT+c?jgGu#uMdYw5@gaQra?$o_jqvq-x}qbW{*Sswo?a%I=xc1U$^QUOW{{@r S 0; - }); - return failingResources.slice(0, 3); - }); - self.iterations = ko.observableArray([]); - self.selectedWardenCheckResult = ko.observable(new WardenCheckResult(createEmptyWardenCheckResult())); - self.totalValidIterations = ko.observable(0); - self.totalInvalidIterations = ko.observable(0); - self.totalIterations = ko.computed(function() { - return self.totalValidIterations() + self.totalInvalidIterations(); - }); - - self.totalIterationsFormatted = ko.computed(function() { - - var validIterations = self.totalValidIterations(); - var invalidIterations = self.totalInvalidIterations(); - var totalIterations = self.totalIterations(); - - return totalIterations + - " (" + - validIterations + - " valid, " + - invalidIterations + - " invalid)."; - }); - - self.setIterationDetails = function(iteration) { - self.latestCheckAt(iteration.completedAt); - updateResourcesInfo(iteration); - updateCharts(iteration); - }; - - function setStats(stats) { - self.totalUptime(stats.totalUptime); - self.totalDowntime(stats.totalDowntime); - self.totalValidIterations(stats.totalValidIterations); - self.totalInvalidIterations(stats.totalInvalidIterations); - self.failingResources([]); - stats.watchers.forEach(function(watcher) { - var watcherStats = new WatcherItem(watcher); - self.failingResources.push(watcherStats); - }); - - self.failingResources.sort(function(left, right) { return left.totalDowntime() < right.totalDowntime() }); - }; - - self.changeWarden = function() { - var selectedOrganizationId = self.selectedOrganization().id(); - var selectedWardenId = self.selectedWarden().id(); - window.location = "/dashboards/organizations/" + selectedOrganizationId + "/wardens/" + selectedWardenId; - }; - - function updateResourcesInfo(iteration) { - var validResults = iteration.results.filter(function(result) { - return result.isValid; - }); - - self.validResources(validResults.length); - self.invalidResources(iteration.results.length); - } - - function setDefaultWarden() { - self.organizations.remove(function(organization) { - return organization.name() === ""; - }); - - var selectedOrganization = self.organizations() - .filter(function(organization) { - return organization.id() === organizationId; - })[0]; - - var selectedWarden = selectedOrganization.wardens() - .filter(function(warden) { - return warden.name() === wardenName; - })[0]; - self.selectedOrganization(selectedOrganization); - self.selectedWarden(selectedWarden); - }; - - - //TODO: Push from server side. - function refreshStats() { - getStats() - .then(function(stats) { - setStats(stats); - }); - }; - - refreshStats(); - setInterval(refreshStats, refreshStatsIntervalSeconds * 1000); - - getOrganizations() - .then(function(organizations) { - organizations.forEach(function(organization) { - self.organizations.push(new Organization(organization)); - }); - setDefaultWarden(); - $('select').material_select(); - }); - - getIterations() - .then(function(iterations) { - if (iterations.length === 0) { - displayDashboard(); - renderEmptyIterationsChart(); - renderEmptyWatchersChart(); - - return; - } - - var latestIteration = iterations[0]; - self.iterations(iterations); - displayDashboard(); - renderIterationsChart(); - renderWatchersChart(latestIteration); - self.setIterationDetails(latestIteration); - }); - - function updateCharts(iteration) { - if (self.shouldUpdateIterationsChart()) { - var removeFirstIteration = self.iterations().length >= 10; - addNewIterationToiterationsChart(iteration, removeFirstIteration); - }; - renderWatchersChart(iteration); - }; - - function displayDashboard() { - $("#loader").addClass("hide"); - $("#dashboard").removeClass("hide"); - }; - - function renderEmptyIterationsChart() { - var data = { - labels: [], - datasets: [ - { - label: "Warden", - fillColor: resources.colors.green, - strokeColor: resources.colors.grey, - pointColor: resources.colors.grey, - pointStrokeColor: resources.colors.white, - pointHighlightFill: resources.colors.white, - pointHighlightStroke: resources.colors.grey, - data: [0] - } - ] - }; - - var options = { - responsive: true - }; - iterationsChart = new Chart(iterationsChartContext).Line(data, options); - }; - - function addNewIterationToiterationsChart(iteration, removeFirstIteration) { - var validResults = iteration.results.filter(function(result) { - return result.isValid; - }); - var point = validResults.length; - var label = iteration.completedAt; - if (removeFirstIteration) { - iterationsChart.removeData(); - } - iterationsChart.addData([point], label); - }; - - function renderIterationsChart() { - var labels = []; - var points = []; - self.iterations() - .forEach(function(iteration) { - labels.push(iteration.completedAt); - var validResults = iteration.results.filter(function(result) { - return result.isValid; - }); - points.push(validResults.length); - }); - - var options = { - scaleOverride: true, - scaleSteps: totalWatchers, - scaleStepWidth: 1, - scaleStartValue: 0, - responsive: true - }; - - var data = { - labels: labels, - datasets: [{ - label: "Warden", - fillColor: resources.colors.green, - strokeColor: resources.colors.grey, - pointColor: resources.colors.grey, - pointStrokeColor: resources.colors.white, - pointHighlightFill: resources.colors.white, - pointHighlightStroke: resources.colors.grey, - data: points - } - ] - } - - iterationsChart = new Chart(iterationsChartContext).Line(data, options); - - $iterationsChart.click(function(evt) { - var point = iterationsChart.getPointsAtEvent(evt)[0]; - var completedAt = point.label; - var iteration = self.iterations() - .filter(function(iteration) { - return iteration.completedAt === completedAt; - })[0]; - var url = "/organizations/" + - organizationId + - "/wardens/" + - wardenId + - "/iterations/" + - iteration.id; - window.open(url, '_blank'); - }); - }; - - function renderEmptyWatchersChart() { - var data = []; - data.push({ - value: 1, - color: resources.colors.lightGrey, - highlight: resources.colors.lightGreyHighlight, - label: "Missing data" - }); - - var options = { - responsive: true - }; - watchersChart = new Chart(watchersChartContext).Pie(data, options); - }; - - function renderWatchersChart(iteration) { - if (!self.shouldUpdateWatchersChart()) { - return; - } - - var invalidResults = iteration.results.filter(function(result) { - return !result.isValid; - }); - var validResults = iteration.results.filter(function(result) { - return result.isValid; - }); - var data = []; - var labels = []; - currentWardenCheckResults = []; - iteration.results.forEach(function(result) { - currentWardenCheckResults.push(result); - labels.push(result.watcherCheckResult.watcherName); - }); - invalidResults.forEach(function(result) { - data.push({ - value: 1, - color: resources.colors.red, - highlight: resources.colors.redHighlight, - label: result.watcherCheckResult.watcherName - }); - }); - - validResults.forEach(function(result) { - data.push({ - value: 1, - color: resources.colors.green, - highlight: resources.colors.greenHighlight, - label: result.watcherCheckResult.watcherName - }); - }); - - var options = { - responsive: true - }; - - watchersChart = new Chart(watchersChartContext).Pie(data, options); - - $watchersChart.click(function(evt) { - var segment = watchersChart.getSegmentsAtEvent(evt)[0]; - var watcherName = segment.label; - var wardenCheckResult = currentWardenCheckResults.filter(function(result) { - return result.watcherCheckResult.watcherName === watcherName; - })[0]; - self.selectedWardenCheckResult(new WardenCheckResult(wardenCheckResult)); - }); - }; - }; - - function createEmptyOrganization() { - return new Organization({ - id: "", - name: "", - wardens: [] - }); - }; - - function createEmptyWardenCheckResult() { - return { - completedAt: "---", - watcherCheckResult: { - watcherName: "---", - watcherType: "---", - description: "---", - isValid: "---" - } - }; - }; - - function Organization(organization) { - var self = this; - self.id = ko.observable(organization.id); - self.name = ko.observable(organization.name); - self.wardens = ko.observableArray([]); - organization.wardens.forEach(function(warden) { - self.wardens.push(new WardenItem(warden)); - }); - }; - - function WardenItem(warden) { - var self = this; - self.id = ko.observable(warden.id); - self.name = ko.observable(warden.name); - self.enabled = ko.observable(warden.name); - }; - - function WatcherItem(watcher) { - var self = this; - self.name = ko.observable(watcher.name); - self.type = ko.observable(watcher.type); - self.totalDowntime = ko.observable(watcher.totalDowntime); - self.totalUptime = ko.observable(watcher.totalUptime); - self.url = ko.computed(function() { - return "/organizations/" + organizationId + "/wardens/" + wardenId + "/watchers/" + self.name(); - }); - self.infoFormatted = ko.computed(function() { - return self.name() + " (" + self.totalDowntime().toFixed(2) + "%" + ")"; - }); - }; - - function WardenCheckResult(result) { - var self = this; - self.watcherName = ko.observable(result.watcherCheckResult.watcherName); - self.watcherType = ko.observable(result.watcherCheckResult.watcherType); - self.isValid = ko.observable(result.watcherCheckResult.isValid); - self.description = ko.observable(result.watcherCheckResult.description); - self.completedAt = ko.observable(result.completedAt); - self.exception = ko.observable(result.exception); - self.url = ko.computed(function() { - return "/organizations/" + organizationId + "/wardens/" + wardenId + "/watchers/" + self.watcherName(); - }); - self.exceptionFormatted = ko.computed(function() { - if (!self.exception()) - return "---"; - - return getExceptionDetails(self.exception()); - }); - - - function getExceptionDetails(exception) { - if (!exception) - return ""; - - var innerException = getExceptionDetails(exception.innerException); - var innerExceptionMessage = ""; - if (innerException) - innerExceptionMessage = "


*Inner exception*

" + innerException; - - return "Source:
" + - exception.source + - "

Message:
" + - exception.message + - "

Stack trace:
" + - exception.stackTraceString + - innerExceptionMessage; - }; - }; - - function getStats() { - var endpoint = organizationId + '/wardens/' + wardenName + '/stats'; - return getDataFromApi(endpoint); - }; - - function getIterations() { - var endpoint = organizationId + '/wardens/' + wardenName + '/iterations'; - - return getDataFromApi(endpoint, { results: 10 }); - }; - - function getOrganizations() { - return getDataFromApi(); - }; - - function getDataFromApi(endpoint, params) { - return $.ajax({ - url: '/api/organizations/' + (endpoint || ""), - headers: { - "X-Api-Key": apiKey - }, - method: 'GET', - data: params, - success: function(response) { - return response; - } - }); - }; - - function initWardenHub() { - $.connection.hub.qs = { organizationId: organizationId, wardenName: wardenName }; - var chat = $.connection.wardenHub; - chat.client.iterationCreated = function(iteration) { - iteration = toCamelCase(iteration); - viewModel.setIterationDetails(iteration); - viewModel.iterations.push(iteration); - if (iteration.isValid) { - viewModel.totalValidIterations(viewModel.totalValidIterations() + 1); - } else { - viewModel.totalInvalidIterations(viewModel.totalInvalidIterations() + 1); - } - }; - - connect(); - - $.connection.hub.disconnected(function() { - var reason = ""; - if ($.connection.hub.lastError) { - reason = " Reason: " + $.connection.hub.lastError.message; - } - - Materialize.toast("Connection has been lost, reconnecting in 3 seconds." + reason, 3000, resources.css.lightRed); - setTimeout(connect, 3000); - }); - - $.connection.hub.reconnected(function () { - Materialize.toast("Reconnection has succeeded.", 3000, resources.css.lightGreen); - }); - - function connect() { - Materialize.toast("Connecting to the Warden Hub.", 3000, resources.css.lightBlue); - $.connection.hub.start() - .done(function() { - Materialize.toast("Connection has been established.", 3000, resources.css.lightGreen); - }) - .fail(function() { - Materialize.toast("Connection could not have been established.", 3000, resources.css.lightRed); - }); - }; - }; - - ////SignalR camelCase JSON resolver does not seem to be working - temporary workaround. - function toCamelCase(o) { - var build, key, destKey, value; - - if (o instanceof Array) { - build = []; - for (key in o) { - value = o[key]; - - if (typeof value === "object") { - value = toCamelCase(value); - } - build.push(value); - } - } else { - build = {}; - for (key in o) { - if (o.hasOwnProperty(key)) { - destKey = (key.charAt(0).toLowerCase() + key.slice(1) || key).toString(); - value = o[key]; - if (value !== null && typeof value === "object") { - value = toCamelCase(value); - } - - build[destKey] = value; - } - } - } - return build; - }; - - return { - init: init - }; -})(); \ No newline at end of file diff --git a/src/Web/Warden.Web/wwwroot/content/js/site.min.js b/src/Web/Warden.Web/wwwroot/content/js/site.min.js deleted file mode 100644 index 7a70155..0000000 --- a/src/Web/Warden.Web/wwwroot/content/js/site.min.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";var app=function(){function e(e){$("nav,#nav-mobile").find("li").removeClass("active");var t=$("nav,#nav-mobile").find('a[href^="'+e+'"]');t.parent().addClass("active"),t.parent().parent().parent().addClass("active")}function t(){$("[data-block]").on("submit",function(e){$(this).validate();var t=$(this).valid();if(t){var o=$(document).find("[type=submit]");o.addClass("disabled"),o.attr("readonly","readonly"),o.prop("disabled",!0)}})}function o(){$("input[type=checkbox]").each(function(){var e="True"===$(this).data("checked");e&&($(this).prop("checked",!0),$(this).val(!0))}),$("input[type=checkbox]").click(function(){$(this).val($(this).is(":checked"))})}function a(){function e(e){window.prompt("Copy to clipboard: Ctrl+C, Enter",e)}$("[data-clipboard]").click(function(){e($(this).data("clipboard"))})}function n(){$(".modal-trigger").leanModal(),$("[data-remove-api-key]").click(function(){$("#api-key-to-delete").val($(this).data("api-key"))}),$("[data-remove-user-from-organization]").click(function(){$("#user-id-to-delete").val($(this).data("user-id"))}),$("[data-remove-warden-from-organization]").click(function(){$("#warden-id-to-delete").val($(this).data("warden-id"))})}var r="",i="",s="",l=function(l){r=l.loginPath||"/login",i=l.logoutPath||"/logout",s=l.url||"/";var c="/"+s.split("/")[1];e(c),t(),o(),n(),a(),$(".tooltipped").tooltip({delay:50}),$(".button-collapse").sideNav()};return{init:l}}(),dashboard=function(){function e(){function e(e){W.totalUptime(e.totalUptime),W.totalDowntime(e.totalDowntime),W.totalValidIterations(e.totalValidIterations),W.totalInvalidIterations(e.totalInvalidIterations),W.failingResources([]),e.watchers.forEach(function(e){var t=new r(e);W.failingResources.push(t)}),W.failingResources.sort(function(e,t){return e.totalDowntime()=10;y(e,t)}A(e)}function v(){$("#loader").addClass("hide"),$("#dashboard").removeClass("hide")}function k(){var e={labels:[],datasets:[{label:"Warden",fillColor:I.colors.green,strokeColor:I.colors.grey,pointColor:I.colors.grey,pointStrokeColor:I.colors.white,pointHighlightFill:I.colors.white,pointHighlightStroke:I.colors.grey,data:[0]}]},t={responsive:!0};x=new Chart(V).Line(e,t)}function y(e,t){var o=e.results.filter(function(e){return e.isValid}),a=o.length,n=e.completedAt;t&&x.removeData(),x.addData([a],n)}function R(){var e=[],t=[];W.iterations().forEach(function(o){e.push(o.completedAt);var a=o.results.filter(function(e){return e.isValid});t.push(a.length)});var o={scaleOverride:!0,scaleSteps:m,scaleStepWidth:1,scaleStartValue:0,responsive:!0},a={labels:e,datasets:[{label:"Warden",fillColor:I.colors.green,strokeColor:I.colors.grey,pointColor:I.colors.grey,pointStrokeColor:I.colors.white,pointHighlightFill:I.colors.white,pointHighlightStroke:I.colors.grey,data:t}]};x=new Chart(V).Line(a,o),w.click(function(e){var t=x.getPointsAtEvent(e)[0],o=t.label,a=W.iterations().filter(function(e){return e.completedAt===o})[0],n="/organizations/"+f+"/wardens/"+g+"/iterations/"+a.id;window.open(n,"_blank")})}function z(){var e=[];e.push({value:1,color:I.colors.lightGrey,highlight:I.colors.lightGreyHighlight,label:"Missing data"});var t={responsive:!0};E=new Chart(D).Pie(e,t)}function A(e){if(W.shouldUpdateWatchersChart()){var t=e.results.filter(function(e){return!e.isValid}),o=e.results.filter(function(e){return e.isValid}),a=[],n=[];U=[],e.results.forEach(function(e){U.push(e),n.push(e.watcherCheckResult.watcherName)}),t.forEach(function(e){a.push({value:1,color:I.colors.red,highlight:I.colors.redHighlight,label:e.watcherCheckResult.watcherName})}),o.forEach(function(e){a.push({value:1,color:I.colors.green,highlight:I.colors.greenHighlight,label:e.watcherCheckResult.watcherName})});var r={responsive:!0};E=new Chart(D).Pie(a,r),C.click(function(e){var t=E.getSegmentsAtEvent(e)[0],o=t.label,a=U.filter(function(e){return e.watcherCheckResult.watcherName===o})[0];W.selectedWardenCheckResult(new i(a))})}}var W=this,U=[];w=$("#iterations-chart"),C=$("#watchers-chart");var V=w[0].getContext("2d"),D=C[0].getContext("2d"),x=null,E=null;W.shouldUpdateIterationsChart=ko.observable(!0),W.shouldUpdateWatchersChart=ko.observable(!0),W.toggleUpdateIterationsChart=function(){var e=W.shouldUpdateIterationsChart(),t="Iterations chart updates have been ";t+=e?"paused.":"resumed.",Materialize.toast(t,3e3,I.css.lightBlue),W.shouldUpdateIterationsChart(!e)},W.toggleUpdateWatchersChart=function(){var e=W.shouldUpdateWatchersChart(),t="Watchers chart updates have been ";t+=e?"paused.":"resumed.",Materialize.toast(t,3e3,I.css.lightBlue),W.shouldUpdateWatchersChart(!e)},W.organizations=ko.observableArray([t()]),W.selectedOrganization=ko.observable(),W.selectedWarden=ko.observable(),W.selectedOrganization.subscribe(function(e){}),W.selectedWarden.subscribe(function(e){$("select").material_select()}),W.totalUptime=ko.observable(0),W.totalUptimeFormatted=ko.computed(function(){return W.totalUptime().toFixed(2)+"%"}),W.totalDowntime=ko.observable(0),W.totalDowntimeFormatted=ko.computed(function(){return W.totalDowntime().toFixed(2)+"%"}),W.validResources=ko.observable(0),W.invalidResources=ko.observable(0),W.totalResourcesFormatted=ko.computed(function(){return W.validResources()+" of "+W.invalidResources()+" watcher(s) returned valid result(s)."}),W.latestCheckAt=ko.observable("---"),W.latestCheckAtFormatted=ko.computed(function(){return W.latestCheckAt()}),W.failingResources=ko.observableArray([]),W.mostFailingResources=ko.computed(function(){var e=W.failingResources().filter(function(e){return e.totalDowntime()>0});return e.slice(0,3)}),W.iterations=ko.observableArray([]),W.selectedWardenCheckResult=ko.observable(new i(o())),W.totalValidIterations=ko.observable(0),W.totalInvalidIterations=ko.observable(0),W.totalIterations=ko.computed(function(){return W.totalValidIterations()+W.totalInvalidIterations()}),W.totalIterationsFormatted=ko.computed(function(){var e=W.totalValidIterations(),t=W.totalInvalidIterations(),o=W.totalIterations();return o+" ("+e+" valid, "+t+" invalid)."}),W.setIterationDetails=function(e){W.latestCheckAt(e.completedAt),n(e),h(e)},W.changeWarden=function(){var e=W.selectedOrganization().id(),t=W.selectedWarden().id();window.location="/dashboards/organizations/"+e+"/wardens/"+t},d(),setInterval(d,1e3*p),c().then(function(e){e.forEach(function(e){W.organizations.push(new a(e))}),u(),$("select").material_select()}),l().then(function(e){if(0===e.length)return v(),k(),void z();var t=e[0];W.iterations(e),v(),R(),A(t),W.setIterationDetails(t)})}function t(){return new a({id:"",name:"",wardens:[]})}function o(){return{completedAt:"---",watcherCheckResult:{watcherName:"---",watcherType:"---",description:"---",isValid:"---"}}}function a(e){var t=this;t.id=ko.observable(e.id),t.name=ko.observable(e.name),t.wardens=ko.observableArray([]),e.wardens.forEach(function(e){t.wardens.push(new n(e))})}function n(e){var t=this;t.id=ko.observable(e.id),t.name=ko.observable(e.name),t.enabled=ko.observable(e.name)}function r(e){var t=this;t.name=ko.observable(e.name),t.type=ko.observable(e.type),t.totalDowntime=ko.observable(e.totalDowntime),t.totalUptime=ko.observable(e.totalUptime),t.url=ko.computed(function(){return"/organizations/"+f+"/wardens/"+g+"/watchers/"+t.name()}),t.infoFormatted=ko.computed(function(){return t.name()+" ("+t.totalDowntime().toFixed(2)+"%)"})}function i(e){function t(e){if(!e)return"";var o=t(e.innerException),a="";return o&&(a="


*Inner exception*

"+o),"Source:
"+e.source+"

Message:
"+e.message+"

Stack trace:
"+e.stackTraceString+a}var o=this;o.watcherName=ko.observable(e.watcherCheckResult.watcherName),o.watcherType=ko.observable(e.watcherCheckResult.watcherType),o.isValid=ko.observable(e.watcherCheckResult.isValid),o.description=ko.observable(e.watcherCheckResult.description),o.completedAt=ko.observable(e.completedAt),o.exception=ko.observable(e.exception),o.url=ko.computed(function(){return"/organizations/"+f+"/wardens/"+g+"/watchers/"+o.watcherName()}),o.exceptionFormatted=ko.computed(function(){return o.exception()?t(o.exception()):"---"})}function s(){var e=f+"/wardens/"+b+"/stats";return u(e)}function l(){var e=f+"/wardens/"+b+"/iterations";return u(e,{results:10})}function c(){return u()}function u(e,t){return $.ajax({url:"/api/organizations/"+(e||""),headers:{"X-Api-Key":v},method:"GET",data:t,success:function(e){return e}})}function d(){function e(){Materialize.toast("Connecting to the Warden Hub.",3e3,I.css.lightBlue),$.connection.hub.start().done(function(){Materialize.toast("Connection has been established.",3e3,I.css.lightGreen)}).fail(function(){Materialize.toast("Connection could not have been established.",3e3,I.css.lightRed)})}$.connection.hub.qs={organizationId:f,wardenName:b};var t=$.connection.wardenHub;t.client.iterationCreated=function(e){e=h(e),k.setIterationDetails(e),k.iterations.push(e),e.isValid?k.totalValidIterations(k.totalValidIterations()+1):k.totalInvalidIterations(k.totalInvalidIterations()+1)},e(),$.connection.hub.disconnected(function(){var t="";$.connection.hub.lastError&&(t=" Reason: "+$.connection.hub.lastError.message),Materialize.toast("Connection has been lost, reconnecting in 3 seconds."+t,3e3,I.css.lightRed),setTimeout(e,3e3)}),$.connection.hub.reconnected(function(){Materialize.toast("Reconnection has succeeded.",3e3,I.css.lightGreen)})}function h(e){var t,o,a,n;if(e instanceof Array){t=[];for(o in e)n=e[o],"object"==typeof n&&(n=h(n)),t.push(n)}else{t={};for(o in e)e.hasOwnProperty(o)&&(a=(o.charAt(0).toLowerCase()+o.slice(1)||o).toString(),n=e[o],null!==n&&"object"==typeof n&&(n=h(n)),t[a]=n)}return t}var f="",b="",g="",v="",p=0,m=0,k=null,w=null,C=null,I={colors:{green:"rgba(91, 187, 22, 0.2)",greenHighlight:"rgba(91, 187, 22, 0.5)",red:"rgba(247, 70, 74, 0.5)",redHighlight:"rgba(247, 70, 74, 0.8)",grey:"rgba(220,220,220,1)",lightGrey:"rgba(75, 74, 73, 0.1)",lightGreyHighlight:"rgba(75, 74, 73, 0.2)",white:"#fff"},css:{lightBlue:"blue lighten-1",lightGreen:"green lighten-1",lightRed:"red lighten-1"}},y=function(t){f=t.organizationId||"",b=t.wardenName||"",g=t.wardenId||"",v=t.apiKey||"",m=t.totalWatchers||0,p=t.refreshStatsIntervalSeconds||60,k=new e,ko.applyBindings(k),d()};return{init:y}}(); \ No newline at end of file diff --git a/src/Tests/Warden.Tests/Core/WardenTests.cs b/tests/Warden.Tests/Core/WardenTests.cs similarity index 100% rename from src/Tests/Warden.Tests/Core/WardenTests.cs rename to tests/Warden.Tests/Core/WardenTests.cs diff --git a/src/Tests/Warden.Tests/Properties/AssemblyInfo.cs b/tests/Warden.Tests/Properties/AssemblyInfo.cs similarity index 100% rename from src/Tests/Warden.Tests/Properties/AssemblyInfo.cs rename to tests/Warden.Tests/Properties/AssemblyInfo.cs diff --git a/src/Tests/Warden.Tests.EndToEnd/Properties/launchSettings.json b/tests/Warden.Tests/Properties/launchSettings.json similarity index 100% rename from src/Tests/Warden.Tests.EndToEnd/Properties/launchSettings.json rename to tests/Warden.Tests/Properties/launchSettings.json diff --git a/src/Integrations/Warden.Integrations.Twilio/Warden.Integrations.Twilio.csproj b/tests/Warden.Tests/Warden.Tests.csproj similarity index 53% rename from src/Integrations/Warden.Integrations.Twilio/Warden.Integrations.Twilio.csproj rename to tests/Warden.Tests/Warden.Tests.csproj index b72cb23..4c9589b 100644 --- a/src/Integrations/Warden.Integrations.Twilio/Warden.Integrations.Twilio.csproj +++ b/tests/Warden.Tests/Warden.Tests.csproj @@ -1,12 +1,12 @@  - - Warden integration with Twilio. - 1.3.1 + Warden tests. + 2.0-beta-1 Piotr Gankiewicz - net461 - Warden.Integrations.Twilio - Warden.Integrations.Twilio + netcoreapp2.0 + Warden.Tests + Warden.Tests + true Warden https://getwarden.net https://github.com/warden-stack/Warden/blob/master/LICENSE @@ -17,22 +17,14 @@ false false - - + + + + + - - + - - - - - - - - - - - + \ No newline at end of file From 3c35eccaff5cead62aefecbca711a832893a4d37 Mon Sep 17 00:00:00 2001 From: Piotr Gankiewicz Date: Thu, 15 Feb 2018 16:36:37 +0100 Subject: [PATCH 6/9] Closed #150 .netstandard2.0 migration --- src/Warden/Warden.csproj | 5 ++--- tests/Warden.Tests/Warden.Tests.csproj | 8 ++++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/Warden/Warden.csproj b/src/Warden/Warden.csproj index 6c8eb18..1928d1a 100644 --- a/src/Warden/Warden.csproj +++ b/src/Warden/Warden.csproj @@ -1,11 +1,11 @@  - Warden is an open source library built to solve the problem of monitoring the resources. - 2.0.0-beta-1 + 2.0.0 Piotr Gankiewicz netstandard2.0 Warden + Warden Warden Warden https://getwarden.net @@ -17,5 +17,4 @@ false false - diff --git a/tests/Warden.Tests/Warden.Tests.csproj b/tests/Warden.Tests/Warden.Tests.csproj index 4c9589b..e00280a 100644 --- a/tests/Warden.Tests/Warden.Tests.csproj +++ b/tests/Warden.Tests/Warden.Tests.csproj @@ -1,7 +1,7 @@  Warden tests. - 2.0-beta-1 + 2.0.0 Piotr Gankiewicz netcoreapp2.0 Warden.Tests @@ -17,6 +17,9 @@ false false + + + @@ -24,7 +27,4 @@ - - - \ No newline at end of file From 0e443ba7f8c74593f73a8f61179174e005aa5b5b Mon Sep 17 00:00:00 2001 From: Piotr Gankiewicz Date: Fri, 16 Feb 2018 14:52:46 +0100 Subject: [PATCH 7/9] Updated docs --- README.md | 64 +++++++++++++++++-------------------------------------- 1 file changed, 19 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index b72a5f0..124c823 100644 --- a/README.md +++ b/README.md @@ -24,32 +24,32 @@ On top of that, you may use all of this information to collect the custom metric **Roadmap** ---------------- -- Migrate fully to the .NET Core (NET Standard). -- Move all of the extensions (Wardens and Integrations) into the separate repositiories. - - Apply new features. +- [x] Migrate fully to the .NET Core (NET Standard). +- [x] Move all of the extensions (Wardens and Integrations) into the separate repositiories. +- [ ] Apply new features. **What kind of monitoring is available?** ---------------- - - **[Disk](https://github.com/spetz/Warden/wiki/Watcher-type-Disk)** - - **[MongoDB](https://github.com/spetz/Warden/wiki/Watcher-type-MongoDB)** - - **[MSSQL](https://github.com/spetz/Warden/wiki/Watcher-type-MSSQL)** - - **[Performance](https://github.com/spetz/Warden/wiki/Watcher-type-Performance)** - - **[Process](https://github.com/spetz/Warden/wiki/Watcher-type-Process)** - - **[Redis](https://github.com/spetz/Warden/wiki/Watcher-type-Redis)** - - **[Server](https://github.com/spetz/Warden/wiki/Watcher-type-Server)** - - **[Web](https://github.com/spetz/Warden/wiki/Watcher-type-Web)** + - **[Disk](https://github.com/warden-stack/Warden.Watchers.Disk)** + - **[MongoDB](https://github.com/warden-stack/Warden.Watchers.MongoDB)** + - **[MSSQL](https://github.com/warden-stack/Warden.Watchers.MSSQL)** + - **[Performance](https://github.com/warden-stack/Warden.Watchers.Performance)** + - **[Process](https://github.com/warden-stack/Warden.Watchers.Process)** + - **[Redis](https://github.com/warden-stack/Warden.Watchers.Redis)** + - **[Server](https://github.com/warden-stack/Warden.Watchers.Server)** + - **[Web](https://github.com/warden-stack/Warden.Watchers.Web)** - **[SSL certificates (3rd party)](https://github.com/janpieterz/Warden.Watchers.SSL)** - **[Azure Storage (3rd party)](https://github.com/janpieterz/Warden.Watchers.AzureStorage)** - **[Azure Service Bus (3rd party)](https://github.com/janpieterz/Warden.Watchers.AzureServiceBus)** **What are the integrations with external services?** ---------------- - - **[Cachet](https://github.com/spetz/Warden/wiki/Integration-with-Cachet)** - - **[HTTP API](https://github.com/spetz/Warden/wiki/Integration-with-HTTP-API)** - - **[MS SQL](https://github.com/spetz/Warden/wiki/Integration-with-MSSQL)** - - **[SendGrid](https://github.com/spetz/Warden/wiki/Integration-with-SendGrid)** - - **[Slack](https://github.com/spetz/Warden/wiki/Integration-with-Slack)** - - **[Twilio](https://github.com/spetz/Warden/wiki/Integration-with-Twilio)** + - **[Cachet](https://github.com/warden-stack/Warden.Integrations.Cachet)** + - **[HTTP API](https://github.com/warden-stack/Warden.Integrations.HTTP-API)** + - **[MS SQL](https://github.com/warden-stack/Warden.Integrations.MSSQL)** + - **[SendGrid](https://github.com/warden-stack/Warden.Integrations.SendGrid)** + - **[Slack](https://github.com/warden-stack/Warden.Integrations.Slack)** + - **[Twilio](https://github.com/warden-stack/Warden.Integrations.Twilio)** - **[Seq (3rd party)](https://github.com/janpieterz/Warden.Integrations.Seq)** **How can I see what's happening with my system?** @@ -67,36 +67,10 @@ Yes, please navigate to the **[wiki](https://github.com/spetz/Warden/wiki)** pag Available as a **[NuGet package](https://www.nuget.org/packages/Warden/)**. ``` -Install-Package Warden +dotnet add package Warden ``` -**Watchers** and **integrations** are available as a separate _NuGet packages_ listed **[here](https://www.nuget.org/profiles/Spetz)**. - -**Cross-platform support** ----------------- - -| Project | .NET Framework | .NET Standard | Comment | -|----------------------|:-------------:|:------------:|--------------------------------- -| **[Warden Core](https://github.com/spetz/Warden/wiki/Warden)** | + | + | -| **[Disk Watcher](https://github.com/spetz/Warden/wiki/Watcher-type-Disk)** | + | + | -| **[MongoDB Watcher](https://github.com/spetz/Warden/wiki/Watcher-type-MongoDB)** | + | + | -| **[MS SQL Watcher](https://github.com/spetz/Warden/wiki/Watcher-type-MSSQL)** | + | + | -| **[Performance Watcher](https://github.com/spetz/Warden/wiki/Watcher-type-Performance)** | + | - | _PerformanceCounter not compatible_ -| **[Process Watcher](https://github.com/spetz/Warden/wiki/Watcher-type-Process)** | + | + | -| **[Redis Watcher](https://github.com/spetz/Warden/wiki/Watcher-type-Redis)** | + | + | -| **[Server Watcher](https://github.com/spetz/Warden/wiki/Watcher-type-Server)** | + | - | _System.Net.Sockets not compatible_ -| **[Web Watcher](https://github.com/spetz/Warden/wiki/Watcher-type-Web)** | + | + | -| **[SSL Watcher (3rd party)](https://github.com/janpieterz/Warden.Watchers.SSL)** | + | + | -| **[Azure Storage Watcher (3rd party)](https://github.com/janpieterz/Warden.Watchers.AzureStorage)** | + | + | -| **[Azure Service Bus Watcher (3rd party)](https://github.com/janpieterz/Warden.Watchers.AzureServiceBus)** | + | - | _Service bus library not compatible_ -| **[Cachet Integration](https://github.com/spetz/Warden/wiki/Integration-with-Cachet)** | + | + | -| **[HTTP API Integration](https://github.com/spetz/Warden/wiki/Integration-with-HTTP-API)** | + | + | -| **[MS SQL Integration](https://github.com/spetz/Warden/wiki/Integration-with-MSSQL)** | + | + | -| **[SendGrid Integration](https://github.com/spetz/Warden/wiki/Integration-with-SendGrid)** | + | + | -| **[Slack Integration](https://github.com/spetz/Warden/wiki/Integration-with-Slack)** | + | + | -| **[Twilio Integration](https://github.com/spetz/Warden/wiki/Integration-with-Twilio )** | + | - | _Twilio not compatible_ -| **[Seq Integration (3rd party)](https://github.com/janpieterz/Warden.Integrations.Seq)** | + | + | -| **[Web Panel](https://github.com/spetz/Warden/wiki/Web-Panel)** | + | - | _Some external libs are not compatible_ +**Watchers** and **Integrations** are available as a separate _NuGet packages_ listed **[here](https://www.nuget.org/packages?q=warden)**. **Quick start**: ---------------- From f3f47246c746a5283df746f4a547d0ccf33b254f Mon Sep 17 00:00:00 2001 From: Piotr Gankiewicz Date: Fri, 16 Feb 2018 14:55:10 +0100 Subject: [PATCH 8/9] Updated docs --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 124c823..b06308e 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ Start the **Warden** and let him do his job - now **you have the full control** var warden = WardenInstance.Create(configuration); await warden.StartAsync(); ``` -Please check out the **[examples](https://github.com/spetz/Warden/wiki/Examples)** by cloning the repository. +Please check out the **[examples](https://github.com/spetz/Warden/wiki/Examples)** by cloning the [repository](https://github.com/warden-stack/Warden.Examples). **Contribute** From d2e93ff9b4230a0a3246859d1a4aa7df33b06f2e Mon Sep 17 00:00:00 2001 From: Piotr Gankiewicz Date: Fri, 16 Feb 2018 17:45:36 +0100 Subject: [PATCH 9/9] Updated docs --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b06308e..85533fc 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ On top of that, you may use all of this information to collect the custom metric - **[MS SQL](https://github.com/warden-stack/Warden.Integrations.MSSQL)** - **[SendGrid](https://github.com/warden-stack/Warden.Integrations.SendGrid)** - **[Slack](https://github.com/warden-stack/Warden.Integrations.Slack)** + - **[SMTP](https://github.com/warden-stack/Warden.Integrations.Smtp)** - **[Twilio](https://github.com/warden-stack/Warden.Integrations.Twilio)** - **[Seq (3rd party)](https://github.com/janpieterz/Warden.Integrations.Seq)**