From b06343362cdccfdec5b46713dc30549094d079ca Mon Sep 17 00:00:00 2001 From: Dave Tillman Date: Tue, 12 Dec 2017 13:29:26 -0700 Subject: [PATCH] Updates for stylecop compatability --- Common.sln | 3 +- config/versions-dev.props | 1 + config/versions-master.props | 1 + config/versions.props | 1 + ...ConfigurationContainerBuilderExtensions.cs | 15 +- .../DefaultLoggerLevelConfigureOptions.cs | 18 +- .../Logging/LoggerFilterConfigureOptions.cs | 48 ++-- .../LoggingContainerBuilderExtensions.cs | 6 +- .../OptionsContainerBuilderExtensions.cs | 18 +- .../Steeltoe.Common.Autofac.csproj | 8 +- .../Discovery/DiscoveryHttpClientHandler.cs | 6 +- .../DiscoveryHttpClientHandlerBase.cs | 46 ++-- .../HttpClientExtensions.cs | 20 +- src/Steeltoe.Common.Http/HttpClientHelper.cs | 111 ++++---- .../Properties/AssemblyInfo.cs | 17 +- .../SerializationHelper.cs | 4 +- .../Steeltoe.Common.Http.csproj | 8 +- .../Steeltoe.Common.Net.csproj | 8 +- .../WindowsNetworkFileShare.cs | 238 +++++++++--------- .../ConfigurationValuesHelper.cs | 21 +- .../PropertyPlaceHolderHelper.cs | 31 ++- .../Discovery/DiscoveryOptions.cs | 35 +-- .../Discovery/IDiscoveryClient.cs | 17 +- .../Discovery/IDiscoveryClientOptions.cs | 4 +- .../Discovery/IDiscoveryLifecycle.cs | 4 +- .../IDiscoveryRegistrationOptions.cs | 4 +- .../Discovery/IServiceInstance.cs | 21 +- .../Options/AbstractOptions.cs | 13 +- src/Steeltoe.Common/Platform.cs | 7 +- src/Steeltoe.Common/Steeltoe.Common.csproj | 7 +- ...igurationContainerBuilderExtensionsTest.cs | 5 +- .../LoggingContainerBuilderExtensionsTest.cs | 5 +- ... OptionsContainerBuilderExtensionsTest.cs} | 16 +- .../Steeltoe.Common.Autofac.Test.csproj | 8 +- .../DiscoveryHttpClientHandlerBaseTest.cs | 114 +-------- .../HttpClientHelperTest.cs | 9 +- .../SerializationHelperTest.cs | 15 +- .../Steeltoe.Common.Http.Test.csproj | 5 +- .../TestDiscoveryClient.cs | 67 +++++ .../TestServiceInstance.cs | 78 ++++++ .../ConfigurationValuesHelperTest.cs | 5 +- .../PropertyPlaceholderHelperTest.cs | 51 ++-- .../Discovery/DiscoveryOptionsTest.cs | 5 +- .../Options/AbstractOptionsTest.cs | 23 +- .../Options/TestOptions.cs | 34 +++ .../Steeltoe.Common.Test.csproj | 5 +- 46 files changed, 643 insertions(+), 543 deletions(-) rename test/Steeltoe.Common.Autofac.Test/Options/{OptionsContainerBuilderExtensions.cs => OptionsContainerBuilderExtensionsTest.cs} (91%) create mode 100644 test/Steeltoe.Common.Http.Test/TestDiscoveryClient.cs create mode 100644 test/Steeltoe.Common.Http.Test/TestServiceInstance.cs create mode 100644 test/Steeltoe.Common.Test/Options/TestOptions.cs diff --git a/Common.sln b/Common.sln index 2f25da1..4ff3e9e 100644 --- a/Common.sln +++ b/Common.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.27004.2005 +VisualStudioVersion = 15.0.27004.2010 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D9798FDE-76F4-4848-8AE0-95249C0101F0}" EndProject @@ -34,6 +34,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution .travis.yml = .travis.yml appveyor.yml = appveyor.yml README.md = README.md + stylecop.json = stylecop.json EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Steeltoe.Common", "src\Steeltoe.Common\Steeltoe.Common.csproj", "{4AEA9704-3B99-4317-A959-7D6E4CDD4811}" diff --git a/config/versions-dev.props b/config/versions-dev.props index eb438ad..a10f587 100644 --- a/config/versions-dev.props +++ b/config/versions-dev.props @@ -6,6 +6,7 @@ 2.0.0 2.0.0 4.6.1 + 1.0.2 4.3.3 3.2.1 4.4.0 diff --git a/config/versions-master.props b/config/versions-master.props index eb438ad..a10f587 100644 --- a/config/versions-master.props +++ b/config/versions-master.props @@ -6,6 +6,7 @@ 2.0.0 2.0.0 4.6.1 + 1.0.2 4.3.3 3.2.1 4.4.0 diff --git a/config/versions.props b/config/versions.props index eb438ad..a10f587 100644 --- a/config/versions.props +++ b/config/versions.props @@ -6,6 +6,7 @@ 2.0.0 2.0.0 4.6.1 + 1.0.2 4.3.3 3.2.1 4.4.0 diff --git a/src/Steeltoe.Common.Autofac/Configuration/ConfigurationContainerBuilderExtensions.cs b/src/Steeltoe.Common.Autofac/Configuration/ConfigurationContainerBuilderExtensions.cs index b72ae22..7d42eba 100644 --- a/src/Steeltoe.Common.Autofac/Configuration/ConfigurationContainerBuilderExtensions.cs +++ b/src/Steeltoe.Common.Autofac/Configuration/ConfigurationContainerBuilderExtensions.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,27 +11,35 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Autofac; using Microsoft.Extensions.Configuration; using System; - namespace Steeltoe.Common.Configuration.Autofac { + /// + /// Extension methods for registering IConfiguration with the Autofac container + /// public static class ConfigurationContainerBuilderExtensions { + /// + /// Register IConfiguration and IConfgurationRoot with the Autofac container + /// + /// the container builder to register with + /// the configuration instance to add to the container public static void RegisterConfiguration(this ContainerBuilder container, IConfiguration configuration) { if (container == null) { throw new ArgumentNullException(nameof(container)); } + if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } + container.RegisterInstance(configuration).As().SingleInstance(); container.RegisterInstance(configuration).As().SingleInstance(); } diff --git a/src/Steeltoe.Common.Autofac/Logging/DefaultLoggerLevelConfigureOptions.cs b/src/Steeltoe.Common.Autofac/Logging/DefaultLoggerLevelConfigureOptions.cs index aea7a33..4e1e581 100644 --- a/src/Steeltoe.Common.Autofac/Logging/DefaultLoggerLevelConfigureOptions.cs +++ b/src/Steeltoe.Common.Autofac/Logging/DefaultLoggerLevelConfigureOptions.cs @@ -1,6 +1,4 @@ -using Microsoft.Extensions.Logging; -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -13,17 +11,23 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; - namespace Steeltoe.Common.Logging.Autofac { + /// + /// Default logger level configuration when using the Autofac container + /// public class DefaultLoggerLevelConfigureOptions : ConfigureOptions { - public DefaultLoggerLevelConfigureOptions(LogLevel level) : - base(options => options.MinLevel = level) + /// + /// Initializes a new instance of the class. + /// + /// default log level to configure + public DefaultLoggerLevelConfigureOptions(LogLevel level) + : base(options => options.MinLevel = level) { } } diff --git a/src/Steeltoe.Common.Autofac/Logging/LoggerFilterConfigureOptions.cs b/src/Steeltoe.Common.Autofac/Logging/LoggerFilterConfigureOptions.cs index 297275f..36acbd9 100644 --- a/src/Steeltoe.Common.Autofac/Logging/LoggerFilterConfigureOptions.cs +++ b/src/Steeltoe.Common.Autofac/Logging/LoggerFilterConfigureOptions.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,23 +11,21 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; - namespace Steeltoe.Common.Logging.Autofac { public class LoggerFilterConfigureOptions : IConfigureOptions { - private readonly IConfiguration _configuration; + private readonly IConfiguration configuration; public LoggerFilterConfigureOptions(IConfiguration configuration) { - _configuration = configuration; + this.configuration = configuration; } public void Configure(LoggerFilterOptions options) @@ -36,14 +33,31 @@ namespace Steeltoe.Common.Logging.Autofac LoadDefaultConfigValues(options); } + private static bool TryGetSwitch(string value, out LogLevel level) + { + if (string.IsNullOrEmpty(value)) + { + level = LogLevel.None; + return false; + } + else if (Enum.TryParse(value, true, out level)) + { + return true; + } + else + { + throw new InvalidOperationException($"Configuration value '{value}' is not supported."); + } + } + private void LoadDefaultConfigValues(LoggerFilterOptions options) { - if (_configuration == null) + if (configuration == null) { return; } - foreach (var configurationSection in _configuration.GetChildren()) + foreach (var configurationSection in configuration.GetChildren()) { if (configurationSection.Key == "LogLevel") { @@ -75,27 +89,11 @@ namespace Steeltoe.Common.Logging.Autofac { category = null; } + var newRule = new LoggerFilterRule(logger, category, level, null); options.Rules.Add(newRule); } } } - - private static bool TryGetSwitch(string value, out LogLevel level) - { - if (string.IsNullOrEmpty(value)) - { - level = LogLevel.None; - return false; - } - else if (Enum.TryParse(value, true, out level)) - { - return true; - } - else - { - throw new InvalidOperationException($"Configuration value '{value}' is not supported."); - } - } } } diff --git a/src/Steeltoe.Common.Autofac/Logging/LoggingContainerBuilderExtensions.cs b/src/Steeltoe.Common.Autofac/Logging/LoggingContainerBuilderExtensions.cs index 728ac27..522c09d 100644 --- a/src/Steeltoe.Common.Autofac/Logging/LoggingContainerBuilderExtensions.cs +++ b/src/Steeltoe.Common.Autofac/Logging/LoggingContainerBuilderExtensions.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Autofac; using Microsoft.Extensions.Configuration; @@ -45,12 +43,14 @@ namespace Steeltoe.Common.Logging.Autofac container.RegisterInstance(new LoggerFilterConfigureOptions(config)).As>().SingleInstance(); container.RegisterInstance(new ConfigurationChangeTokenSource(config)).As>().SingleInstance(); } + public static void RegisterConsoleLogging(this ContainerBuilder container) { if (container == null) { throw new ArgumentNullException(nameof(container)); } + container.RegisterType().As(); } } diff --git a/src/Steeltoe.Common.Autofac/Options/OptionsContainerBuilderExtensions.cs b/src/Steeltoe.Common.Autofac/Options/OptionsContainerBuilderExtensions.cs index 897c3ab..df11b52 100644 --- a/src/Steeltoe.Common.Autofac/Options/OptionsContainerBuilderExtensions.cs +++ b/src/Steeltoe.Common.Autofac/Options/OptionsContainerBuilderExtensions.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,14 +11,12 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Autofac; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using System; - namespace Steeltoe.Common.Options.Autofac { public static class OptionsContainerBuilderExtensions @@ -38,10 +35,12 @@ namespace Steeltoe.Common.Options.Autofac container.RegisterGeneric(typeof(OptionsFactory<>)).As(typeof(IOptionsFactory<>)).InstancePerDependency(); } - public static void RegisterOption(this ContainerBuilder container, IConfiguration config) where TOption : class + public static void RegisterOption(this ContainerBuilder container, IConfiguration config) + where TOption : class => container.RegisterOption(Microsoft.Extensions.Options.Options.DefaultName, config); - public static void RegisterOption(this ContainerBuilder container, string name, IConfiguration config) where TOption : class + public static void RegisterOption(this ContainerBuilder container, string name, IConfiguration config) + where TOption : class { if (container == null) { @@ -57,10 +56,12 @@ namespace Steeltoe.Common.Options.Autofac container.RegisterInstance(new NamedConfigureFromConfigurationOptions(name, config)).As>().SingleInstance(); } - public static void RegisterPostConfigure(this ContainerBuilder container, Action configureOptions) where TOptions : class + public static void RegisterPostConfigure(this ContainerBuilder container, Action configureOptions) + where TOptions : class => container.RegisterPostConfigure(Microsoft.Extensions.Options.Options.DefaultName, configureOptions); - public static void RegisterPostConfigure(this ContainerBuilder container, string name, Action configureOptions) where TOptions : class + public static void RegisterPostConfigure(this ContainerBuilder container, string name, Action configureOptions) + where TOptions : class { if (container == null) { @@ -71,6 +72,7 @@ namespace Steeltoe.Common.Options.Autofac { throw new ArgumentNullException(nameof(configureOptions)); } + container.RegisterInstance(new PostConfigureOptions(name, configureOptions)).As>().SingleInstance(); } } diff --git a/src/Steeltoe.Common.Autofac/Steeltoe.Common.Autofac.csproj b/src/Steeltoe.Common.Autofac/Steeltoe.Common.Autofac.csproj index b52207b..55d505f 100644 --- a/src/Steeltoe.Common.Autofac/Steeltoe.Common.Autofac.csproj +++ b/src/Steeltoe.Common.Autofac/Steeltoe.Common.Autofac.csproj @@ -17,14 +17,16 @@ bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Autofac.xml + SA1101;SA1309;SA1310;SA1401;SA1600;1591 - - SA1100;SA1101;SA1124;SA1202;SA1204;SA1309;SA1310;SA1313;SA1600;SA1611;1591;1701;1702;1705 - + + + All + diff --git a/src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandler.cs b/src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandler.cs index 3eaa7a0..cfaa24f 100644 --- a/src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandler.cs +++ b/src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandler.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Logging; @@ -20,7 +18,7 @@ namespace Steeltoe.Common.Discovery { public class DiscoveryHttpClientHandler : DiscoveryHttpClientHandlerBase { - public DiscoveryHttpClientHandler(IDiscoveryClient client, ILogger logger = null) + public DiscoveryHttpClientHandler(IDiscoveryClient client, ILogger logger = null) : base(client, logger) { } diff --git a/src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandlerBase.cs b/src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandlerBase.cs index d079e4a..b424777 100644 --- a/src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandlerBase.cs +++ b/src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandlerBase.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Logging; using System; @@ -24,9 +22,9 @@ namespace Steeltoe.Common.Discovery { public class DiscoveryHttpClientHandlerBase : HttpClientHandler { + protected static Random _random = new Random(); protected IDiscoveryClient _client; protected ILogger _logger; - protected static Random _random = new Random(); public DiscoveryHttpClientHandlerBase(IDiscoveryClient client, ILogger logger = null) { @@ -39,25 +37,6 @@ namespace Steeltoe.Common.Discovery _logger = logger; } - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - var current = request.RequestUri; - try - { - request.RequestUri = LookupService(current); - return await base.SendAsync(request, cancellationToken); - } catch(Exception e) - { - _logger?.LogDebug(e, "Exception during SendAsync()"); - throw; - } - finally - { - request.RequestUri = current; - } - - } - public virtual Uri LookupService(Uri current) { _logger?.LogDebug("LookupService({0})", current.ToString()); @@ -72,11 +51,28 @@ namespace Steeltoe.Common.Discovery int indx = _random.Next(instances.Count); current = new Uri(instances[indx].Uri, current.PathAndQuery); } + _logger?.LogDebug("LookupService() returning {0} ", current.ToString()); return current; - } + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var current = request.RequestUri; + try + { + request.RequestUri = LookupService(current); + return await base.SendAsync(request, cancellationToken); + } + catch (Exception e) + { + _logger?.LogDebug(e, "Exception during SendAsync()"); + throw; + } + finally + { + request.RequestUri = current; + } + } } } - diff --git a/src/Steeltoe.Common.Http/HttpClientExtensions.cs b/src/Steeltoe.Common.Http/HttpClientExtensions.cs index 94eca5a..f71a172 100644 --- a/src/Steeltoe.Common.Http/HttpClientExtensions.cs +++ b/src/Steeltoe.Common.Http/HttpClientExtensions.cs @@ -42,9 +42,9 @@ namespace Steeltoe.Common.Http /// /// Type of object to serialize /// HttpClient doing the sending - /// Your Serializer Settings /// Url to POST to /// Object to send + /// Your Serializer Settings /// Task to be awaited public static Task PostAsJsonAsync(this HttpClient httpClient, string url, T data, JsonSerializerSettings settings) { @@ -57,10 +57,10 @@ namespace Steeltoe.Common.Http /// /// Convert an object to JSON and PUT it /// - /// - /// - /// - /// + /// the type of the data + /// provided HttpClient + /// the http endpoint to Put to + /// the data to put /// Task to be awaited public static Task PutAsJsonAsync(this HttpClient httpClient, string url, T data) { @@ -73,11 +73,11 @@ namespace Steeltoe.Common.Http /// /// Convert an object to JSON and PUT it /// - /// - /// - /// - /// - /// + /// the type of the data + /// provided HttpClient + /// the http endpoint to Put to + /// the data to put + /// the serialization setttings to use /// Task to be awaited public static Task PutAsJsonAsync(this HttpClient httpClient, string url, T data, JsonSerializerSettings settings) { diff --git a/src/Steeltoe.Common.Http/HttpClientHelper.cs b/src/Steeltoe.Common.Http/HttpClientHelper.cs index 1de96f3..71f976a 100644 --- a/src/Steeltoe.Common.Http/HttpClientHelper.cs +++ b/src/Steeltoe.Common.Http/HttpClientHelper.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; @@ -32,34 +30,12 @@ namespace Steeltoe.Common.Http { public static class HttpClientHelper { + internal static Func _reflectedDelegate = null; + private const int DEFAULT_GETACCESSTOKEN_TIMEOUT = 10000; // Milliseconds private const bool DEFAULT_VALIDATE_CERTIFICATES = true; - private static Func DefaultDelegate { get; } = (sender, cert, chain, sslPolicyErrors) => true; - internal static Func _reflectedDelegate = null; - internal static Func GetDisableDelegate() - { - if (Platform.IsFullFramework) - { - return null; - } - if (_reflectedDelegate != null) - { - return _reflectedDelegate; - } - - var property = typeof(HttpClientHandler).GetProperty("DangerousAcceptAnyServerCertificateValidator", - BindingFlags.Public | BindingFlags.Static); - if (property != null) - { - _reflectedDelegate = property.GetValue(null) as Func; - if (_reflectedDelegate != null) - { - return _reflectedDelegate; - } - } - return DefaultDelegate; - } + private static Func DefaultDelegate { get; } = (sender, cert, chain, sslPolicyErrors) => true; public static HttpClient GetHttpClient(bool validateCertificates, int timeout) { @@ -70,7 +46,6 @@ namespace Steeltoe.Common.Http } else { - if (!validateCertificates) { var handler = new HttpClientHandler(); @@ -83,10 +58,15 @@ namespace Steeltoe.Common.Http client = new HttpClient(); } } + client.Timeout = TimeSpan.FromMilliseconds(timeout); return client; } - public static void ConfigureCertificateValidatation(bool validateCertificates, out SecurityProtocolType protocolType, out RemoteCertificateValidationCallback prevValidator) + + public static void ConfigureCertificateValidatation( + bool validateCertificates, + out SecurityProtocolType protocolType, + out RemoteCertificateValidationCallback prevValidator) { prevValidator = null; protocolType = (SecurityProtocolType)0; @@ -102,9 +82,12 @@ namespace Steeltoe.Common.Http } } } - public static void RestoreCertificateValidation(bool validateCertificates, SecurityProtocolType protocolType, RemoteCertificateValidationCallback prevValidator) - { + public static void RestoreCertificateValidation( + bool validateCertificates, + SecurityProtocolType protocolType, + RemoteCertificateValidationCallback prevValidator) + { if (Platform.IsFullFramework) { if (!validateCertificates) @@ -112,26 +95,31 @@ namespace Steeltoe.Common.Http ServicePointManager.SecurityProtocol = protocolType; ServicePointManager.ServerCertificateValidationCallback = prevValidator; } - } - } + public static string GetEncodedUserPassword(string user, string password) { if (user == null) + { user = string.Empty; + } + if (password == null) + { password = string.Empty; + } + return Convert.ToBase64String(Encoding.ASCII.GetBytes(user + ":" + password)); } - public static HttpRequestMessage GetRequestMessage(HttpMethod method, string requestUri, Func GetAccessToken) + public static HttpRequestMessage GetRequestMessage(HttpMethod method, string requestUri, Func getAccessToken) { var request = GetRequestMessage(method, requestUri, null, null); - if (GetAccessToken != null) + if (getAccessToken != null) { - var accessToken = GetAccessToken(); + var accessToken = getAccessToken(); if (accessToken != null) { @@ -139,6 +127,7 @@ namespace Steeltoe.Common.Http request.Headers.Authorization = auth; } } + return request; } @@ -157,16 +146,22 @@ namespace Steeltoe.Common.Http var request = new HttpRequestMessage(method, requestUri); if (!string.IsNullOrEmpty(password)) { - AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Basic", + AuthenticationHeaderValue auth = new AuthenticationHeaderValue( + "Basic", GetEncodedUserPassword(userName, password)); request.Headers.Authorization = auth; } return request; } + public static async Task GetAccessToken( - string accessTokenUri, string clientId, string clientSecret, - int timeout = DEFAULT_GETACCESSTOKEN_TIMEOUT, bool validateCertificates = DEFAULT_VALIDATE_CERTIFICATES, ILogger logger = null) + string accessTokenUri, + string clientId, + string clientSecret, + int timeout = DEFAULT_GETACCESSTOKEN_TIMEOUT, + bool validateCertificates = DEFAULT_VALIDATE_CERTIFICATES, + ILogger logger = null) { if (string.IsNullOrEmpty(accessTokenUri)) @@ -183,6 +178,7 @@ namespace Steeltoe.Common.Http { throw new ArgumentException(nameof(accessTokenUri)); } + var request = new HttpRequestMessage(HttpMethod.Post, accessTokenUri); HttpClient client = GetHttpClient(validateCertificates, timeout); @@ -207,8 +203,10 @@ namespace Steeltoe.Common.Http { if (response.StatusCode != HttpStatusCode.OK) { - logger?.LogInformation("GetAccessToken returned status: {0} while obtaining access token from: {1}", - response.StatusCode, accessTokenUri); + logger?.LogInformation( + "GetAccessToken returned status: {0} while obtaining access token from: {1}", + response.StatusCode, + accessTokenUri); return null; } @@ -226,7 +224,36 @@ namespace Steeltoe.Common.Http { HttpClientHelper.RestoreCertificateValidation(validateCertificates, prevProtocols, prevValidator); } + return null; } + + internal static Func GetDisableDelegate() + { + if (Platform.IsFullFramework) + { + return null; + } + + if (_reflectedDelegate != null) + { + return _reflectedDelegate; + } + + var property = typeof(HttpClientHandler).GetProperty( + "DangerousAcceptAnyServerCertificateValidator", + BindingFlags.Public | BindingFlags.Static); + + if (property != null) + { + _reflectedDelegate = property.GetValue(null) as Func; + if (_reflectedDelegate != null) + { + return _reflectedDelegate; + } + } + + return DefaultDelegate; + } } } diff --git a/src/Steeltoe.Common.Http/Properties/AssemblyInfo.cs b/src/Steeltoe.Common.Http/Properties/AssemblyInfo.cs index d63fb24..ab19f12 100644 --- a/src/Steeltoe.Common.Http/Properties/AssemblyInfo.cs +++ b/src/Steeltoe.Common.Http/Properties/AssemblyInfo.cs @@ -1,4 +1,17 @@ -using System.Runtime.CompilerServices; +// Copyright 2017 the original author or authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Steeltoe.Common.Http.Test")] - diff --git a/src/Steeltoe.Common.Http/SerializationHelper.cs b/src/Steeltoe.Common.Http/SerializationHelper.cs index 9644192..ef647c7 100644 --- a/src/Steeltoe.Common.Http/SerializationHelper.cs +++ b/src/Steeltoe.Common.Http/SerializationHelper.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Logging; using Newtonsoft.Json; diff --git a/src/Steeltoe.Common.Http/Steeltoe.Common.Http.csproj b/src/Steeltoe.Common.Http/Steeltoe.Common.Http.csproj index cad526e..919c9da 100644 --- a/src/Steeltoe.Common.Http/Steeltoe.Common.Http.csproj +++ b/src/Steeltoe.Common.Http/Steeltoe.Common.Http.csproj @@ -17,14 +17,16 @@ bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Http.xml + SA1101;SA1309;SA1310;SA1401;SA1600;1591 - - SA1100;SA1101;SA1124;SA1202;SA1204;SA1309;SA1310;SA1313;SA1600;SA1611;1591;1701;1702;1705 - + + + All + diff --git a/src/Steeltoe.Common.Net/Steeltoe.Common.Net.csproj b/src/Steeltoe.Common.Net/Steeltoe.Common.Net.csproj index d49c1e3..9443a44 100644 --- a/src/Steeltoe.Common.Net/Steeltoe.Common.Net.csproj +++ b/src/Steeltoe.Common.Net/Steeltoe.Common.Net.csproj @@ -17,11 +17,13 @@ bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Net.xml + SA1101;SA1309;SA1310;SA1401;SA1600;SA1307;1591 - - SA1100;SA1101;SA1124;SA1202;SA1204;SA1309;SA1310;SA1313;SA1600;SA1611;1591;1701;1702;1705 - + + + All + diff --git a/src/Steeltoe.Common.Net/WindowsNetworkFileShare.cs b/src/Steeltoe.Common.Net/WindowsNetworkFileShare.cs index 40e4516..357c901 100644 --- a/src/Steeltoe.Common.Net/WindowsNetworkFileShare.cs +++ b/src/Steeltoe.Common.Net/WindowsNetworkFileShare.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using System; using System.Net; @@ -23,7 +21,59 @@ namespace Steeltoe.Common.Net { public class WindowsNetworkFileShare { - readonly string _networkName; + private const int NO_ERROR = 0; + private const int ERROR_ACCESS_DENIED = 5; + private const int ERROR_ALREADY_ASSIGNED = 85; + private const int ERROR_PATH_NOT_FOUND = 53; + private const int ERROR_BAD_DEVICE = 1200; + private const int ERROR_BAD_NET_NAME = 67; + private const int ERROR_BAD_PROVIDER = 1204; + private const int ERROR_CANCELLED = 1223; + private const int ERROR_EXTENDED_ERROR = 1208; + private const int ERROR_INVALID_ADDRESS = 487; + private const int ERROR_INVALID_PARAMETER = 87; + private const int ERROR_INVALID_PASSWORD = 86; + private const int ERROR_INVALID_PASSWORDNAME = 1216; + private const int ERROR_MORE_DATA = 234; + private const int ERROR_NO_MORE_ITEMS = 259; + private const int ERROR_NO_NET_OR_BAD_PATH = 1203; + private const int ERROR_NO_NETWORK = 1222; + private const int ERROR_BAD_PROFILE = 1206; + private const int ERROR_CANNOT_OPEN_PROFILE = 1205; + private const int ERROR_DEVICE_IN_USE = 2404; + private const int ERROR_NOT_CONNECTED = 2250; + private const int ERROR_OPEN_FILES = 2401; + private const int ERROR_LOGON_FAILURE = 1326; + + // Created with excel formula: + // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " + private static ErrorClass[] error_list = new ErrorClass[] + { + new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), + new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), + new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), + new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), + new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), + new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), + new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), + new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), + new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), + new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), + new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), + new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), + new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), + new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), + new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), + new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), + new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), + new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), + new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), + new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), + new ErrorClass(ERROR_LOGON_FAILURE, "The user name or password is incorrect"), + new ErrorClass(ERROR_PATH_NOT_FOUND, "The network path not found") + }; + + private readonly string _networkName; public WindowsNetworkFileShare(string networkName, NetworkCredential credentials) { @@ -41,7 +91,6 @@ namespace Steeltoe.Common.Net ? credentials.UserName : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName); - var result = WNetUseConnection(IntPtr.Zero, netResource, credentials.Password, userName, 0, null, null, null); if (result != 0) @@ -55,53 +104,6 @@ namespace Steeltoe.Common.Net Dispose(false); } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - WNetCancelConnection2(_networkName, 0, true); - } - - [DllImport("mpr.dll")] - private static extern int WNetAddConnection2(NetResource netResource, - string password, string username, int flags); - - [DllImport("mpr.dll")] - private static extern int WNetCancelConnection2(string name, int flags, - bool force); - - [DllImport("mpr.dll")] - private static extern int WNetUseConnection( - IntPtr hwndOwner, - NetResource netResource, - string password, string username, int flags, - string lpAccessName, - string lpBufferSize, - string lpResult - ); - - [DllImport("mpr.dll", CharSet = CharSet.Auto)] - public static extern int WNetGetLastError(out int Error, - out StringBuilder ErrorBuf, int ErrorBufSize, out StringBuilder NameBuf, int NameBufSize); - - - [StructLayout(LayoutKind.Sequential)] - public class NetResource - { - public ResourceScope Scope; - public ResourceType ResourceType; - public ResourceDisplaytype DisplayType; - public int Usage; - public string LocalName; - public string RemoteName; - public string Comment; - public string Provider; - } - public enum ResourceScope : int { Connected = 1, @@ -109,7 +111,7 @@ namespace Steeltoe.Common.Net Remembered, Recent, Context - }; + } public enum ResourceType : int { @@ -134,80 +136,63 @@ namespace Steeltoe.Common.Net Tree = 0x0a, Ndscontainer = 0x0b } - #region Errors - const int NO_ERROR = 0; - const int ERROR_ACCESS_DENIED = 5; - const int ERROR_ALREADY_ASSIGNED = 85; - const int ERROR_PATH_NOT_FOUND = 53; - const int ERROR_BAD_DEVICE = 1200; - const int ERROR_BAD_NET_NAME = 67; - const int ERROR_BAD_PROVIDER = 1204; - const int ERROR_CANCELLED = 1223; - const int ERROR_EXTENDED_ERROR = 1208; - const int ERROR_INVALID_ADDRESS = 487; - const int ERROR_INVALID_PARAMETER = 87; - const int ERROR_INVALID_PASSWORD = 86; - const int ERROR_INVALID_PASSWORDNAME = 1216; - const int ERROR_MORE_DATA = 234; - const int ERROR_NO_MORE_ITEMS = 259; - const int ERROR_NO_NET_OR_BAD_PATH = 1203; - const int ERROR_NO_NETWORK = 1222; + [DllImport("mpr.dll", CharSet = CharSet.Auto)] + public static extern int WNetGetLastError( + out int error, + out StringBuilder errorBuf, + int errorBufSize, + out StringBuilder nameBuf, + int nameBufSize); - const int ERROR_BAD_PROFILE = 1206; - const int ERROR_CANNOT_OPEN_PROFILE = 1205; - const int ERROR_DEVICE_IN_USE = 2404; - const int ERROR_NOT_CONNECTED = 2250; - const int ERROR_OPEN_FILES = 2401; - const int ERROR_LOGON_FAILURE = 1326; - - private struct ErrorClass + public void Dispose() { - public int num; - public string message; - public ErrorClass(int num, string message) - { - this.num = num; - this.message = message; - } + Dispose(true); + GC.SuppressFinalize(this); } + protected virtual void Dispose(bool disposing) + { + WNetCancelConnection2(_networkName, 0, true); + } - // Created with excel formula: - // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " - private static ErrorClass[] ERROR_LIST = new ErrorClass[] { - new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), - new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), - new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), - new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), - new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), - new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), - new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), - new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), - new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), - new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), - new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), - new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), - new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), - new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), - new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), - new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), - new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), - new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), - new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), - new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), - new ErrorClass(ERROR_LOGON_FAILURE,"The user name or password is incorrect"), - new ErrorClass(ERROR_PATH_NOT_FOUND,"The network path not found") - }; + [DllImport("mpr.dll")] + private static extern int WNetAddConnection2( + NetResource netResource, + string password, + string username, + int flags); + + [DllImport("mpr.dll")] + private static extern int WNetCancelConnection2( + string name, + int flags, + bool force); + + [DllImport("mpr.dll")] + private static extern int WNetUseConnection( + IntPtr hwndOwner, + NetResource netResource, + string password, + string username, + int flags, + string lpAccessName, + string lpBufferSize, + string lpResult); private static string GetErrorForNumber(int errNum) { - foreach (ErrorClass er in ERROR_LIST) + foreach (ErrorClass er in error_list) { - if (er.num == errNum) return er.message; + if (er.num == errNum) + { + return er.message; + } } + return "Error: Unknown, " + errNum; } + private static string GetLastError(int result) { StringBuilder sbErrorBuf = new StringBuilder(500); @@ -216,7 +201,30 @@ namespace Steeltoe.Common.Net int res = WNetGetLastError(out resultref, out sbErrorBuf, sbErrorBuf.Capacity, out sbNameBuf, sbNameBuf.Capacity); return sbErrorBuf.ToString(); } - #endregion + private struct ErrorClass + { + public int num; + public string message; + + public ErrorClass(int num, string message) + { + this.num = num; + this.message = message; + } + } + + [StructLayout(LayoutKind.Sequential)] + public class NetResource + { + public ResourceScope Scope; + public ResourceType ResourceType; + public ResourceDisplaytype DisplayType; + public int Usage; + public string LocalName; + public string RemoteName; + public string Comment; + public string Provider; + } } } diff --git a/src/Steeltoe.Common/Configuration/ConfigurationValuesHelper.cs b/src/Steeltoe.Common/Configuration/ConfigurationValuesHelper.cs index 280be38..8088966 100644 --- a/src/Steeltoe.Common/Configuration/ConfigurationValuesHelper.cs +++ b/src/Steeltoe.Common/Configuration/ConfigurationValuesHelper.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,17 +11,14 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Configuration; using System; - namespace Steeltoe.Common.Configuration { public static class ConfigurationValuesHelper { - public static string GetSetting(string key, IConfiguration primary, IConfiguration secondary, IConfiguration resolve, string def) { // First check for key in primary @@ -49,10 +45,14 @@ namespace Steeltoe.Common.Configuration { int result; if (int.TryParse(val, out result)) + { return result; + } } + return def; } + public static double GetDouble(string key, IConfiguration config, IConfiguration resolve, double def) { var val = GetString(key, config, resolve, null); @@ -60,8 +60,11 @@ namespace Steeltoe.Common.Configuration { double result; if (double.TryParse(val, out result)) + { return result; + } } + return def; } @@ -71,12 +74,15 @@ namespace Steeltoe.Common.Configuration if (!string.IsNullOrEmpty(val)) { bool result; - if (Boolean.TryParse(val, out result)) + if (bool.TryParse(val, out result)) + { return result; + } } - return def; + return def; } + public static string GetString(string key, IConfiguration config, IConfiguration resolve, string def) { if (string.IsNullOrEmpty(key)) @@ -94,6 +100,7 @@ namespace Steeltoe.Common.Configuration { return PropertyPlaceholderHelper.ResolvePlaceholders(val, resolve); } + return def; } } diff --git a/src/Steeltoe.Common/Configuration/PropertyPlaceHolderHelper.cs b/src/Steeltoe.Common/Configuration/PropertyPlaceHolderHelper.cs index e7f3167..1dd7164 100644 --- a/src/Steeltoe.Common/Configuration/PropertyPlaceHolderHelper.cs +++ b/src/Steeltoe.Common/Configuration/PropertyPlaceHolderHelper.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; @@ -25,9 +23,7 @@ namespace Steeltoe.Common.Configuration /// /// Utility class for working with configuration values that have placeholders in them. /// A placeholder takes the form of ${some:config:reference?default_if_not_present}> - /// /// Note: This was "inspired" by the Spring class: PropertyPlaceholderHelper - /// /// public static class PropertyPlaceholderHelper { @@ -50,14 +46,15 @@ namespace Steeltoe.Common.Configuration private static string ParseStringValue(string property, IConfiguration config, ISet visitedPlaceHolders, ILogger logger = null) { - if (config == null) { return property; } if (string.IsNullOrEmpty(property)) + { return property; + } StringBuilder result = new StringBuilder(property); @@ -67,19 +64,20 @@ namespace Steeltoe.Common.Configuration int endIndex = FindEndIndex(result, startIndex); if (endIndex != -1) { - string placeholder = result.Substring(startIndex + PREFIX.Length, endIndex); string originalPlaceholder = placeholder; if (!visitedPlaceHolders.Add(originalPlaceholder)) { - throw new ArgumentException(String.Format("Circular placeholder reference '{0}' in property definitions", - originalPlaceholder)); + throw new ArgumentException($"Circular placeholder reference '{originalPlaceholder}' in property definitions"); } + // Recursive invocation, parsing placeholders contained in the placeholder key. placeholder = ParseStringValue(placeholder, config, visitedPlaceHolders); + // Handle array references foo:bar[1]:baz format -> foo:bar:1:baz - string lookup = placeholder.Replace('[', ':').Replace("]", ""); + string lookup = placeholder.Replace('[', ':').Replace("]", string.Empty); + // Now obtain the value for the fully resolved key... string propVal = config[lookup]; if (propVal == null) @@ -96,6 +94,7 @@ namespace Steeltoe.Common.Configuration } } } + if (propVal != null) { // Recursive invocation, parsing placeholders contained in these @@ -110,6 +109,7 @@ namespace Steeltoe.Common.Configuration // Proceed with unprocessed value. startIndex = result.IndexOf(PREFIX, endIndex + PREFIX.Length); } + visitedPlaceHolders.Remove(originalPlaceholder); } else @@ -121,14 +121,12 @@ namespace Steeltoe.Common.Configuration return result.ToString(); } - private static int FindEndIndex(StringBuilder property, int startIndex) { int index = startIndex + PREFIX.Length; int withinNestedPlaceholder = 0; while (index < property.Length) { - if (SubstringMatch(property, index, SUFFIX)) { if (withinNestedPlaceholder > 0) @@ -151,9 +149,10 @@ namespace Steeltoe.Common.Configuration index++; } } - return -1; + return -1; } + private static bool SubstringMatch(StringBuilder str, int index, string substring) { for (int j = 0; j < substring.Length; j++) @@ -164,6 +163,7 @@ namespace Steeltoe.Common.Configuration return false; } } + return true; } @@ -172,12 +172,17 @@ namespace Steeltoe.Common.Configuration builder.Remove(start, end - start); builder.Insert(start, str); } + private static int IndexOf(this StringBuilder builder, string str, int start) { if (start >= builder.Length) + { return -1; + } + return builder.ToString().IndexOf(str, start); } + private static string Substring(this StringBuilder builder, int start, int end) { return builder.ToString().Substring(start, end - start); diff --git a/src/Steeltoe.Common/Discovery/DiscoveryOptions.cs b/src/Steeltoe.Common/Discovery/DiscoveryOptions.cs index 5625389..a906a5f 100644 --- a/src/Steeltoe.Common/Discovery/DiscoveryOptions.cs +++ b/src/Steeltoe.Common/Discovery/DiscoveryOptions.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,25 +11,34 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Configuration; using System; - namespace Steeltoe.Common.Discovery { + public enum DiscoveryClientType + { + EUREKA, UNKNOWN + } + public class DiscoveryOptions { - public DiscoveryOptions(IConfiguration config) : this() + protected string _type; + protected IDiscoveryClientOptions _clientOptions; + protected IDiscoveryRegistrationOptions _registrationOptions; + + public DiscoveryOptions(IConfiguration config) + : this() { if (config == null) { throw new ArgumentNullException(nameof(config)); } - Configure(config); + Configure(config); } + public DiscoveryOptions() { ClientType = DiscoveryClientType.UNKNOWN; @@ -44,7 +52,6 @@ namespace Steeltoe.Common.Discovery } } - protected string _type; public DiscoveryClientType ClientType { get @@ -53,47 +60,45 @@ namespace Steeltoe.Common.Discovery { return DiscoveryClientType.UNKNOWN; } + return (DiscoveryClientType)System.Enum.Parse(typeof(DiscoveryClientType), _type); } + set { _type = System.Enum.GetName(typeof(DiscoveryClientType), value); } } - protected IDiscoveryClientOptions _clientOptions; public IDiscoveryClientOptions ClientOptions { get { return _clientOptions; } + set { _clientOptions = value; } - } - protected IDiscoveryRegistrationOptions _registrationOptions; + public IDiscoveryRegistrationOptions RegistrationOptions { get { return _registrationOptions; } + set { _registrationOptions = value; } } + public virtual void Configure(IConfiguration config) { ClientType = DiscoveryClientType.UNKNOWN; } - } - - public enum DiscoveryClientType { EUREKA, UNKNOWN } - - } diff --git a/src/Steeltoe.Common/Discovery/IDiscoveryClient.cs b/src/Steeltoe.Common/Discovery/IDiscoveryClient.cs index 4a256d1..981b2ba 100644 --- a/src/Steeltoe.Common/Discovery/IDiscoveryClient.cs +++ b/src/Steeltoe.Common/Discovery/IDiscoveryClient.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,9 +11,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// -using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -23,30 +20,28 @@ namespace Steeltoe.Common.Discovery public interface IDiscoveryClient { /// - /// A human readable description of the implementation + /// Gets a human readable description of the implementation /// string Description { get; } /// - /// All known service Ids + /// Gets all known service Ids /// IList Services { get; } /// /// ServiceInstance with information used to register the local service /// - /// + /// The IServiceInstance IServiceInstance GetLocalServiceInstance(); /// /// Get all ServiceInstances associated with a particular serviceId /// /// the serviceId to lookup - /// - IList GetInstances(String serviceId); - + /// List of service instances + IList GetInstances(string serviceId); Task ShutdownAsync(); - } } diff --git a/src/Steeltoe.Common/Discovery/IDiscoveryClientOptions.cs b/src/Steeltoe.Common/Discovery/IDiscoveryClientOptions.cs index 968b30a..5612766 100644 --- a/src/Steeltoe.Common/Discovery/IDiscoveryClientOptions.cs +++ b/src/Steeltoe.Common/Discovery/IDiscoveryClientOptions.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// namespace Steeltoe.Common.Discovery { diff --git a/src/Steeltoe.Common/Discovery/IDiscoveryLifecycle.cs b/src/Steeltoe.Common/Discovery/IDiscoveryLifecycle.cs index 88456fb..e4e18fc 100644 --- a/src/Steeltoe.Common/Discovery/IDiscoveryLifecycle.cs +++ b/src/Steeltoe.Common/Discovery/IDiscoveryLifecycle.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using System.Threading; diff --git a/src/Steeltoe.Common/Discovery/IDiscoveryRegistrationOptions.cs b/src/Steeltoe.Common/Discovery/IDiscoveryRegistrationOptions.cs index af10046..a91bb45 100644 --- a/src/Steeltoe.Common/Discovery/IDiscoveryRegistrationOptions.cs +++ b/src/Steeltoe.Common/Discovery/IDiscoveryRegistrationOptions.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// namespace Steeltoe.Common.Discovery { diff --git a/src/Steeltoe.Common/Discovery/IServiceInstance.cs b/src/Steeltoe.Common/Discovery/IServiceInstance.cs index 6977b06..9c3e91e 100644 --- a/src/Steeltoe.Common/Discovery/IServiceInstance.cs +++ b/src/Steeltoe.Common/Discovery/IServiceInstance.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using System; using System.Collections.Generic; @@ -22,27 +20,32 @@ namespace Steeltoe.Common.Discovery public interface IServiceInstance { /// - /// The service id as register by the DiscoveryClient + /// Gets the service id as register by the DiscoveryClient /// string ServiceId { get; } + /// - /// The hostname of the registered ServiceInstance + /// Gets the hostname of the registered ServiceInstance /// string Host { get; } + /// - /// The port of the registered ServiceInstance + /// Gets the port of the registered ServiceInstance /// int Port { get; } + /// - /// If the port of the registered ServiceInstance is https or not + /// Gets a value indicating whether if the port of the registered ServiceInstance is https or not /// bool IsSecure { get; } + /// - /// the service uri address + /// Gets the service uri address /// Uri Uri { get; } + /// - /// The key value pair metadata associated with the service instance + /// Gets the key value pair metadata associated with the service instance /// IDictionary Metadata { get; } } diff --git a/src/Steeltoe.Common/Options/AbstractOptions.cs b/src/Steeltoe.Common/Options/AbstractOptions.cs index 8b0984b..a305bcd 100644 --- a/src/Steeltoe.Common/Options/AbstractOptions.cs +++ b/src/Steeltoe.Common/Options/AbstractOptions.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,8 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// - using Microsoft.Extensions.Configuration; using System; @@ -24,7 +21,6 @@ namespace Steeltoe.Common.Options { public AbstractOptions() { - } public AbstractOptions(IConfigurationRoot root, string sectionPrefix = null) @@ -34,17 +30,15 @@ namespace Steeltoe.Common.Options throw new ArgumentNullException(nameof(root)); } - if (!string.IsNullOrEmpty(sectionPrefix)) { var section = root.GetSection(sectionPrefix); section.Bind(this); - } else + } + else { root.Bind(this); } - - } public AbstractOptions(IConfiguration config) @@ -53,6 +47,7 @@ namespace Steeltoe.Common.Options { throw new ArgumentNullException(nameof(config)); } + config.Bind(this); } } diff --git a/src/Steeltoe.Common/Platform.cs b/src/Steeltoe.Common/Platform.cs index 7a5223c..daede63 100644 --- a/src/Steeltoe.Common/Platform.cs +++ b/src/Steeltoe.Common/Platform.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using System.Runtime.InteropServices; @@ -23,9 +21,8 @@ namespace Steeltoe.Common public const string NET_FRAMEWORK = ".NET Framework"; public const string NET_CORE = ".NET Core"; - public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(NET_FRAMEWORK); - public static bool IsNetCore => RuntimeInformation.FrameworkDescription.StartsWith(NET_CORE); + public static bool IsNetCore => RuntimeInformation.FrameworkDescription.StartsWith(NET_CORE); } } diff --git a/src/Steeltoe.Common/Steeltoe.Common.csproj b/src/Steeltoe.Common/Steeltoe.Common.csproj index f7b8a04..ae040f2 100644 --- a/src/Steeltoe.Common/Steeltoe.Common.csproj +++ b/src/Steeltoe.Common/Steeltoe.Common.csproj @@ -17,18 +17,23 @@ bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.xml + SA1101;SA1309;SA1310;SA1401;SA1600;1591 - SA1100;SA1101;SA1124;SA1202;SA1204;SA1309;SA1310;SA1313;SA1600;SA1611;1591;1701;1702;1705 + + All + + stylecop.json Always + \ No newline at end of file diff --git a/test/Steeltoe.Common.Autofac.Test/Configuration/ConfigurationContainerBuilderExtensionsTest.cs b/test/Steeltoe.Common.Autofac.Test/Configuration/ConfigurationContainerBuilderExtensionsTest.cs index 97b67f9..dafff28 100644 --- a/test/Steeltoe.Common.Autofac.Test/Configuration/ConfigurationContainerBuilderExtensionsTest.cs +++ b/test/Steeltoe.Common.Autofac.Test/Configuration/ConfigurationContainerBuilderExtensionsTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Autofac; using Microsoft.Extensions.Configuration; @@ -43,6 +41,5 @@ namespace Steeltoe.Common.Configuration.Autofac.Test Assert.True(built.IsRegistered()); Assert.True(built.IsRegistered()); } - } } diff --git a/test/Steeltoe.Common.Autofac.Test/Logging/LoggingContainerBuilderExtensionsTest.cs b/test/Steeltoe.Common.Autofac.Test/Logging/LoggingContainerBuilderExtensionsTest.cs index a46ec02..8964ecd 100644 --- a/test/Steeltoe.Common.Autofac.Test/Logging/LoggingContainerBuilderExtensionsTest.cs +++ b/test/Steeltoe.Common.Autofac.Test/Logging/LoggingContainerBuilderExtensionsTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Autofac; using Microsoft.Extensions.Configuration; @@ -50,7 +48,6 @@ namespace Steeltoe.Common.Autofac.Test.Logging Assert.NotNull(fac); var logger = built.Resolve>(); Assert.NotNull(logger); - } } } diff --git a/test/Steeltoe.Common.Autofac.Test/Options/OptionsContainerBuilderExtensions.cs b/test/Steeltoe.Common.Autofac.Test/Options/OptionsContainerBuilderExtensionsTest.cs similarity index 91% rename from test/Steeltoe.Common.Autofac.Test/Options/OptionsContainerBuilderExtensions.cs rename to test/Steeltoe.Common.Autofac.Test/Options/OptionsContainerBuilderExtensionsTest.cs index fd8b13f..6672360 100644 --- a/test/Steeltoe.Common.Autofac.Test/Options/OptionsContainerBuilderExtensions.cs +++ b/test/Steeltoe.Common.Autofac.Test/Options/OptionsContainerBuilderExtensionsTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Autofac; using Microsoft.Extensions.Configuration; @@ -39,7 +37,6 @@ namespace Steeltoe.Common.Options.Autofac.Test Assert.Throws(() => container.RegisterOption(null)); ContainerBuilder container2 = new ContainerBuilder(); Assert.Throws(() => container2.RegisterOption(null)); - } [Fact] @@ -60,10 +57,9 @@ namespace Steeltoe.Common.Options.Autofac.Test var service = built.Resolve>(); Assert.NotNull(service); Assert.NotNull(service.Value); - Assert.Equal("foobar", service.Value.f1); + Assert.Equal("foobar", service.Value.F1); } - [Fact] public void RegisterPostConfigure_Registers_RunsPostAction() { @@ -79,7 +75,7 @@ namespace Steeltoe.Common.Options.Autofac.Test container.RegisterOption(config); container.RegisterPostConfigure((opt) => { - opt.f1 = "changed"; + opt.F1 = "changed"; }); var built = container.Build(); @@ -87,12 +83,12 @@ namespace Steeltoe.Common.Options.Autofac.Test var service = built.Resolve>(); Assert.NotNull(service); Assert.NotNull(service.Value); - Assert.Equal("changed", service.Value.f1); + Assert.Equal("changed", service.Value.F1); } - class MyOption + private class MyOption { - public string f1 { get; set; } + public string F1 { get; set; } } } } diff --git a/test/Steeltoe.Common.Autofac.Test/Steeltoe.Common.Autofac.Test.csproj b/test/Steeltoe.Common.Autofac.Test/Steeltoe.Common.Autofac.Test.csproj index b8b4506..39570d5 100644 --- a/test/Steeltoe.Common.Autofac.Test/Steeltoe.Common.Autofac.Test.csproj +++ b/test/Steeltoe.Common.Autofac.Test/Steeltoe.Common.Autofac.Test.csproj @@ -13,7 +13,7 @@ - SA1100;SA1101;SA1202;SA1204;SA1309;SA1310;SA1313;SA1402;SA1600;SA1652;1591;1701;1702;1705 + SA1101;SA1309;SA1310;SA1401;SA1600;SA1652;1591 @@ -25,9 +25,11 @@ - - + + All + + stylecop.json diff --git a/test/Steeltoe.Common.Http.Test/DiscoveryHttpClientHandlerBaseTest.cs b/test/Steeltoe.Common.Http.Test/DiscoveryHttpClientHandlerBaseTest.cs index 91da6c7..38d3d80 100644 --- a/test/Steeltoe.Common.Http.Test/DiscoveryHttpClientHandlerBaseTest.cs +++ b/test/Steeltoe.Common.Http.Test/DiscoveryHttpClientHandlerBaseTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,12 +11,10 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Steeltoe.Common.Discovery; using System; using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; using Xunit; @@ -43,10 +40,12 @@ namespace Steeltoe.Common.Http.Test IDiscoveryClient client = new TestDiscoveryClient(); DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); Uri uri = new Uri("http://foo:8080/test"); + // Act and Assert var result = handler.LookupService(uri); Assert.Equal(uri, result); } + [Fact] public void LookupService_DoesntFindService_ReturnsOriginalURI() { @@ -67,113 +66,10 @@ namespace Steeltoe.Common.Http.Test IDiscoveryClient client = new TestDiscoveryClient(new TestServiceInstance(new Uri("http://foundit:5555"))); DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); Uri uri = new Uri("http://foo/test/bar/foo?test=1&test2=2"); + // Act and Assert var result = handler.LookupService(uri); Assert.Equal(new Uri("http://foundit:5555/test/bar/foo?test=1&test2=2"), result); } - } - - class TestDiscoveryClient : IDiscoveryClient - { - - private IServiceInstance _instance; - public TestDiscoveryClient(IServiceInstance instance = null) - { - _instance = instance; - } - public string Description - { - get - { - throw new NotImplementedException(); - } - } - - public IList Services - { - get - { - throw new NotImplementedException(); - } - } - - public IList GetInstances(string serviceId) - { - if (_instance != null) - { - return new List() { _instance }; - } - return new List(); - - } - - public IServiceInstance GetLocalServiceInstance() - { - throw new NotImplementedException(); - } - - public Task ShutdownAsync() - { - throw new NotImplementedException(); - } - } - - class TestServiceInstance : IServiceInstance - { - - private Uri _uri; - public TestServiceInstance(Uri uri) - { - _uri = uri; - } - public string Host - { - get - { - throw new NotImplementedException(); - } - } - - public bool IsSecure - { - get - { - throw new NotImplementedException(); - } - } - - public IDictionary Metadata - { - get - { - throw new NotImplementedException(); - } - } - - public int Port - { - get - { - throw new NotImplementedException(); - } - } - - public string ServiceId - { - get - { - throw new NotImplementedException(); - } - } - - public Uri Uri - { - get - { - return _uri; - } - } - } -} - +} \ No newline at end of file diff --git a/test/Steeltoe.Common.Http.Test/HttpClientHelperTest.cs b/test/Steeltoe.Common.Http.Test/HttpClientHelperTest.cs index 1d5cca0..8d66f0f 100644 --- a/test/Steeltoe.Common.Http.Test/HttpClientHelperTest.cs +++ b/test/Steeltoe.Common.Http.Test/HttpClientHelperTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using System; using System.Net; @@ -79,6 +77,7 @@ namespace Steeltoe.Common.Http.Test Assert.Null(ServicePointManager.ServerCertificateValidationCallback); } } + [Fact] public void RestoreCertificateValidation_ValidateFalse() { @@ -153,6 +152,7 @@ namespace Steeltoe.Common.Http.Test Assert.Throws(() => HttpClientHelper.GetRequestMessage(null, null, null, null)); Assert.Throws(() => HttpClientHelper.GetRequestMessage(HttpMethod.Get, null, null, null)); } + [Fact] public void GetRequestMessage_CreatesCorrectMessage() { @@ -161,7 +161,6 @@ namespace Steeltoe.Common.Http.Test Assert.Equal(HttpMethod.Put, message.Method); Assert.Equal("http://localhost/foobar", message.RequestUri.ToString()); Assert.Null(message.Headers.Authorization); - } [Fact] @@ -197,9 +196,7 @@ namespace Steeltoe.Common.Http.Test else { Assert.NotNull(del1); - } } } - } diff --git a/test/Steeltoe.Common.Http.Test/SerializationHelperTest.cs b/test/Steeltoe.Common.Http.Test/SerializationHelperTest.cs index 9f0901f..2e2763b 100644 --- a/test/Steeltoe.Common.Http.Test/SerializationHelperTest.cs +++ b/test/Steeltoe.Common.Http.Test/SerializationHelperTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using System; using System.IO; @@ -47,13 +45,14 @@ namespace Steeltoe.Common.Http.Test var result = SerializationHelper.Deserialize(memStream); Assert.NotNull(result); - Assert.Equal(100, result.f1); - Assert.Equal(200, result.f2); + Assert.Equal(100, result.F1); + Assert.Equal(200, result.F2); } - class Test + + private class Test { - public int f1=0; - public long f2=0; + public int F1 = 0; + public long F2 = 0; } } } diff --git a/test/Steeltoe.Common.Http.Test/Steeltoe.Common.Http.Test.csproj b/test/Steeltoe.Common.Http.Test/Steeltoe.Common.Http.Test.csproj index 65547ad..d315b6e 100644 --- a/test/Steeltoe.Common.Http.Test/Steeltoe.Common.Http.Test.csproj +++ b/test/Steeltoe.Common.Http.Test/Steeltoe.Common.Http.Test.csproj @@ -14,7 +14,7 @@ - SA1100;SA1101;SA1202;SA1204;SA1309;SA1310;SA1313;SA1402;SA1600;SA1652;1591;1701;1702;1705 + SA1101;SA1309;SA1310;SA1401;SA1600;SA1652;1591 @@ -27,6 +27,9 @@ + + All + diff --git a/test/Steeltoe.Common.Http.Test/TestDiscoveryClient.cs b/test/Steeltoe.Common.Http.Test/TestDiscoveryClient.cs new file mode 100644 index 0000000..5291bc3 --- /dev/null +++ b/test/Steeltoe.Common.Http.Test/TestDiscoveryClient.cs @@ -0,0 +1,67 @@ +// Copyright 2017 the original author or authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Steeltoe.Common.Discovery; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Steeltoe.Common.Http.Test +{ + internal class TestDiscoveryClient : IDiscoveryClient + { + private IServiceInstance _instance; + + public TestDiscoveryClient(IServiceInstance instance = null) + { + _instance = instance; + } + + public string Description + { + get + { + throw new NotImplementedException(); + } + } + + public IList Services + { + get + { + throw new NotImplementedException(); + } + } + + public IList GetInstances(string serviceId) + { + if (_instance != null) + { + return new List() { _instance }; + } + + return new List(); + } + + public IServiceInstance GetLocalServiceInstance() + { + throw new NotImplementedException(); + } + + public Task ShutdownAsync() + { + throw new NotImplementedException(); + } + } +} diff --git a/test/Steeltoe.Common.Http.Test/TestServiceInstance.cs b/test/Steeltoe.Common.Http.Test/TestServiceInstance.cs new file mode 100644 index 0000000..cf2067d --- /dev/null +++ b/test/Steeltoe.Common.Http.Test/TestServiceInstance.cs @@ -0,0 +1,78 @@ +// Copyright 2017 the original author or authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Steeltoe.Common.Discovery; +using System; +using System.Collections.Generic; + +namespace Steeltoe.Common.Http.Test +{ + internal class TestServiceInstance : IServiceInstance + { + private Uri _uri; + + public TestServiceInstance(Uri uri) + { + _uri = uri; + } + + public string Host + { + get + { + throw new NotImplementedException(); + } + } + + public bool IsSecure + { + get + { + throw new NotImplementedException(); + } + } + + public IDictionary Metadata + { + get + { + throw new NotImplementedException(); + } + } + + public int Port + { + get + { + throw new NotImplementedException(); + } + } + + public string ServiceId + { + get + { + throw new NotImplementedException(); + } + } + + public Uri Uri + { + get + { + return _uri; + } + } + } +} diff --git a/test/Steeltoe.Common.Test/Configuration/ConfigurationValuesHelperTest.cs b/test/Steeltoe.Common.Test/Configuration/ConfigurationValuesHelperTest.cs index fe14bdc..2a1dd67 100644 --- a/test/Steeltoe.Common.Test/Configuration/ConfigurationValuesHelperTest.cs +++ b/test/Steeltoe.Common.Test/Configuration/ConfigurationValuesHelperTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Configuration; using System; @@ -211,6 +209,7 @@ namespace Steeltoe.Common.Configuration.Test var result = ConfigurationValuesHelper.GetSetting("a:b", config1, config2, null, "foobar"); Assert.Equal("setting1", result); } + [Fact] public void GetSetting_GetsFromSecond() { diff --git a/test/Steeltoe.Common.Test/Configuration/PropertyPlaceholderHelperTest.cs b/test/Steeltoe.Common.Test/Configuration/PropertyPlaceholderHelperTest.cs index 3df4c54..812e310 100644 --- a/test/Steeltoe.Common.Test/Configuration/PropertyPlaceholderHelperTest.cs +++ b/test/Steeltoe.Common.Test/Configuration/PropertyPlaceholderHelperTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Configuration; using System.Collections.Generic; @@ -23,17 +21,15 @@ namespace Steeltoe.Common.Configuration.Test { public class PropertyPlaceholderHelperTest { - [Fact] public void ResolvePlaceholders_ResolvesSinglePlaceholder() { - // Arrange string text = "foo=${foo}"; ConfigurationBuilder builder = new ConfigurationBuilder(); var dic1 = new Dictionary() { - {"foo", "bar"} + { "foo", "bar" } }; builder.AddInMemoryCollection(dic1); var config = builder.Build(); @@ -42,38 +38,35 @@ namespace Steeltoe.Common.Configuration.Test string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, config); Assert.Equal("foo=bar", result); } + [Fact] public void ResolvePlaceholders_ResolvesMultiplePlaceholders() { - // Arrange string text = "foo=${foo},bar=${bar}"; ConfigurationBuilder builder = new ConfigurationBuilder(); var dic1 = new Dictionary() { - {"foo", "bar"}, - {"bar", "baz" } - + { "foo", "bar" }, + { "bar", "baz" } }; builder.AddInMemoryCollection(dic1); - var config = builder.Build(); // Act and Assert - string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, config); + string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, builder.Build()); Assert.Equal("foo=bar,bar=baz", result); } + [Fact] public void ResolvePlaceholders_ResolvesMultipleRecursivePlaceholders() { - // Arrange string text = "foo=${bar}"; ConfigurationBuilder builder = new ConfigurationBuilder(); var dic1 = new Dictionary() { - {"bar", "${baz}"}, - {"baz", "bar"} - + { "bar", "${baz}" }, + { "baz", "bar" } }; builder.AddInMemoryCollection(dic1); var config = builder.Build(); @@ -86,15 +79,13 @@ namespace Steeltoe.Common.Configuration.Test [Fact] public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders() { - // Arrange string text1 = "foo=${b${inner}}"; ConfigurationBuilder builder1 = new ConfigurationBuilder(); var dic1 = new Dictionary() { - {"bar", "bar"}, - {"inner", "ar"} - + { "bar", "bar" }, + { "inner", "ar" } }; builder1.AddInMemoryCollection(dic1); var config1 = builder1.Build(); @@ -103,33 +94,30 @@ namespace Steeltoe.Common.Configuration.Test ConfigurationBuilder builder2 = new ConfigurationBuilder(); var dic2 = new Dictionary() { - {"top", "${child}+${child}"}, - {"child", "${${differentiator}.grandchild}" }, - {"differentiator", "first" }, - {"first.grandchild", "actualValue" } + { "top", "${child}+${child}" }, + { "child", "${${differentiator}.grandchild}" }, + { "differentiator", "first" }, + { "first.grandchild", "actualValue" } }; builder2.AddInMemoryCollection(dic2); var config2 = builder2.Build(); - // Act and Assert string result1 = PropertyPlaceholderHelper.ResolvePlaceholders(text1, config1); Assert.Equal("foo=bar", result1); string result2 = PropertyPlaceholderHelper.ResolvePlaceholders(text2, config2); Assert.Equal("actualValue+actualValue", result2); - } + [Fact] public void ResolvePlaceholders_UnresolvedPlaceholderIsIgnored() { - // Arrange string text = "foo=${foo},bar=${bar}"; ConfigurationBuilder builder = new ConfigurationBuilder(); var dic1 = new Dictionary() { - {"foo", "bar"} - + { "foo", "bar" } }; builder.AddInMemoryCollection(dic1); var config = builder.Build(); @@ -142,7 +130,6 @@ namespace Steeltoe.Common.Configuration.Test [Fact] public void ResolvePlaceholders_ResolvesArrayRefPlaceholder() { - // Arrange var json1 = @" { @@ -187,13 +174,11 @@ namespace Steeltoe.Common.Configuration.Test Assert.Equal("foo=my-app2.10.244.0.34.xip.io", result); } - static string CreateTempFile(string contents) + private static string CreateTempFile(string contents) { var tempFile = Path.GetTempFileName(); File.WriteAllText(tempFile, contents); return tempFile; - } - } } diff --git a/test/Steeltoe.Common.Test/Discovery/DiscoveryOptionsTest.cs b/test/Steeltoe.Common.Test/Discovery/DiscoveryOptionsTest.cs index 36578f9..f54c8db 100644 --- a/test/Steeltoe.Common.Test/Discovery/DiscoveryOptionsTest.cs +++ b/test/Steeltoe.Common.Test/Discovery/DiscoveryOptionsTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Configuration; using System; @@ -39,6 +37,5 @@ namespace Steeltoe.Common.Discovery.Test var ex = Assert.Throws(() => new DiscoveryOptions(config)); Assert.Contains(nameof(config), ex.Message); } - } } diff --git a/test/Steeltoe.Common.Test/Options/AbstractOptionsTest.cs b/test/Steeltoe.Common.Test/Options/AbstractOptionsTest.cs index 191a14d..0ed104a 100644 --- a/test/Steeltoe.Common.Test/Options/AbstractOptionsTest.cs +++ b/test/Steeltoe.Common.Test/Options/AbstractOptionsTest.cs @@ -1,5 +1,4 @@ -// -// Copyright 2017 the original author or authors. +// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// using Microsoft.Extensions.Configuration; using Steeltoe.Common.Options; @@ -32,7 +30,6 @@ namespace Steeltoe.Common.Test.Options Assert.Throws(() => new TestOptions(root, "foobar")); Assert.Throws(() => new TestOptions(config)); - } [Fact] @@ -41,7 +38,7 @@ namespace Steeltoe.Common.Test.Options var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(new Dictionary() { - {"foo", "bar" } + { "foo", "bar" } }); IConfigurationRoot root = builder.Build(); @@ -50,31 +47,17 @@ namespace Steeltoe.Common.Test.Options var opt1 = new TestOptions(root); Assert.Equal("bar", opt1.Foo); - var opt2 = new TestOptions(config); Assert.Equal("bar", opt2.Foo); var builder2 = new ConfigurationBuilder(); builder2.AddInMemoryCollection(new Dictionary() { - {"prefix:foo", "bar" } + { "prefix:foo", "bar" } }); IConfigurationRoot root2 = builder2.Build(); var opt3 = new TestOptions(root2, "prefix"); Assert.Equal("bar", opt3.Foo); } } - - class TestOptions : AbstractOptions - { - public string Foo { get; set; } - public TestOptions(IConfigurationRoot root , string prefix) : base(root, prefix) - { - - } - public TestOptions(IConfiguration config) : base (config) - { - - } - } } diff --git a/test/Steeltoe.Common.Test/Options/TestOptions.cs b/test/Steeltoe.Common.Test/Options/TestOptions.cs new file mode 100644 index 0000000..47e8a3e --- /dev/null +++ b/test/Steeltoe.Common.Test/Options/TestOptions.cs @@ -0,0 +1,34 @@ +// Copyright 2017 the original author or authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Microsoft.Extensions.Configuration; +using Steeltoe.Common.Options; + +namespace Steeltoe.Common.Test.Options +{ + internal class TestOptions : AbstractOptions + { + public TestOptions(IConfigurationRoot root, string prefix) + : base(root, prefix) + { + } + + public TestOptions(IConfiguration config) + : base(config) + { + } + + public string Foo { get; set; } + } +} diff --git a/test/Steeltoe.Common.Test/Steeltoe.Common.Test.csproj b/test/Steeltoe.Common.Test/Steeltoe.Common.Test.csproj index e6e10dc..669873d 100644 --- a/test/Steeltoe.Common.Test/Steeltoe.Common.Test.csproj +++ b/test/Steeltoe.Common.Test/Steeltoe.Common.Test.csproj @@ -14,7 +14,7 @@ - SA1100;SA1101;SA1202;SA1204;SA1309;SA1310;SA1313;SA1402;SA1600;SA1652;1591;1701;1702;1705 + SA1101;SA1309;SA1310;SA1401;SA1600;SA1652;1591 @@ -27,6 +27,9 @@ + + All +