Updates for stylecop compatability

This commit is contained in:
Dave Tillman 2017-12-12 13:29:26 -07:00
Родитель 46cbfe1f07
Коммит b06343362c
46 изменённых файлов: 643 добавлений и 543 удалений

Просмотреть файл

@ -1,7 +1,7 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15 # Visual Studio 15
VisualStudioVersion = 15.0.27004.2005 VisualStudioVersion = 15.0.27004.2010
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D9798FDE-76F4-4848-8AE0-95249C0101F0}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D9798FDE-76F4-4848-8AE0-95249C0101F0}"
EndProject EndProject
@ -34,6 +34,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
.travis.yml = .travis.yml .travis.yml = .travis.yml
appveyor.yml = appveyor.yml appveyor.yml = appveyor.yml
README.md = README.md README.md = README.md
stylecop.json = stylecop.json
EndProjectSection EndProjectSection
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Steeltoe.Common", "src\Steeltoe.Common\Steeltoe.Common.csproj", "{4AEA9704-3B99-4317-A959-7D6E4CDD4811}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Steeltoe.Common", "src\Steeltoe.Common\Steeltoe.Common.csproj", "{4AEA9704-3B99-4317-A959-7D6E4CDD4811}"

Просмотреть файл

@ -6,6 +6,7 @@
<AspNetCoreTestVersion>2.0.0</AspNetCoreTestVersion> <AspNetCoreTestVersion>2.0.0</AspNetCoreTestVersion>
<AspNetCoreMvcTestVersion>2.0.0</AspNetCoreMvcTestVersion> <AspNetCoreMvcTestVersion>2.0.0</AspNetCoreMvcTestVersion>
<AutofacVersion>4.6.1</AutofacVersion> <AutofacVersion>4.6.1</AutofacVersion>
<StyleCopVersion>1.0.2</StyleCopVersion>
<HttpVersion>4.3.3</HttpVersion> <HttpVersion>4.3.3</HttpVersion>
<MockHttpVersion>3.2.1</MockHttpVersion> <MockHttpVersion>3.2.1</MockHttpVersion>
<CoreFxVersion>4.4.0</CoreFxVersion> <CoreFxVersion>4.4.0</CoreFxVersion>

Просмотреть файл

@ -6,6 +6,7 @@
<AspNetCoreTestVersion>2.0.0</AspNetCoreTestVersion> <AspNetCoreTestVersion>2.0.0</AspNetCoreTestVersion>
<AspNetCoreMvcTestVersion>2.0.0</AspNetCoreMvcTestVersion> <AspNetCoreMvcTestVersion>2.0.0</AspNetCoreMvcTestVersion>
<AutofacVersion>4.6.1</AutofacVersion> <AutofacVersion>4.6.1</AutofacVersion>
<StyleCopVersion>1.0.2</StyleCopVersion>
<HttpVersion>4.3.3</HttpVersion> <HttpVersion>4.3.3</HttpVersion>
<MockHttpVersion>3.2.1</MockHttpVersion> <MockHttpVersion>3.2.1</MockHttpVersion>
<CoreFxVersion>4.4.0</CoreFxVersion> <CoreFxVersion>4.4.0</CoreFxVersion>

Просмотреть файл

@ -6,6 +6,7 @@
<AspNetCoreTestVersion>2.0.0</AspNetCoreTestVersion> <AspNetCoreTestVersion>2.0.0</AspNetCoreTestVersion>
<AspNetCoreMvcTestVersion>2.0.0</AspNetCoreMvcTestVersion> <AspNetCoreMvcTestVersion>2.0.0</AspNetCoreMvcTestVersion>
<AutofacVersion>4.6.1</AutofacVersion> <AutofacVersion>4.6.1</AutofacVersion>
<StyleCopVersion>1.0.2</StyleCopVersion>
<HttpVersion>4.3.3</HttpVersion> <HttpVersion>4.3.3</HttpVersion>
<MockHttpVersion>3.2.1</MockHttpVersion> <MockHttpVersion>3.2.1</MockHttpVersion>
<CoreFxVersion>4.4.0</CoreFxVersion> <CoreFxVersion>4.4.0</CoreFxVersion>

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Autofac; using Autofac;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System; using System;
namespace Steeltoe.Common.Configuration.Autofac namespace Steeltoe.Common.Configuration.Autofac
{ {
/// <summary>
/// Extension methods for registering IConfiguration with the Autofac container
/// </summary>
public static class ConfigurationContainerBuilderExtensions public static class ConfigurationContainerBuilderExtensions
{ {
/// <summary>
/// Register IConfiguration and IConfgurationRoot with the Autofac container
/// </summary>
/// <param name="container">the container builder to register with</param>
/// <param name="configuration">the configuration instance to add to the container</param>
public static void RegisterConfiguration(this ContainerBuilder container, IConfiguration configuration) public static void RegisterConfiguration(this ContainerBuilder container, IConfiguration configuration)
{ {
if (container == null) if (container == null)
{ {
throw new ArgumentNullException(nameof(container)); throw new ArgumentNullException(nameof(container));
} }
if (configuration == null) if (configuration == null)
{ {
throw new ArgumentNullException(nameof(configuration)); throw new ArgumentNullException(nameof(configuration));
} }
container.RegisterInstance(configuration).As<IConfigurationRoot>().SingleInstance(); container.RegisterInstance(configuration).As<IConfigurationRoot>().SingleInstance();
container.RegisterInstance(configuration).As<IConfiguration>().SingleInstance(); container.RegisterInstance(configuration).As<IConfiguration>().SingleInstance();
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Steeltoe.Common.Logging.Autofac namespace Steeltoe.Common.Logging.Autofac
{ {
/// <summary>
/// Default logger level configuration when using the Autofac container
/// </summary>
public class DefaultLoggerLevelConfigureOptions : ConfigureOptions<LoggerFilterOptions> public class DefaultLoggerLevelConfigureOptions : ConfigureOptions<LoggerFilterOptions>
{ {
public DefaultLoggerLevelConfigureOptions(LogLevel level) : /// <summary>
base(options => options.MinLevel = level) /// Initializes a new instance of the <see cref="DefaultLoggerLevelConfigureOptions"/> class.
/// </summary>
/// <param name="level">default log level to configure</param>
public DefaultLoggerLevelConfigureOptions(LogLevel level)
: base(options => options.MinLevel = level)
{ {
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using System; using System;
namespace Steeltoe.Common.Logging.Autofac namespace Steeltoe.Common.Logging.Autofac
{ {
public class LoggerFilterConfigureOptions : IConfigureOptions<LoggerFilterOptions> public class LoggerFilterConfigureOptions : IConfigureOptions<LoggerFilterOptions>
{ {
private readonly IConfiguration _configuration; private readonly IConfiguration configuration;
public LoggerFilterConfigureOptions(IConfiguration configuration) public LoggerFilterConfigureOptions(IConfiguration configuration)
{ {
_configuration = configuration; this.configuration = configuration;
} }
public void Configure(LoggerFilterOptions options) public void Configure(LoggerFilterOptions options)
@ -36,14 +33,31 @@ namespace Steeltoe.Common.Logging.Autofac
LoadDefaultConfigValues(options); 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) private void LoadDefaultConfigValues(LoggerFilterOptions options)
{ {
if (_configuration == null) if (configuration == null)
{ {
return; return;
} }
foreach (var configurationSection in _configuration.GetChildren()) foreach (var configurationSection in configuration.GetChildren())
{ {
if (configurationSection.Key == "LogLevel") if (configurationSection.Key == "LogLevel")
{ {
@ -75,27 +89,11 @@ namespace Steeltoe.Common.Logging.Autofac
{ {
category = null; category = null;
} }
var newRule = new LoggerFilterRule(logger, category, level, null); var newRule = new LoggerFilterRule(logger, category, level, null);
options.Rules.Add(newRule); 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.");
}
}
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Autofac; using Autofac;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -45,12 +43,14 @@ namespace Steeltoe.Common.Logging.Autofac
container.RegisterInstance(new LoggerFilterConfigureOptions(config)).As<IConfigureOptions<LoggerFilterOptions>>().SingleInstance(); container.RegisterInstance(new LoggerFilterConfigureOptions(config)).As<IConfigureOptions<LoggerFilterOptions>>().SingleInstance();
container.RegisterInstance(new ConfigurationChangeTokenSource<LoggerFilterOptions>(config)).As<IOptionsChangeTokenSource<LoggerFilterOptions>>().SingleInstance(); container.RegisterInstance(new ConfigurationChangeTokenSource<LoggerFilterOptions>(config)).As<IOptionsChangeTokenSource<LoggerFilterOptions>>().SingleInstance();
} }
public static void RegisterConsoleLogging(this ContainerBuilder container) public static void RegisterConsoleLogging(this ContainerBuilder container)
{ {
if (container == null) if (container == null)
{ {
throw new ArgumentNullException(nameof(container)); throw new ArgumentNullException(nameof(container));
} }
container.RegisterType<ConsoleLoggerProvider>().As<ILoggerProvider>(); container.RegisterType<ConsoleLoggerProvider>().As<ILoggerProvider>();
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Autofac; using Autofac;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using System; using System;
namespace Steeltoe.Common.Options.Autofac namespace Steeltoe.Common.Options.Autofac
{ {
public static class OptionsContainerBuilderExtensions public static class OptionsContainerBuilderExtensions
@ -38,10 +35,12 @@ namespace Steeltoe.Common.Options.Autofac
container.RegisterGeneric(typeof(OptionsFactory<>)).As(typeof(IOptionsFactory<>)).InstancePerDependency(); container.RegisterGeneric(typeof(OptionsFactory<>)).As(typeof(IOptionsFactory<>)).InstancePerDependency();
} }
public static void RegisterOption<TOption>(this ContainerBuilder container, IConfiguration config) where TOption : class public static void RegisterOption<TOption>(this ContainerBuilder container, IConfiguration config)
where TOption : class
=> container.RegisterOption<TOption>(Microsoft.Extensions.Options.Options.DefaultName, config); => container.RegisterOption<TOption>(Microsoft.Extensions.Options.Options.DefaultName, config);
public static void RegisterOption<TOption>(this ContainerBuilder container, string name, IConfiguration config) where TOption : class public static void RegisterOption<TOption>(this ContainerBuilder container, string name, IConfiguration config)
where TOption : class
{ {
if (container == null) if (container == null)
{ {
@ -57,10 +56,12 @@ namespace Steeltoe.Common.Options.Autofac
container.RegisterInstance(new NamedConfigureFromConfigurationOptions<TOption>(name, config)).As<IConfigureOptions<TOption>>().SingleInstance(); container.RegisterInstance(new NamedConfigureFromConfigurationOptions<TOption>(name, config)).As<IConfigureOptions<TOption>>().SingleInstance();
} }
public static void RegisterPostConfigure<TOptions>(this ContainerBuilder container, Action<TOptions> configureOptions) where TOptions : class public static void RegisterPostConfigure<TOptions>(this ContainerBuilder container, Action<TOptions> configureOptions)
where TOptions : class
=> container.RegisterPostConfigure(Microsoft.Extensions.Options.Options.DefaultName, configureOptions); => container.RegisterPostConfigure(Microsoft.Extensions.Options.Options.DefaultName, configureOptions);
public static void RegisterPostConfigure<TOptions>(this ContainerBuilder container, string name, Action<TOptions> configureOptions) where TOptions : class public static void RegisterPostConfigure<TOptions>(this ContainerBuilder container, string name, Action<TOptions> configureOptions)
where TOptions : class
{ {
if (container == null) if (container == null)
{ {
@ -71,6 +72,7 @@ namespace Steeltoe.Common.Options.Autofac
{ {
throw new ArgumentNullException(nameof(configureOptions)); throw new ArgumentNullException(nameof(configureOptions));
} }
container.RegisterInstance(new PostConfigureOptions<TOptions>(name, configureOptions)).As<IPostConfigureOptions<TOptions>>().SingleInstance(); container.RegisterInstance(new PostConfigureOptions<TOptions>(name, configureOptions)).As<IPostConfigureOptions<TOptions>>().SingleInstance();
} }
} }

Просмотреть файл

@ -17,14 +17,16 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Autofac.xml</DocumentationFile> <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Autofac.xml</DocumentationFile>
<NoWarn>SA1101;SA1309;SA1310;SA1401;SA1600;1591</NoWarn>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<NoWarn>SA1100;SA1101;SA1124;SA1202;SA1204;SA1309;SA1310;SA1313;SA1600;SA1611;1591;1701;1702;1705</NoWarn>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Autofac" Version="$(AutofacVersion)" /> <PackageReference Include="Autofac" Version="$(AutofacVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="$(AspNetCoreVersion)" />
<PackageReference Include="StyleCop.Analyzers" Version="$(StyleCopVersion)">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<AdditionalFiles Include="..\..\stylecop.json"> <AdditionalFiles Include="..\..\stylecop.json">

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -20,7 +18,7 @@ namespace Steeltoe.Common.Discovery
{ {
public class DiscoveryHttpClientHandler : DiscoveryHttpClientHandlerBase public class DiscoveryHttpClientHandler : DiscoveryHttpClientHandlerBase
{ {
public DiscoveryHttpClientHandler(IDiscoveryClient client, ILogger logger = null) public DiscoveryHttpClientHandler(IDiscoveryClient client, ILogger logger = null)
: base(client, logger) : base(client, logger)
{ {
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
@ -24,9 +22,9 @@ namespace Steeltoe.Common.Discovery
{ {
public class DiscoveryHttpClientHandlerBase : HttpClientHandler public class DiscoveryHttpClientHandlerBase : HttpClientHandler
{ {
protected static Random _random = new Random();
protected IDiscoveryClient _client; protected IDiscoveryClient _client;
protected ILogger _logger; protected ILogger _logger;
protected static Random _random = new Random();
public DiscoveryHttpClientHandlerBase(IDiscoveryClient client, ILogger logger = null) public DiscoveryHttpClientHandlerBase(IDiscoveryClient client, ILogger logger = null)
{ {
@ -39,25 +37,6 @@ namespace Steeltoe.Common.Discovery
_logger = logger; _logger = logger;
} }
protected override async Task<HttpResponseMessage> 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) public virtual Uri LookupService(Uri current)
{ {
_logger?.LogDebug("LookupService({0})", current.ToString()); _logger?.LogDebug("LookupService({0})", current.ToString());
@ -72,11 +51,28 @@ namespace Steeltoe.Common.Discovery
int indx = _random.Next(instances.Count); int indx = _random.Next(instances.Count);
current = new Uri(instances[indx].Uri, current.PathAndQuery); current = new Uri(instances[indx].Uri, current.PathAndQuery);
} }
_logger?.LogDebug("LookupService() returning {0} ", current.ToString()); _logger?.LogDebug("LookupService() returning {0} ", current.ToString());
return current; return current;
} }
protected override async Task<HttpResponseMessage> 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;
}
}
} }
} }

Просмотреть файл

@ -42,9 +42,9 @@ namespace Steeltoe.Common.Http
/// </summary> /// </summary>
/// <typeparam name="T">Type of object to serialize</typeparam> /// <typeparam name="T">Type of object to serialize</typeparam>
/// <param name="httpClient">HttpClient doing the sending</param> /// <param name="httpClient">HttpClient doing the sending</param>
/// <param name="settings">Your Serializer Settings</param>
/// <param name="url">Url to POST to</param> /// <param name="url">Url to POST to</param>
/// <param name="data">Object to send</param> /// <param name="data">Object to send</param>
/// <param name="settings">Your Serializer Settings</param>
/// <returns>Task to be awaited</returns> /// <returns>Task to be awaited</returns>
public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient httpClient, string url, T data, JsonSerializerSettings settings) public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient httpClient, string url, T data, JsonSerializerSettings settings)
{ {
@ -57,10 +57,10 @@ namespace Steeltoe.Common.Http
/// <summary> /// <summary>
/// Convert an object to JSON and PUT it /// Convert an object to JSON and PUT it
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T">the type of the data</typeparam>
/// <param name="httpClient"></param> /// <param name="httpClient">provided HttpClient</param>
/// <param name="url"></param> /// <param name="url">the http endpoint to Put to</param>
/// <param name="data"></param> /// <param name="data">the data to put</param>
/// <returns>Task to be awaited</returns> /// <returns>Task to be awaited</returns>
public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient httpClient, string url, T data) public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient httpClient, string url, T data)
{ {
@ -73,11 +73,11 @@ namespace Steeltoe.Common.Http
/// <summary> /// <summary>
/// Convert an object to JSON and PUT it /// Convert an object to JSON and PUT it
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T">the type of the data</typeparam>
/// <param name="httpClient"></param> /// <param name="httpClient">provided HttpClient</param>
/// <param name="url"></param> /// <param name="url">the http endpoint to Put to</param>
/// <param name="data"></param> /// <param name="data">the data to put</param>
/// <param name="settings"></param> /// <param name="settings">the serialization setttings to use</param>
/// <returns>Task to be awaited</returns> /// <returns>Task to be awaited</returns>
public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient httpClient, string url, T data, JsonSerializerSettings settings) public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient httpClient, string url, T data, JsonSerializerSettings settings)
{ {

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@ -32,34 +30,12 @@ namespace Steeltoe.Common.Http
{ {
public static class HttpClientHelper public static class HttpClientHelper
{ {
internal static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _reflectedDelegate = null;
private const int DEFAULT_GETACCESSTOKEN_TIMEOUT = 10000; // Milliseconds private const int DEFAULT_GETACCESSTOKEN_TIMEOUT = 10000; // Milliseconds
private const bool DEFAULT_VALIDATE_CERTIFICATES = true; private const bool DEFAULT_VALIDATE_CERTIFICATES = true;
private static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> DefaultDelegate { get; } = (sender, cert, chain, sslPolicyErrors) => true;
internal static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _reflectedDelegate = null;
internal static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> GetDisableDelegate()
{
if (Platform.IsFullFramework)
{
return null;
}
if (_reflectedDelegate != null) private static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> DefaultDelegate { get; } = (sender, cert, chain, sslPolicyErrors) => true;
{
return _reflectedDelegate;
}
var property = typeof(HttpClientHandler).GetProperty("DangerousAcceptAnyServerCertificateValidator",
BindingFlags.Public | BindingFlags.Static);
if (property != null)
{
_reflectedDelegate = property.GetValue(null) as Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>;
if (_reflectedDelegate != null)
{
return _reflectedDelegate;
}
}
return DefaultDelegate;
}
public static HttpClient GetHttpClient(bool validateCertificates, int timeout) public static HttpClient GetHttpClient(bool validateCertificates, int timeout)
{ {
@ -70,7 +46,6 @@ namespace Steeltoe.Common.Http
} }
else else
{ {
if (!validateCertificates) if (!validateCertificates)
{ {
var handler = new HttpClientHandler(); var handler = new HttpClientHandler();
@ -83,10 +58,15 @@ namespace Steeltoe.Common.Http
client = new HttpClient(); client = new HttpClient();
} }
} }
client.Timeout = TimeSpan.FromMilliseconds(timeout); client.Timeout = TimeSpan.FromMilliseconds(timeout);
return client; 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; prevValidator = null;
protocolType = (SecurityProtocolType)0; 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 (Platform.IsFullFramework)
{ {
if (!validateCertificates) if (!validateCertificates)
@ -112,26 +95,31 @@ namespace Steeltoe.Common.Http
ServicePointManager.SecurityProtocol = protocolType; ServicePointManager.SecurityProtocol = protocolType;
ServicePointManager.ServerCertificateValidationCallback = prevValidator; ServicePointManager.ServerCertificateValidationCallback = prevValidator;
} }
} }
} }
public static string GetEncodedUserPassword(string user, string password) public static string GetEncodedUserPassword(string user, string password)
{ {
if (user == null) if (user == null)
{
user = string.Empty; user = string.Empty;
}
if (password == null) if (password == null)
{
password = string.Empty; password = string.Empty;
}
return Convert.ToBase64String(Encoding.ASCII.GetBytes(user + ":" + password)); return Convert.ToBase64String(Encoding.ASCII.GetBytes(user + ":" + password));
} }
public static HttpRequestMessage GetRequestMessage(HttpMethod method, string requestUri, Func<string> GetAccessToken) public static HttpRequestMessage GetRequestMessage(HttpMethod method, string requestUri, Func<string> getAccessToken)
{ {
var request = GetRequestMessage(method, requestUri, null, null); var request = GetRequestMessage(method, requestUri, null, null);
if (GetAccessToken != null) if (getAccessToken != null)
{ {
var accessToken = GetAccessToken(); var accessToken = getAccessToken();
if (accessToken != null) if (accessToken != null)
{ {
@ -139,6 +127,7 @@ namespace Steeltoe.Common.Http
request.Headers.Authorization = auth; request.Headers.Authorization = auth;
} }
} }
return request; return request;
} }
@ -157,16 +146,22 @@ namespace Steeltoe.Common.Http
var request = new HttpRequestMessage(method, requestUri); var request = new HttpRequestMessage(method, requestUri);
if (!string.IsNullOrEmpty(password)) if (!string.IsNullOrEmpty(password))
{ {
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Basic", AuthenticationHeaderValue auth = new AuthenticationHeaderValue(
"Basic",
GetEncodedUserPassword(userName, password)); GetEncodedUserPassword(userName, password));
request.Headers.Authorization = auth; request.Headers.Authorization = auth;
} }
return request; return request;
} }
public static async Task<string> GetAccessToken( public static async Task<string> GetAccessToken(
string accessTokenUri, string clientId, string clientSecret, string accessTokenUri,
int timeout = DEFAULT_GETACCESSTOKEN_TIMEOUT, bool validateCertificates = DEFAULT_VALIDATE_CERTIFICATES, ILogger logger = null) string clientId,
string clientSecret,
int timeout = DEFAULT_GETACCESSTOKEN_TIMEOUT,
bool validateCertificates = DEFAULT_VALIDATE_CERTIFICATES,
ILogger logger = null)
{ {
if (string.IsNullOrEmpty(accessTokenUri)) if (string.IsNullOrEmpty(accessTokenUri))
@ -183,6 +178,7 @@ namespace Steeltoe.Common.Http
{ {
throw new ArgumentException(nameof(accessTokenUri)); throw new ArgumentException(nameof(accessTokenUri));
} }
var request = new HttpRequestMessage(HttpMethod.Post, accessTokenUri); var request = new HttpRequestMessage(HttpMethod.Post, accessTokenUri);
HttpClient client = GetHttpClient(validateCertificates, timeout); HttpClient client = GetHttpClient(validateCertificates, timeout);
@ -207,8 +203,10 @@ namespace Steeltoe.Common.Http
{ {
if (response.StatusCode != HttpStatusCode.OK) if (response.StatusCode != HttpStatusCode.OK)
{ {
logger?.LogInformation("GetAccessToken returned status: {0} while obtaining access token from: {1}", logger?.LogInformation(
response.StatusCode, accessTokenUri); "GetAccessToken returned status: {0} while obtaining access token from: {1}",
response.StatusCode,
accessTokenUri);
return null; return null;
} }
@ -226,7 +224,36 @@ namespace Steeltoe.Common.Http
{ {
HttpClientHelper.RestoreCertificateValidation(validateCertificates, prevProtocols, prevValidator); HttpClientHelper.RestoreCertificateValidation(validateCertificates, prevProtocols, prevValidator);
} }
return null; return null;
} }
internal static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> 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<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>;
if (_reflectedDelegate != null)
{
return _reflectedDelegate;
}
}
return DefaultDelegate;
}
} }
} }

Просмотреть файл

@ -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")] [assembly: InternalsVisibleTo("Steeltoe.Common.Http.Test")]

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;

Просмотреть файл

@ -17,14 +17,16 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Http.xml</DocumentationFile> <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Http.xml</DocumentationFile>
<NoWarn>SA1101;SA1309;SA1310;SA1401;SA1600;1591</NoWarn>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<NoWarn>SA1100;SA1101;SA1124;SA1202;SA1204;SA1309;SA1310;SA1313;SA1600;SA1611;1591;1701;1702;1705</NoWarn>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="$(JsonNetVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(JsonNetVersion)" />
<PackageReference Include="System.Net.Http" Version="$(HttpVersion)" /> <PackageReference Include="System.Net.Http" Version="$(HttpVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="$(AspNetCoreVersion)" />
<PackageReference Include="StyleCop.Analyzers" Version="$(StyleCopVersion)">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(CI_BUILD)' == ''"> <ItemGroup Condition="'$(CI_BUILD)' == ''">

Просмотреть файл

@ -17,11 +17,13 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Net.xml</DocumentationFile> <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Net.xml</DocumentationFile>
<NoWarn>SA1101;SA1309;SA1310;SA1401;SA1600;SA1307;1591</NoWarn>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<NoWarn>SA1100;SA1101;SA1124;SA1202;SA1204;SA1309;SA1310;SA1313;SA1600;SA1611;1591;1701;1702;1705</NoWarn>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="$(StyleCopVersion)">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<AdditionalFiles Include="..\..\stylecop.json"> <AdditionalFiles Include="..\..\stylecop.json">

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using System; using System;
using System.Net; using System.Net;
@ -23,7 +21,59 @@ namespace Steeltoe.Common.Net
{ {
public class WindowsNetworkFileShare 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) public WindowsNetworkFileShare(string networkName, NetworkCredential credentials)
{ {
@ -41,7 +91,6 @@ namespace Steeltoe.Common.Net
? credentials.UserName ? credentials.UserName
: string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName); : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
var result = WNetUseConnection(IntPtr.Zero, netResource, credentials.Password, userName, 0, null, null, null); var result = WNetUseConnection(IntPtr.Zero, netResource, credentials.Password, userName, 0, null, null, null);
if (result != 0) if (result != 0)
@ -55,53 +104,6 @@ namespace Steeltoe.Common.Net
Dispose(false); 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 public enum ResourceScope : int
{ {
Connected = 1, Connected = 1,
@ -109,7 +111,7 @@ namespace Steeltoe.Common.Net
Remembered, Remembered,
Recent, Recent,
Context Context
}; }
public enum ResourceType : int public enum ResourceType : int
{ {
@ -134,80 +136,63 @@ namespace Steeltoe.Common.Net
Tree = 0x0a, Tree = 0x0a,
Ndscontainer = 0x0b Ndscontainer = 0x0b
} }
#region Errors
const int NO_ERROR = 0;
const int ERROR_ACCESS_DENIED = 5; [DllImport("mpr.dll", CharSet = CharSet.Auto)]
const int ERROR_ALREADY_ASSIGNED = 85; public static extern int WNetGetLastError(
const int ERROR_PATH_NOT_FOUND = 53; out int error,
const int ERROR_BAD_DEVICE = 1200; out StringBuilder errorBuf,
const int ERROR_BAD_NET_NAME = 67; int errorBufSize,
const int ERROR_BAD_PROVIDER = 1204; out StringBuilder nameBuf,
const int ERROR_CANCELLED = 1223; int nameBufSize);
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;
const int ERROR_BAD_PROFILE = 1206; public void Dispose()
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 int num; Dispose(true);
public string message; GC.SuppressFinalize(this);
public ErrorClass(int num, string message)
{
this.num = num;
this.message = message;
}
} }
protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}
// Created with excel formula: [DllImport("mpr.dll")]
// ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static extern int WNetAddConnection2(
private static ErrorClass[] ERROR_LIST = new ErrorClass[] { NetResource netResource,
new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), string password,
new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), string username,
new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), int flags);
new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"),
new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), [DllImport("mpr.dll")]
new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), private static extern int WNetCancelConnection2(
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), string name,
new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), int flags,
new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), bool force);
new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"),
new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), [DllImport("mpr.dll")]
new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), private static extern int WNetUseConnection(
new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), IntPtr hwndOwner,
new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), NetResource netResource,
new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), string password,
new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), string username,
new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), int flags,
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), string lpAccessName,
new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), string lpBufferSize,
new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), string lpResult);
new ErrorClass(ERROR_LOGON_FAILURE,"The user name or password is incorrect"),
new ErrorClass(ERROR_PATH_NOT_FOUND,"The network path not found")
};
private static string GetErrorForNumber(int errNum) 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; return "Error: Unknown, " + errNum;
} }
private static string GetLastError(int result) private static string GetLastError(int result)
{ {
StringBuilder sbErrorBuf = new StringBuilder(500); 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); int res = WNetGetLastError(out resultref, out sbErrorBuf, sbErrorBuf.Capacity, out sbNameBuf, sbNameBuf.Capacity);
return sbErrorBuf.ToString(); 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;
}
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System; using System;
namespace Steeltoe.Common.Configuration namespace Steeltoe.Common.Configuration
{ {
public static class ConfigurationValuesHelper public static class ConfigurationValuesHelper
{ {
public static string GetSetting(string key, IConfiguration primary, IConfiguration secondary, IConfiguration resolve, string def) public static string GetSetting(string key, IConfiguration primary, IConfiguration secondary, IConfiguration resolve, string def)
{ {
// First check for key in primary // First check for key in primary
@ -49,10 +45,14 @@ namespace Steeltoe.Common.Configuration
{ {
int result; int result;
if (int.TryParse(val, out result)) if (int.TryParse(val, out result))
{
return result; return result;
}
} }
return def; return def;
} }
public static double GetDouble(string key, IConfiguration config, IConfiguration resolve, double def) public static double GetDouble(string key, IConfiguration config, IConfiguration resolve, double def)
{ {
var val = GetString(key, config, resolve, null); var val = GetString(key, config, resolve, null);
@ -60,8 +60,11 @@ namespace Steeltoe.Common.Configuration
{ {
double result; double result;
if (double.TryParse(val, out result)) if (double.TryParse(val, out result))
{
return result; return result;
}
} }
return def; return def;
} }
@ -71,12 +74,15 @@ namespace Steeltoe.Common.Configuration
if (!string.IsNullOrEmpty(val)) if (!string.IsNullOrEmpty(val))
{ {
bool result; bool result;
if (Boolean.TryParse(val, out result)) if (bool.TryParse(val, out result))
{
return result; return result;
}
} }
return def;
return def;
} }
public static string GetString(string key, IConfiguration config, IConfiguration resolve, string def) public static string GetString(string key, IConfiguration config, IConfiguration resolve, string def)
{ {
if (string.IsNullOrEmpty(key)) if (string.IsNullOrEmpty(key))
@ -94,6 +100,7 @@ namespace Steeltoe.Common.Configuration
{ {
return PropertyPlaceholderHelper.ResolvePlaceholders(val, resolve); return PropertyPlaceholderHelper.ResolvePlaceholders(val, resolve);
} }
return def; return def;
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -25,9 +23,7 @@ namespace Steeltoe.Common.Configuration
/// <summary> /// <summary>
/// Utility class for working with configuration values that have placeholders in them. /// Utility class for working with configuration values that have placeholders in them.
/// A placeholder takes the form of <code> ${some:config:reference?default_if_not_present}></code> /// A placeholder takes the form of <code> ${some:config:reference?default_if_not_present}></code>
///
/// Note: This was "inspired" by the Spring class: PropertyPlaceholderHelper /// Note: This was "inspired" by the Spring class: PropertyPlaceholderHelper
///
/// </summary> /// </summary>
public static class PropertyPlaceholderHelper public static class PropertyPlaceholderHelper
{ {
@ -50,14 +46,15 @@ namespace Steeltoe.Common.Configuration
private static string ParseStringValue(string property, IConfiguration config, ISet<string> visitedPlaceHolders, ILogger logger = null) private static string ParseStringValue(string property, IConfiguration config, ISet<string> visitedPlaceHolders, ILogger logger = null)
{ {
if (config == null) if (config == null)
{ {
return property; return property;
} }
if (string.IsNullOrEmpty(property)) if (string.IsNullOrEmpty(property))
{
return property; return property;
}
StringBuilder result = new StringBuilder(property); StringBuilder result = new StringBuilder(property);
@ -67,19 +64,20 @@ namespace Steeltoe.Common.Configuration
int endIndex = FindEndIndex(result, startIndex); int endIndex = FindEndIndex(result, startIndex);
if (endIndex != -1) if (endIndex != -1)
{ {
string placeholder = result.Substring(startIndex + PREFIX.Length, endIndex); string placeholder = result.Substring(startIndex + PREFIX.Length, endIndex);
string originalPlaceholder = placeholder; string originalPlaceholder = placeholder;
if (!visitedPlaceHolders.Add(originalPlaceholder)) if (!visitedPlaceHolders.Add(originalPlaceholder))
{ {
throw new ArgumentException(String.Format("Circular placeholder reference '{0}' in property definitions", throw new ArgumentException($"Circular placeholder reference '{originalPlaceholder}' in property definitions");
originalPlaceholder));
} }
// Recursive invocation, parsing placeholders contained in the placeholder key. // Recursive invocation, parsing placeholders contained in the placeholder key.
placeholder = ParseStringValue(placeholder, config, visitedPlaceHolders); placeholder = ParseStringValue(placeholder, config, visitedPlaceHolders);
// Handle array references foo:bar[1]:baz format -> foo:bar:1:baz // 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... // Now obtain the value for the fully resolved key...
string propVal = config[lookup]; string propVal = config[lookup];
if (propVal == null) if (propVal == null)
@ -96,6 +94,7 @@ namespace Steeltoe.Common.Configuration
} }
} }
} }
if (propVal != null) if (propVal != null)
{ {
// Recursive invocation, parsing placeholders contained in these // Recursive invocation, parsing placeholders contained in these
@ -110,6 +109,7 @@ namespace Steeltoe.Common.Configuration
// Proceed with unprocessed value. // Proceed with unprocessed value.
startIndex = result.IndexOf(PREFIX, endIndex + PREFIX.Length); startIndex = result.IndexOf(PREFIX, endIndex + PREFIX.Length);
} }
visitedPlaceHolders.Remove(originalPlaceholder); visitedPlaceHolders.Remove(originalPlaceholder);
} }
else else
@ -121,14 +121,12 @@ namespace Steeltoe.Common.Configuration
return result.ToString(); return result.ToString();
} }
private static int FindEndIndex(StringBuilder property, int startIndex) private static int FindEndIndex(StringBuilder property, int startIndex)
{ {
int index = startIndex + PREFIX.Length; int index = startIndex + PREFIX.Length;
int withinNestedPlaceholder = 0; int withinNestedPlaceholder = 0;
while (index < property.Length) while (index < property.Length)
{ {
if (SubstringMatch(property, index, SUFFIX)) if (SubstringMatch(property, index, SUFFIX))
{ {
if (withinNestedPlaceholder > 0) if (withinNestedPlaceholder > 0)
@ -151,9 +149,10 @@ namespace Steeltoe.Common.Configuration
index++; index++;
} }
} }
return -1;
return -1;
} }
private static bool SubstringMatch(StringBuilder str, int index, string substring) private static bool SubstringMatch(StringBuilder str, int index, string substring)
{ {
for (int j = 0; j < substring.Length; j++) for (int j = 0; j < substring.Length; j++)
@ -164,6 +163,7 @@ namespace Steeltoe.Common.Configuration
return false; return false;
} }
} }
return true; return true;
} }
@ -172,12 +172,17 @@ namespace Steeltoe.Common.Configuration
builder.Remove(start, end - start); builder.Remove(start, end - start);
builder.Insert(start, str); builder.Insert(start, str);
} }
private static int IndexOf(this StringBuilder builder, string str, int start) private static int IndexOf(this StringBuilder builder, string str, int start)
{ {
if (start >= builder.Length) if (start >= builder.Length)
{
return -1; return -1;
}
return builder.ToString().IndexOf(str, start); return builder.ToString().IndexOf(str, start);
} }
private static string Substring(this StringBuilder builder, int start, int end) private static string Substring(this StringBuilder builder, int start, int end)
{ {
return builder.ToString().Substring(start, end - start); return builder.ToString().Substring(start, end - start);

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System; using System;
namespace Steeltoe.Common.Discovery namespace Steeltoe.Common.Discovery
{ {
public enum DiscoveryClientType
{
EUREKA, UNKNOWN
}
public class DiscoveryOptions 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) if (config == null)
{ {
throw new ArgumentNullException(nameof(config)); throw new ArgumentNullException(nameof(config));
} }
Configure(config);
Configure(config);
} }
public DiscoveryOptions() public DiscoveryOptions()
{ {
ClientType = DiscoveryClientType.UNKNOWN; ClientType = DiscoveryClientType.UNKNOWN;
@ -44,7 +52,6 @@ namespace Steeltoe.Common.Discovery
} }
} }
protected string _type;
public DiscoveryClientType ClientType public DiscoveryClientType ClientType
{ {
get get
@ -53,47 +60,45 @@ namespace Steeltoe.Common.Discovery
{ {
return DiscoveryClientType.UNKNOWN; return DiscoveryClientType.UNKNOWN;
} }
return (DiscoveryClientType)System.Enum.Parse(typeof(DiscoveryClientType), _type); return (DiscoveryClientType)System.Enum.Parse(typeof(DiscoveryClientType), _type);
} }
set set
{ {
_type = System.Enum.GetName(typeof(DiscoveryClientType), value); _type = System.Enum.GetName(typeof(DiscoveryClientType), value);
} }
} }
protected IDiscoveryClientOptions _clientOptions;
public IDiscoveryClientOptions ClientOptions public IDiscoveryClientOptions ClientOptions
{ {
get get
{ {
return _clientOptions; return _clientOptions;
} }
set set
{ {
_clientOptions = value; _clientOptions = value;
} }
} }
protected IDiscoveryRegistrationOptions _registrationOptions;
public IDiscoveryRegistrationOptions RegistrationOptions public IDiscoveryRegistrationOptions RegistrationOptions
{ {
get get
{ {
return _registrationOptions; return _registrationOptions;
} }
set set
{ {
_registrationOptions = value; _registrationOptions = value;
} }
} }
public virtual void Configure(IConfiguration config) public virtual void Configure(IConfiguration config)
{ {
ClientType = DiscoveryClientType.UNKNOWN; ClientType = DiscoveryClientType.UNKNOWN;
} }
} }
public enum DiscoveryClientType { EUREKA, UNKNOWN }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -23,30 +20,28 @@ namespace Steeltoe.Common.Discovery
public interface IDiscoveryClient public interface IDiscoveryClient
{ {
/// <summary> /// <summary>
/// A human readable description of the implementation /// Gets a human readable description of the implementation
/// </summary> /// </summary>
string Description { get; } string Description { get; }
/// <summary> /// <summary>
/// All known service Ids /// Gets all known service Ids
/// </summary> /// </summary>
IList<string> Services { get; } IList<string> Services { get; }
/// <summary> /// <summary>
/// ServiceInstance with information used to register the local service /// ServiceInstance with information used to register the local service
/// </summary> /// </summary>
/// <returns></returns> /// <returns>The IServiceInstance</returns>
IServiceInstance GetLocalServiceInstance(); IServiceInstance GetLocalServiceInstance();
/// <summary> /// <summary>
/// Get all ServiceInstances associated with a particular serviceId /// Get all ServiceInstances associated with a particular serviceId
/// </summary> /// </summary>
/// <param name="serviceId">the serviceId to lookup</param> /// <param name="serviceId">the serviceId to lookup</param>
/// <returns></returns> /// <returns>List of service instances</returns>
IList<IServiceInstance> GetInstances(String serviceId); IList<IServiceInstance> GetInstances(string serviceId);
Task ShutdownAsync(); Task ShutdownAsync();
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
namespace Steeltoe.Common.Discovery namespace Steeltoe.Common.Discovery
{ {

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using System.Threading; using System.Threading;

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
namespace Steeltoe.Common.Discovery namespace Steeltoe.Common.Discovery
{ {

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -22,27 +20,32 @@ namespace Steeltoe.Common.Discovery
public interface IServiceInstance public interface IServiceInstance
{ {
/// <summary> /// <summary>
/// The service id as register by the DiscoveryClient /// Gets the service id as register by the DiscoveryClient
/// </summary> /// </summary>
string ServiceId { get; } string ServiceId { get; }
/// <summary> /// <summary>
/// The hostname of the registered ServiceInstance /// Gets the hostname of the registered ServiceInstance
/// </summary> /// </summary>
string Host { get; } string Host { get; }
/// <summary> /// <summary>
/// The port of the registered ServiceInstance /// Gets the port of the registered ServiceInstance
/// </summary> /// </summary>
int Port { get; } int Port { get; }
/// <summary> /// <summary>
/// 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
/// </summary> /// </summary>
bool IsSecure { get; } bool IsSecure { get; }
/// <summary> /// <summary>
/// the service uri address /// Gets the service uri address
/// </summary> /// </summary>
Uri Uri { get; } Uri Uri { get; }
/// <summary> /// <summary>
/// The key value pair metadata associated with the service instance /// Gets the key value pair metadata associated with the service instance
/// </summary> /// </summary>
IDictionary<string, string> Metadata { get; } IDictionary<string, string> Metadata { get; }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System; using System;
@ -24,7 +21,6 @@ namespace Steeltoe.Common.Options
{ {
public AbstractOptions() public AbstractOptions()
{ {
} }
public AbstractOptions(IConfigurationRoot root, string sectionPrefix = null) public AbstractOptions(IConfigurationRoot root, string sectionPrefix = null)
@ -34,17 +30,15 @@ namespace Steeltoe.Common.Options
throw new ArgumentNullException(nameof(root)); throw new ArgumentNullException(nameof(root));
} }
if (!string.IsNullOrEmpty(sectionPrefix)) if (!string.IsNullOrEmpty(sectionPrefix))
{ {
var section = root.GetSection(sectionPrefix); var section = root.GetSection(sectionPrefix);
section.Bind(this); section.Bind(this);
} else }
else
{ {
root.Bind(this); root.Bind(this);
} }
} }
public AbstractOptions(IConfiguration config) public AbstractOptions(IConfiguration config)
@ -53,6 +47,7 @@ namespace Steeltoe.Common.Options
{ {
throw new ArgumentNullException(nameof(config)); throw new ArgumentNullException(nameof(config));
} }
config.Bind(this); config.Bind(this);
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -23,9 +21,8 @@ namespace Steeltoe.Common
public const string NET_FRAMEWORK = ".NET Framework"; public const string NET_FRAMEWORK = ".NET Framework";
public const string NET_CORE = ".NET Core"; public const string NET_CORE = ".NET Core";
public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(NET_FRAMEWORK); 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);
} }
} }

Просмотреть файл

@ -17,18 +17,23 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.xml</DocumentationFile> <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.xml</DocumentationFile>
<NoWarn>SA1101;SA1309;SA1310;SA1401;SA1600;1591</NoWarn>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<NoWarn>SA1100;SA1101;SA1124;SA1202;SA1204;SA1309;SA1310;SA1313;SA1600;SA1611;1591;1701;1702;1705</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="$(AspNetCoreVersion)" />
<PackageReference Include="StyleCop.Analyzers" Version="$(StyleCopVersion)">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<AdditionalFiles Include="..\..\stylecop.json"> <AdditionalFiles Include="..\..\stylecop.json">
<Link>stylecop.json</Link> <Link>stylecop.json</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</AdditionalFiles> </AdditionalFiles>
</ItemGroup> </ItemGroup>
</Project> </Project>

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Autofac; using Autofac;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -43,6 +41,5 @@ namespace Steeltoe.Common.Configuration.Autofac.Test
Assert.True(built.IsRegistered<IConfigurationRoot>()); Assert.True(built.IsRegistered<IConfigurationRoot>());
Assert.True(built.IsRegistered<IConfiguration>()); Assert.True(built.IsRegistered<IConfiguration>());
} }
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Autofac; using Autofac;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -50,7 +48,6 @@ namespace Steeltoe.Common.Autofac.Test.Logging
Assert.NotNull(fac); Assert.NotNull(fac);
var logger = built.Resolve<ILogger<LoggingContainerBuilderExtensionsTest>>(); var logger = built.Resolve<ILogger<LoggingContainerBuilderExtensionsTest>>();
Assert.NotNull(logger); Assert.NotNull(logger);
} }
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Autofac; using Autofac;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -39,7 +37,6 @@ namespace Steeltoe.Common.Options.Autofac.Test
Assert.Throws<ArgumentNullException>(() => container.RegisterOption<MyOption>(null)); Assert.Throws<ArgumentNullException>(() => container.RegisterOption<MyOption>(null));
ContainerBuilder container2 = new ContainerBuilder(); ContainerBuilder container2 = new ContainerBuilder();
Assert.Throws<ArgumentNullException>(() => container2.RegisterOption<MyOption>(null)); Assert.Throws<ArgumentNullException>(() => container2.RegisterOption<MyOption>(null));
} }
[Fact] [Fact]
@ -60,10 +57,9 @@ namespace Steeltoe.Common.Options.Autofac.Test
var service = built.Resolve<IOptions<MyOption>>(); var service = built.Resolve<IOptions<MyOption>>();
Assert.NotNull(service); Assert.NotNull(service);
Assert.NotNull(service.Value); Assert.NotNull(service.Value);
Assert.Equal("foobar", service.Value.f1); Assert.Equal("foobar", service.Value.F1);
} }
[Fact] [Fact]
public void RegisterPostConfigure_Registers_RunsPostAction() public void RegisterPostConfigure_Registers_RunsPostAction()
{ {
@ -79,7 +75,7 @@ namespace Steeltoe.Common.Options.Autofac.Test
container.RegisterOption<MyOption>(config); container.RegisterOption<MyOption>(config);
container.RegisterPostConfigure<MyOption>((opt) => container.RegisterPostConfigure<MyOption>((opt) =>
{ {
opt.f1 = "changed"; opt.F1 = "changed";
}); });
var built = container.Build(); var built = container.Build();
@ -87,12 +83,12 @@ namespace Steeltoe.Common.Options.Autofac.Test
var service = built.Resolve<IOptions<MyOption>>(); var service = built.Resolve<IOptions<MyOption>>();
Assert.NotNull(service); Assert.NotNull(service);
Assert.NotNull(service.Value); 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; }
} }
} }
} }

Просмотреть файл

@ -13,7 +13,7 @@
</None> </None>
</ItemGroup> </ItemGroup>
<PropertyGroup> <PropertyGroup>
<NoWarn>SA1100;SA1101;SA1202;SA1204;SA1309;SA1310;SA1313;SA1402;SA1600;SA1652;1591;1701;1702;1705</NoWarn> <NoWarn>SA1101;SA1309;SA1310;SA1401;SA1600;SA1652;1591</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@ -25,9 +25,11 @@
<PackageReference Include="xunit" Version="$(XunitVersion)" /> <PackageReference Include="xunit" Version="$(XunitVersion)" />
<PackageReference Include="xunit.runner.visualstudio" Version="$(XunitStudioVersion)" /> <PackageReference Include="xunit.runner.visualstudio" Version="$(XunitStudioVersion)" />
<DotNetCliToolReference Include="dotnet-xunit" Version="$(XunitVersion)" /> <DotNetCliToolReference Include="dotnet-xunit" Version="$(XunitVersion)" />
<PackageReference Include="StyleCop.Analyzers" Version="$(StyleCopVersion)">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<AdditionalFiles Include="..\..\stylecop.json"> <AdditionalFiles Include="..\..\stylecop.json">
<Link>stylecop.json</Link> <Link>stylecop.json</Link>

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Steeltoe.Common.Discovery; using Steeltoe.Common.Discovery;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
@ -43,10 +40,12 @@ namespace Steeltoe.Common.Http.Test
IDiscoveryClient client = new TestDiscoveryClient(); IDiscoveryClient client = new TestDiscoveryClient();
DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client);
Uri uri = new Uri("http://foo:8080/test"); Uri uri = new Uri("http://foo:8080/test");
// Act and Assert // Act and Assert
var result = handler.LookupService(uri); var result = handler.LookupService(uri);
Assert.Equal(uri, result); Assert.Equal(uri, result);
} }
[Fact] [Fact]
public void LookupService_DoesntFindService_ReturnsOriginalURI() 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"))); IDiscoveryClient client = new TestDiscoveryClient(new TestServiceInstance(new Uri("http://foundit:5555")));
DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client);
Uri uri = new Uri("http://foo/test/bar/foo?test=1&test2=2"); Uri uri = new Uri("http://foo/test/bar/foo?test=1&test2=2");
// Act and Assert // Act and Assert
var result = handler.LookupService(uri); var result = handler.LookupService(uri);
Assert.Equal(new Uri("http://foundit:5555/test/bar/foo?test=1&test2=2"), result); 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<string> Services
{
get
{
throw new NotImplementedException();
}
}
public IList<IServiceInstance> GetInstances(string serviceId)
{
if (_instance != null)
{
return new List<IServiceInstance>() { _instance };
}
return new List<IServiceInstance>();
}
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<string, string> 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;
}
}
}
}

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using System; using System;
using System.Net; using System.Net;
@ -79,6 +77,7 @@ namespace Steeltoe.Common.Http.Test
Assert.Null(ServicePointManager.ServerCertificateValidationCallback); Assert.Null(ServicePointManager.ServerCertificateValidationCallback);
} }
} }
[Fact] [Fact]
public void RestoreCertificateValidation_ValidateFalse() public void RestoreCertificateValidation_ValidateFalse()
{ {
@ -153,6 +152,7 @@ namespace Steeltoe.Common.Http.Test
Assert.Throws<ArgumentNullException>(() => HttpClientHelper.GetRequestMessage(null, null, null, null)); Assert.Throws<ArgumentNullException>(() => HttpClientHelper.GetRequestMessage(null, null, null, null));
Assert.Throws<ArgumentNullException>(() => HttpClientHelper.GetRequestMessage(HttpMethod.Get, null, null, null)); Assert.Throws<ArgumentNullException>(() => HttpClientHelper.GetRequestMessage(HttpMethod.Get, null, null, null));
} }
[Fact] [Fact]
public void GetRequestMessage_CreatesCorrectMessage() public void GetRequestMessage_CreatesCorrectMessage()
{ {
@ -161,7 +161,6 @@ namespace Steeltoe.Common.Http.Test
Assert.Equal(HttpMethod.Put, message.Method); Assert.Equal(HttpMethod.Put, message.Method);
Assert.Equal("http://localhost/foobar", message.RequestUri.ToString()); Assert.Equal("http://localhost/foobar", message.RequestUri.ToString());
Assert.Null(message.Headers.Authorization); Assert.Null(message.Headers.Authorization);
} }
[Fact] [Fact]
@ -197,9 +196,7 @@ namespace Steeltoe.Common.Http.Test
else else
{ {
Assert.NotNull(del1); Assert.NotNull(del1);
} }
} }
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using System; using System;
using System.IO; using System.IO;
@ -47,13 +45,14 @@ namespace Steeltoe.Common.Http.Test
var result = SerializationHelper.Deserialize<Test>(memStream); var result = SerializationHelper.Deserialize<Test>(memStream);
Assert.NotNull(result); Assert.NotNull(result);
Assert.Equal(100, result.f1); Assert.Equal(100, result.F1);
Assert.Equal(200, result.f2); Assert.Equal(200, result.F2);
} }
class Test
private class Test
{ {
public int f1=0; public int F1 = 0;
public long f2=0; public long F2 = 0;
} }
} }
} }

Просмотреть файл

@ -14,7 +14,7 @@
</ItemGroup> </ItemGroup>
<PropertyGroup> <PropertyGroup>
<NoWarn>SA1100;SA1101;SA1202;SA1204;SA1309;SA1310;SA1313;SA1402;SA1600;SA1652;1591;1701;1702;1705</NoWarn> <NoWarn>SA1101;SA1309;SA1310;SA1401;SA1600;SA1652;1591</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@ -27,6 +27,9 @@
<PackageReference Include="xunit" Version="$(XunitVersion)" /> <PackageReference Include="xunit" Version="$(XunitVersion)" />
<PackageReference Include="xunit.runner.visualstudio" Version="$(XunitStudioVersion)" /> <PackageReference Include="xunit.runner.visualstudio" Version="$(XunitStudioVersion)" />
<DotNetCliToolReference Include="dotnet-xunit" Version="$(XunitVersion)" /> <DotNetCliToolReference Include="dotnet-xunit" Version="$(XunitVersion)" />
<PackageReference Include="StyleCop.Analyzers" Version="$(StyleCopVersion)">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

Просмотреть файл

@ -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<string> Services
{
get
{
throw new NotImplementedException();
}
}
public IList<IServiceInstance> GetInstances(string serviceId)
{
if (_instance != null)
{
return new List<IServiceInstance>() { _instance };
}
return new List<IServiceInstance>();
}
public IServiceInstance GetLocalServiceInstance()
{
throw new NotImplementedException();
}
public Task ShutdownAsync()
{
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -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<string, string> 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;
}
}
}
}

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System; using System;
@ -211,6 +209,7 @@ namespace Steeltoe.Common.Configuration.Test
var result = ConfigurationValuesHelper.GetSetting("a:b", config1, config2, null, "foobar"); var result = ConfigurationValuesHelper.GetSetting("a:b", config1, config2, null, "foobar");
Assert.Equal("setting1", result); Assert.Equal("setting1", result);
} }
[Fact] [Fact]
public void GetSetting_GetsFromSecond() public void GetSetting_GetsFromSecond()
{ {

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System.Collections.Generic; using System.Collections.Generic;
@ -23,17 +21,15 @@ namespace Steeltoe.Common.Configuration.Test
{ {
public class PropertyPlaceholderHelperTest public class PropertyPlaceholderHelperTest
{ {
[Fact] [Fact]
public void ResolvePlaceholders_ResolvesSinglePlaceholder() public void ResolvePlaceholders_ResolvesSinglePlaceholder()
{ {
// Arrange // Arrange
string text = "foo=${foo}"; string text = "foo=${foo}";
ConfigurationBuilder builder = new ConfigurationBuilder(); ConfigurationBuilder builder = new ConfigurationBuilder();
var dic1 = new Dictionary<string, string>() var dic1 = new Dictionary<string, string>()
{ {
{"foo", "bar"} { "foo", "bar" }
}; };
builder.AddInMemoryCollection(dic1); builder.AddInMemoryCollection(dic1);
var config = builder.Build(); var config = builder.Build();
@ -42,38 +38,35 @@ namespace Steeltoe.Common.Configuration.Test
string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, config); string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, config);
Assert.Equal("foo=bar", result); Assert.Equal("foo=bar", result);
} }
[Fact] [Fact]
public void ResolvePlaceholders_ResolvesMultiplePlaceholders() public void ResolvePlaceholders_ResolvesMultiplePlaceholders()
{ {
// Arrange // Arrange
string text = "foo=${foo},bar=${bar}"; string text = "foo=${foo},bar=${bar}";
ConfigurationBuilder builder = new ConfigurationBuilder(); ConfigurationBuilder builder = new ConfigurationBuilder();
var dic1 = new Dictionary<string, string>() var dic1 = new Dictionary<string, string>()
{ {
{"foo", "bar"}, { "foo", "bar" },
{"bar", "baz" } { "bar", "baz" }
}; };
builder.AddInMemoryCollection(dic1); builder.AddInMemoryCollection(dic1);
var config = builder.Build();
// Act and Assert // Act and Assert
string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, config); string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, builder.Build());
Assert.Equal("foo=bar,bar=baz", result); Assert.Equal("foo=bar,bar=baz", result);
} }
[Fact] [Fact]
public void ResolvePlaceholders_ResolvesMultipleRecursivePlaceholders() public void ResolvePlaceholders_ResolvesMultipleRecursivePlaceholders()
{ {
// Arrange // Arrange
string text = "foo=${bar}"; string text = "foo=${bar}";
ConfigurationBuilder builder = new ConfigurationBuilder(); ConfigurationBuilder builder = new ConfigurationBuilder();
var dic1 = new Dictionary<string, string>() var dic1 = new Dictionary<string, string>()
{ {
{"bar", "${baz}"}, { "bar", "${baz}" },
{"baz", "bar"} { "baz", "bar" }
}; };
builder.AddInMemoryCollection(dic1); builder.AddInMemoryCollection(dic1);
var config = builder.Build(); var config = builder.Build();
@ -86,15 +79,13 @@ namespace Steeltoe.Common.Configuration.Test
[Fact] [Fact]
public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders() public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders()
{ {
// Arrange // Arrange
string text1 = "foo=${b${inner}}"; string text1 = "foo=${b${inner}}";
ConfigurationBuilder builder1 = new ConfigurationBuilder(); ConfigurationBuilder builder1 = new ConfigurationBuilder();
var dic1 = new Dictionary<string, string>() var dic1 = new Dictionary<string, string>()
{ {
{"bar", "bar"}, { "bar", "bar" },
{"inner", "ar"} { "inner", "ar" }
}; };
builder1.AddInMemoryCollection(dic1); builder1.AddInMemoryCollection(dic1);
var config1 = builder1.Build(); var config1 = builder1.Build();
@ -103,33 +94,30 @@ namespace Steeltoe.Common.Configuration.Test
ConfigurationBuilder builder2 = new ConfigurationBuilder(); ConfigurationBuilder builder2 = new ConfigurationBuilder();
var dic2 = new Dictionary<string, string>() var dic2 = new Dictionary<string, string>()
{ {
{"top", "${child}+${child}"}, { "top", "${child}+${child}" },
{"child", "${${differentiator}.grandchild}" }, { "child", "${${differentiator}.grandchild}" },
{"differentiator", "first" }, { "differentiator", "first" },
{"first.grandchild", "actualValue" } { "first.grandchild", "actualValue" }
}; };
builder2.AddInMemoryCollection(dic2); builder2.AddInMemoryCollection(dic2);
var config2 = builder2.Build(); var config2 = builder2.Build();
// Act and Assert // Act and Assert
string result1 = PropertyPlaceholderHelper.ResolvePlaceholders(text1, config1); string result1 = PropertyPlaceholderHelper.ResolvePlaceholders(text1, config1);
Assert.Equal("foo=bar", result1); Assert.Equal("foo=bar", result1);
string result2 = PropertyPlaceholderHelper.ResolvePlaceholders(text2, config2); string result2 = PropertyPlaceholderHelper.ResolvePlaceholders(text2, config2);
Assert.Equal("actualValue+actualValue", result2); Assert.Equal("actualValue+actualValue", result2);
} }
[Fact] [Fact]
public void ResolvePlaceholders_UnresolvedPlaceholderIsIgnored() public void ResolvePlaceholders_UnresolvedPlaceholderIsIgnored()
{ {
// Arrange // Arrange
string text = "foo=${foo},bar=${bar}"; string text = "foo=${foo},bar=${bar}";
ConfigurationBuilder builder = new ConfigurationBuilder(); ConfigurationBuilder builder = new ConfigurationBuilder();
var dic1 = new Dictionary<string, string>() var dic1 = new Dictionary<string, string>()
{ {
{"foo", "bar"} { "foo", "bar" }
}; };
builder.AddInMemoryCollection(dic1); builder.AddInMemoryCollection(dic1);
var config = builder.Build(); var config = builder.Build();
@ -142,7 +130,6 @@ namespace Steeltoe.Common.Configuration.Test
[Fact] [Fact]
public void ResolvePlaceholders_ResolvesArrayRefPlaceholder() public void ResolvePlaceholders_ResolvesArrayRefPlaceholder()
{ {
// Arrange // Arrange
var json1 = @" var json1 = @"
{ {
@ -187,13 +174,11 @@ namespace Steeltoe.Common.Configuration.Test
Assert.Equal("foo=my-app2.10.244.0.34.xip.io", result); 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(); var tempFile = Path.GetTempFileName();
File.WriteAllText(tempFile, contents); File.WriteAllText(tempFile, contents);
return tempFile; return tempFile;
} }
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System; using System;
@ -39,6 +37,5 @@ namespace Steeltoe.Common.Discovery.Test
var ex = Assert.Throws<ArgumentNullException>(() => new DiscoveryOptions(config)); var ex = Assert.Throws<ArgumentNullException>(() => new DiscoveryOptions(config));
Assert.Contains(nameof(config), ex.Message); Assert.Contains(nameof(config), ex.Message);
} }
} }
} }

Просмотреть файл

@ -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"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with 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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Steeltoe.Common.Options; using Steeltoe.Common.Options;
@ -32,7 +30,6 @@ namespace Steeltoe.Common.Test.Options
Assert.Throws<ArgumentNullException>(() => new TestOptions(root, "foobar")); Assert.Throws<ArgumentNullException>(() => new TestOptions(root, "foobar"));
Assert.Throws<ArgumentNullException>(() => new TestOptions(config)); Assert.Throws<ArgumentNullException>(() => new TestOptions(config));
} }
[Fact] [Fact]
@ -41,7 +38,7 @@ namespace Steeltoe.Common.Test.Options
var builder = new ConfigurationBuilder(); var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(new Dictionary<string, string>() builder.AddInMemoryCollection(new Dictionary<string, string>()
{ {
{"foo", "bar" } { "foo", "bar" }
}); });
IConfigurationRoot root = builder.Build(); IConfigurationRoot root = builder.Build();
@ -50,31 +47,17 @@ namespace Steeltoe.Common.Test.Options
var opt1 = new TestOptions(root); var opt1 = new TestOptions(root);
Assert.Equal("bar", opt1.Foo); Assert.Equal("bar", opt1.Foo);
var opt2 = new TestOptions(config); var opt2 = new TestOptions(config);
Assert.Equal("bar", opt2.Foo); Assert.Equal("bar", opt2.Foo);
var builder2 = new ConfigurationBuilder(); var builder2 = new ConfigurationBuilder();
builder2.AddInMemoryCollection(new Dictionary<string, string>() builder2.AddInMemoryCollection(new Dictionary<string, string>()
{ {
{"prefix:foo", "bar" } { "prefix:foo", "bar" }
}); });
IConfigurationRoot root2 = builder2.Build(); IConfigurationRoot root2 = builder2.Build();
var opt3 = new TestOptions(root2, "prefix"); var opt3 = new TestOptions(root2, "prefix");
Assert.Equal("bar", opt3.Foo); 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)
{
}
}
} }

Просмотреть файл

@ -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; }
}
}

Просмотреть файл

@ -14,7 +14,7 @@
</ItemGroup> </ItemGroup>
<PropertyGroup> <PropertyGroup>
<NoWarn>SA1100;SA1101;SA1202;SA1204;SA1309;SA1310;SA1313;SA1402;SA1600;SA1652;1591;1701;1702;1705</NoWarn> <NoWarn>SA1101;SA1309;SA1310;SA1401;SA1600;SA1652;1591</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@ -27,6 +27,9 @@
<PackageReference Include="xunit" Version="$(XunitVersion)" /> <PackageReference Include="xunit" Version="$(XunitVersion)" />
<PackageReference Include="xunit.runner.visualstudio" Version="$(XunitStudioVersion)" /> <PackageReference Include="xunit.runner.visualstudio" Version="$(XunitStudioVersion)" />
<DotNetCliToolReference Include="dotnet-xunit" Version="$(XunitVersion)" /> <DotNetCliToolReference Include="dotnet-xunit" Version="$(XunitVersion)" />
<PackageReference Include="StyleCop.Analyzers" Version="$(StyleCopVersion)">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>