Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removed dependency on Microsoft.AspNetCore.Http.Extensions #312

Merged
merged 5 commits into from
Aug 31, 2018
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public void VariableNotFoundRendersEmptyString()
Assert.Empty(result);
}

[Theory, MemberData("VariableFoundData")]
[Theory, MemberData(nameof(VariableFoundData))]
public void VariableFoundRendersValue(object expectedValue)
{
var httpContext = Substitute.For<HttpContextBase>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ public void CulturedVariableFoundRendersValue(object expectedValue)
httpContext.Items = new Dictionary<object, object>();
httpContext.Items.Add("key", expectedValue);
#else
httpContext.Items.Count.Returns(1);
httpContext.Items.Contains("key").Returns(true);
httpContext.Items["key"].Returns(expectedValue);
#endif
var cultureInfo = new CultureInfo("nl-NL");
Expand All @@ -85,6 +87,8 @@ public void VariableFoundRendersValue(object expectedValue)
httpContext.Items = new Dictionary<object, object>();
httpContext.Items.Add("key", expectedValue);
#else
httpContext.Items.Count.Returns(1);
httpContext.Items.Contains("key").Returns(true);
httpContext.Items["key"].Returns(expectedValue);
#endif

Expand All @@ -101,7 +105,14 @@ public void VariableFoundRendersValue(object expectedValue)
public void NestedPropertyRendersValue(string itemKey, string variable, object data, object expectedValue)
{
var httpContext = Substitute.For<HttpContextBase>();
#if ASP_NET_CORE
httpContext.Items = new Dictionary<object, object>();
httpContext.Items.Add(itemKey, data);
#else
httpContext.Items.Count.Returns(1);
httpContext.Items.Contains(itemKey).Returns(true);
httpContext.Items[itemKey].Returns(data);
#endif

var renderer = new AspNetItemValueLayoutRenderer();
renderer.Variable = variable;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public void NullRequestRendersEmptyStringWithoutLoggingError()
string result = renderer.Render(new LogEventInfo());

Assert.Empty(result);
Assert.Equal(true, string.IsNullOrEmpty(internalLog.ToString()));
Assert.True(string.IsNullOrEmpty(internalLog.ToString()));
}

public class ItemTests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,12 @@ namespace NLog.Web.Tests.LayoutRenderers
{
public class AspNetSessionValueLayoutRendererTests : TestInvolvingAspNetHttpContext
{



public AspNetSessionValueLayoutRendererTests()
{
SetUp();
}

public void SetUp()
private void SetUp()
{
//auto load won't work yet (in DNX), so use <extensions>
LogManager.Configuration = CreateConfigurationFromString(@"
Expand Down Expand Up @@ -232,7 +229,7 @@ private void ExecTest(string key, object value, object expected, LayoutRenderer
/// <summary>
/// Create Fake Session http://stackoverflow.com/a/10126711/201303
/// </summary>
public void SetupFakeSession()
private void SetupFakeSession()
{
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
Expand Down
14 changes: 7 additions & 7 deletions NLog.Web.AspNetCore/Internal/PropertyReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,27 @@ internal class PropertyReader
/// Get value of a property
/// </summary>
/// <param name="key">key</param>
/// <param name="container">Container to perform value lookup using key</param>
/// <param name="getVal">function to get a value with this key</param>
/// <param name="evaluateAsNestedProperties">evaluate <paramref name="key"/> as a nested property path. E.g. A.B is property B inside A.</param>
/// <returns>value</returns>
public static object GetValue(string key, Func<string, object> getVal, bool evaluateAsNestedProperties)
public static object GetValue<T>(string key, T container, Func<T, string, object> getVal, bool evaluateAsNestedProperties)
{
if (String.IsNullOrEmpty(key))
{
return null;
}

var value = evaluateAsNestedProperties ? GetValueAsNestedProperties(key, getVal) : getVal(key);
var value = evaluateAsNestedProperties ? GetValueAsNestedProperties(key, container, getVal) : getVal(container, key);
return value;
}

private static object GetValueAsNestedProperties(string key, Func<string, object> getVal)
private static object GetValueAsNestedProperties<T>(string key, T container, Func<T, string, object> getVal)
{
var path = key.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries);
var path = key.IndexOf('.') >= 0 ? key.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) : null;

var value = getVal(path.First());

if (value != null)
var value = getVal(container, path?.First() ?? key);
if (value != null && path?.Length > 1)
{
foreach (var property in path.Skip(1))
{
Expand Down
16 changes: 16 additions & 0 deletions NLog.Web.AspNetCore/Internal/RequestAccessorExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,21 @@ internal static HttpRequest TryGetRequest(this HttpContext context)
return context.Request;
}
#endif

#if ASP_NET_CORE
internal static string GetString(this ISession session, string key)
{
if (!session.TryGetValue(key, out var data))
return null;

if (data == null)
return null;

if (data.Length == 0)
return string.Empty;

return Encoding.UTF8.GetString(data);
}
#endif
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
Expand Down Expand Up @@ -79,18 +80,21 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
return;
}
var context = HttpContextAccessor.HttpContext;

if (context == null)
var context = HttpContextAccessor.HttpContext;
#if !ASP_NET_CORE
Func<System.Collections.IDictionary, string, object> getVal = (items, key) =>
{
return;
}

Func<string, object> getVal = k => context.Items[k];

var value = PropertyReader.GetValue(Variable, getVal, EvaluateAsNestedProperties);
return items?.Count > 0 && items.Contains(key) ? items[key] : null;
};
#else
Func<IDictionary<object, object>, string, object> getVal = (items, key) =>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why Funcs and not private methodes?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No special reason. Think I was just keeping the existing coding-style.

Copy link
Member

@304NotModified 304NotModified Aug 30, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really prefer private method then. Less clutter.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By private methods do you mean normal methods or local methods (c# 7.0) ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

normal please.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

{
return items != null && items.TryGetValue(key, out var itemValue) ? itemValue : null;
};
#endif
var value = PropertyReader.GetValue(Variable, context?.Items, getVal, EvaluateAsNestedProperties);
var formatProvider = GetFormatProvider(logEvent, Culture);

builder.Append(Convert.ToString(value, formatProvider));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ protected AspNetLayoutRendererBase()
/// Provides access to the current request HttpContext.
/// </summary>
/// <returns>HttpContextAccessor or <c>null</c></returns>
[NLog.Config.NLogConfigurationIgnorePropertyAttribute]
public IHttpContextAccessor HttpContextAccessor
{
get => _httpContextAccessor ?? (_httpContextAccessor = RetrieveHttpContextAccessor());
Expand Down Expand Up @@ -72,9 +73,11 @@ private static IHttpContextAccessor RetrieveHttpContextAccessor()
}

#else

/// <summary>
/// Provides access to the current request HttpContext.
/// </summary>
[NLog.Config.NLogConfigurationIgnorePropertyAttribute]
public IHttpContextAccessor HttpContextAccessor { get; set; }

#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,20 +86,20 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
InternalLogger.Debug("Session is null");
return;
}

#if !ASP_NET_CORE
var value = PropertyReader.GetValue(Variable, k => context.Session[k], EvaluateAsNestedProperties);
var value = PropertyReader.GetValue(Variable, context.Session, (session,key) => session.Count > 0 ? session[key] : null, EvaluateAsNestedProperties);
#else
if (context.Items == null || context.Features.Get<ISessionFeature>()?.Session == null) { return; }

//because session.get / session.getstring also creating log messages in some cases, this could lead to stackoverflow issues.
//We remember on the context.Items that we are looking up a session value so we prevent stackoverflows
if (context.Items.ContainsKey(NLogRetrievingSessionValue)) { return; }

if (context.Items == null || context.Features.Get<ISessionFeature>()?.Session == null) { return; }
if (context.Items.Count > 0 && context.Items.ContainsKey(NLogRetrievingSessionValue)) { return; }
context.Items[NLogRetrievingSessionValue] = true;

object value;
try
{
value = PropertyReader.GetValue(Variable, k => context.Session.GetString(k), EvaluateAsNestedProperties);
value = PropertyReader.GetValue(Variable, context.Session, (session, key) => session.GetString(key), EvaluateAsNestedProperties);
}
catch (Exception ex)
{
Expand All @@ -110,8 +110,8 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
context.Items.Remove(NLogRetrievingSessionValue);
}

#endif

var formatProvider = GetFormatProvider(logEvent, Culture);
builder.Append(Convert.ToString(value, formatProvider));
}
Expand Down
2 changes: 0 additions & 2 deletions NLog.Web.AspNetCore/NLog.Web.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,12 @@ Supported platforms:

<ItemGroup Condition=" '$(TargetFramework)' != 'netstandard2.0' and '$(TargetFramework)' != 'net461' ">
<PackageReference Include="Microsoft.AspNetCore.Http" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Routing.Abstractions" Version="1.1.1" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'net461' ">
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Routing.Abstractions" Version="2.0.0" />
</ItemGroup>
Expand Down
18 changes: 6 additions & 12 deletions NLog.Web.Tests/NLog.Web.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>NLog.Web.Tests</RootNamespace>
<AssemblyName>NLog.Web.Tests</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
Expand All @@ -20,6 +20,7 @@
<TestProjectType>UnitTest</TestProjectType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
Expand Down Expand Up @@ -54,9 +55,6 @@
<Reference Include="System.IO.Compression" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Transactions" />
Expand All @@ -65,21 +63,17 @@
<Reference Include="System.Web.Routing" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<Reference Include="xunit.abstractions">
<HintPath>..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.assert">
<HintPath>..\packages\xunit.assert.2.3.1\lib\netstandard1.1\xunit.assert.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.core">
<HintPath>..\packages\xunit.extensibility.core.2.3.1\lib\netstandard1.1\xunit.core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.execution.dotnet">
<HintPath>..\packages\xunit.extensibility.execution.2.3.1\lib\netstandard1.1\xunit.execution.dotnet.dll</HintPath>
<Private>True</Private>
<Reference Include="xunit.execution.desktop">
<HintPath>..\packages\xunit.extensibility.execution.2.3.1\lib\net452\xunit.execution.desktop.dll</HintPath>
</Reference>
</ItemGroup>
<Choose>
Expand Down Expand Up @@ -151,7 +145,7 @@
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\xunit.runner.visualstudio.2.3.1\build\net20\xunit.runner.visualstudio.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\xunit.runner.visualstudio.2.3.1\build\net20\xunit.runner.visualstudio.props'))" />
<Error Condition="!Exists('..\packages\xunit.core.2.3.1\build\xunit.core.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\xunit.core.2.3.1\build\xunit.core.props'))" />
Expand Down
51 changes: 10 additions & 41 deletions NLog.Web.Tests/packages.NLog.Web.Tests.config
Original file line number Diff line number Diff line change
@@ -1,44 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.NETCore.Platforms" version="1.1.0" targetFramework="net45" />
<package id="NETStandard.Library" version="1.6.1" targetFramework="net45" />
<package id="NLog" version="4.5.8" targetFramework="net45" />
<package id="NSubstitute" version="2.0.3" targetFramework="net45" />
<package id="System.Collections" version="4.3.0" targetFramework="net45" />
<package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="net45" />
<package id="System.Globalization" version="4.3.0" targetFramework="net45" />
<package id="System.IO" version="4.3.0" targetFramework="net45" />
<package id="System.IO.Compression" version="4.3.0" targetFramework="net45" />
<package id="System.Linq" version="4.3.0" targetFramework="net45" />
<package id="System.Linq.Expressions" version="4.3.0" targetFramework="net45" />
<package id="System.Net.Http" version="4.3.0" targetFramework="net45" />
<package id="System.Net.Primitives" version="4.3.0" targetFramework="net45" />
<package id="System.ObjectModel" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection.Primitives" version="4.3.0" targetFramework="net45" />
<package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net45" />
<package id="System.Text.Encoding" version="4.3.0" targetFramework="net45" />
<package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="net45" />
<package id="System.Threading" version="4.3.0" targetFramework="net45" />
<package id="System.Threading.Tasks" version="4.3.0" targetFramework="net45" />
<package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="net45" />
<package id="System.Xml.XDocument" version="4.3.0" targetFramework="net45" />
<package id="xunit" version="2.3.1" targetFramework="net45" />
<package id="xunit.abstractions" version="2.0.1" targetFramework="net45" />
<package id="xunit.analyzers" version="0.8.0" targetFramework="net45" />
<package id="xunit.assert" version="2.3.1" targetFramework="net45" />
<package id="xunit.core" version="2.3.1" targetFramework="net45" />
<package id="xunit.extensibility.core" version="2.3.1" targetFramework="net45" />
<package id="xunit.extensibility.execution" version="2.3.1" targetFramework="net45" />
<package id="xunit.runner.visualstudio" version="2.3.1" targetFramework="net45" developmentDependency="true" />
<package id="NLog" version="4.5.8" targetFramework="net452" />
<package id="NSubstitute" version="2.0.3" targetFramework="net452" />
<package id="xunit" version="2.3.1" targetFramework="net452" />
<package id="xunit.abstractions" version="2.0.1" targetFramework="net452" />
<package id="xunit.analyzers" version="0.8.0" targetFramework="net452" />
<package id="xunit.assert" version="2.3.1" targetFramework="net452" />
<package id="xunit.core" version="2.3.1" targetFramework="net452" />
<package id="xunit.extensibility.core" version="2.3.1" targetFramework="net452" />
<package id="xunit.extensibility.execution" version="2.3.1" targetFramework="net452" />
<package id="xunit.runner.visualstudio" version="2.3.1" targetFramework="net452" developmentDependency="true" />
</packages>