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

Updates for .NET 8 code analysis - Part 2 #1446

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion .github/workflows/integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ jobs:
strategy:
fail-fast: false
matrix:
version: [net6.0,net7.0]
version: [net6.0, net7.0, net8.0]
steps:
- uses: actions/checkout@v4

Expand Down
4 changes: 2 additions & 2 deletions build/docker-compose.net6.0.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ services:
build:
args:
PUBLISH_FRAMEWORK: net6.0
TEST_SDK_VERSION: 6.0
BUILD_SDK_VERSION: 7.0
TEST_SDK_VERSION: "6.0"
BUILD_SDK_VERSION: "8.0"
4 changes: 2 additions & 2 deletions build/docker-compose.net7.0.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ services:
build:
args:
PUBLISH_FRAMEWORK: net7.0
TEST_SDK_VERSION: 7.0
BUILD_SDK_VERSION: 7.0
TEST_SDK_VERSION: "7.0"
BUILD_SDK_VERSION: "8.0"
9 changes: 9 additions & 0 deletions build/docker-compose.net8.0.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
version: '3.7'

services:
tests:
build:
args:
PUBLISH_FRAMEWORK: net8.0
TEST_SDK_VERSION: "8.0"
BUILD_SDK_VERSION: "8.0"
4 changes: 2 additions & 2 deletions examples/AspNet/Global.asax.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ namespace Examples.AspNet;
public class WebApiApplication : HttpApplication
#pragma warning restore SA1649 // File name should match first type name
{
private IDisposable? tracerProvider;
private IDisposable? meterProvider;
private TracerProvider? tracerProvider;
private MeterProvider? meterProvider;

protected void Application_Start()
{
Expand Down
2 changes: 1 addition & 1 deletion examples/wcf/server-aspnetframework/Global.asax.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ namespace Examples.Wcf.Server.AspNetFramework;
public class WebApiApplication : HttpApplication
#pragma warning restore SA1649 // File name should match first type name
{
private IDisposable? tracerProvider;
private TracerProvider? tracerProvider;

protected void Application_Start()
{
Expand Down
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"rollForward": "latestFeature",
"version": "7.0.400"
"version": "8.0.100"
}
}
1 change: 1 addition & 0 deletions opentelemetry-dotnet-contrib.sln
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{824BD1DE
build\debug.snk = build\debug.snk
build\docker-compose.net6.0.yml = build\docker-compose.net6.0.yml
build\docker-compose.net7.0.yml = build\docker-compose.net7.0.yml
build\docker-compose.net8.0.yml = build\docker-compose.net8.0.yml
build\opentelemetry-icon-color.png = build\opentelemetry-icon-color.png
build\OpenTelemetryContrib.prod.ruleset = build\OpenTelemetryContrib.prod.ruleset
build\OpenTelemetryContrib.test.ruleset = build\OpenTelemetryContrib.test.ruleset
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
using System.Diagnostics;
using System.IO.Compression;
using System.Net;
#if NETFRAMEWORK
using System.Net.Http;
#endif
using System.Net.Http.Headers;
using OpenTelemetry.Internal;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
// limitations under the License.
// </copyright>

#if NETFRAMEWORK
using System.Net.Http;
#endif

namespace OpenTelemetry.Exporter.OneCollector;

internal interface IHttpClient
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
// limitations under the License.
// </copyright>

#if NETFRAMEWORK
using System.Net.Http;
#endif
using Microsoft.Extensions.Configuration;
using OpenTelemetry.Exporter.OneCollector;
using OpenTelemetry.Internal;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,14 @@ public static TracerProviderBuilder AddAutoFlushActivityProcessor(
Func<Activity, bool> predicate,
int timeoutMilliseconds = 10000)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(builder);
#else
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
#endif

#pragma warning disable CA2000 // Dispose objects before losing scope
return builder.AddProcessor(new AutoFlushActivityProcessor(predicate, timeoutMilliseconds));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@ internal static (string? Host, int? Port) GetHostAndPort(string? httpScheme, str
return (null, null);
}

#pragma warning disable CA1861 // Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array
var hostAndPort = hostHeader.Split(new char[] { ':' }, 2);
#pragma warning restore CA1861 // Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array
if (hostAndPort.Length > 1)
{
var host = hostAndPort[0];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,12 @@ public void OnPerforming(PerformingContext performingContext)
public void OnPerformed(PerformedContext performedContext)
{
// Short-circuit if nobody is listening
if (!HangfireInstrumentation.ActivitySource.HasListeners() || !performedContext.Items.ContainsKey(HangfireInstrumentationConstants.ActivityKey))
if (!HangfireInstrumentation.ActivitySource.HasListeners() || !performedContext.Items.TryGetValue(HangfireInstrumentationConstants.ActivityKey, out var value))
{
return;
}

if (performedContext.Items[HangfireInstrumentationConstants.ActivityKey] is Activity activity)
if (value is Activity activity)
{
if (performedContext.Exception != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ internal static List<KeyValuePair<string, object>> ExtractMetadataV4ResourceAttr

if (!clusterArn.StartsWith("arn:", StringComparison.Ordinal))
{
#pragma warning disable CA1865 // Use string.LastIndexOf(char) instead of string.LastIndexOf(string) when you have string with a single char
var baseArn = containerArn.Substring(containerArn.LastIndexOf(":", StringComparison.Ordinal));
#pragma warning restore CA1865 // Use string.LastIndexOf(char) instead of string.LastIndexOf(string) when you have string with a single char
clusterArn = $"{baseArn}:cluster/{clusterArn}";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ namespace OpenTelemetry.Exporter.InfluxDB.Tests;
public class InfluxDBMetricsExporterTests
{
private static readonly string OpenTelemetrySdkVersion;
private static readonly double[] TestBoundaries = new[] { 10D, 20D, 100D, 200D };

#pragma warning disable CA1810 // Initialize reference type static fields inline
static InfluxDBMetricsExporterTests()
Expand Down Expand Up @@ -312,7 +313,7 @@ public void ExportHistogramMetricWhenTelegrafPrometheusV1MetricsSchemaUsed()
.AddMeter(meter.Name)
.AddView("histogram_metric", new ExplicitBucketHistogramConfiguration
{
Boundaries = new[] { 10D, 20D, 100D, 200D },
Boundaries = TestBoundaries,
RecordMinMax = true,
})
.ConfigureDefaultTestResource()
Expand Down Expand Up @@ -403,7 +404,7 @@ public void ExportHistogramMetricWhenTelegrafPrometheusV2MetricsSchemaUsed()
.AddMeter(meter.Name)
.AddView("histogram_metric", new ExplicitBucketHistogramConfiguration
{
Boundaries = new[] { 10D, 20D, 100D, 200D },
Boundaries = TestBoundaries,
RecordMinMax = true,
})
.ConfigureDefaultTestResource()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,13 @@ private static object ParseFieldValue(string fieldValue)
return boolValue;
}

#pragma warning disable CA1865 // Use char overload
if (fieldValue.EndsWith("i", StringComparison.Ordinal)
&& long.TryParse(fieldValue.AsSpan(0, fieldValue.Length - 1).ToString(), out long intValue))
{
return intValue;
}
#pragma warning restore CA1865 // Use char overload

if (double.TryParse(fieldValue, NumberStyles.Float, CultureInfo.InvariantCulture, out double doubleValue))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

using System.Diagnostics;
using System.Net;
#if NETFRAMEWORK
using System.Net.Http;
#endif
using System.Reflection;
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.Logging;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

using System.IO.Compression;
using System.Net;
#if NETFRAMEWORK
using System.Net.Http;
#endif
using System.Text;
using OpenTelemetry.Tests;
using Xunit;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public static HttpResponseMessage Create(HttpStatusCode statusCode, IDictionary<
}
}

httpResponseMessage.StatusCode = statusCode;
httpResponseMessage!.StatusCode = statusCode;
string dummyJson = "{\"key1\":\"value1\"}";
httpResponseMessage.Content = new StringContent(body ?? dummyJson); // Content should be in Json format else we get exception from downstream unmarshalling
return httpResponseMessage;
Expand Down Expand Up @@ -152,7 +152,9 @@ public static HttpResponse ParseRawReponse(string rawResponse)
break;
}

#pragma warning disable CA1865 // Use char overload
var index = currentLine.IndexOf(":", StringComparison.Ordinal);
#pragma warning restore CA1865 // Use char overload
if (index != -1)
{
var headerKey = currentLine.Substring(0, index);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ public void GetHttpTags_APIGatewayProxyRequest_ReturnsCorrectTags()
},
MultiValueQueryStringParameters = new Dictionary<string, IList<string>>
{
#pragma warning disable CA1861 // Avoid constant arrays as arguments
{ "q1", new[] { "value1" } },
#pragma warning restore CA1861 // Avoid constant arrays as arguments
},
RequestContext = new APIGatewayProxyRequest.ProxyRequestContext
{
Expand Down Expand Up @@ -70,7 +72,9 @@ public void GetHttpTags_APIGatewayProxyRequestWithEmptyContext_ReturnsTagsFromRe
{
MultiValueQueryStringParameters = new Dictionary<string, IList<string>>
{
#pragma warning disable CA1861 // Avoid constant arrays as arguments
{ "q1", new[] { "value1" } },
#pragma warning restore CA1861 // Avoid constant arrays as arguments
},
HttpMethod = "POST",
Path = "/path/test",
Expand Down Expand Up @@ -251,11 +255,13 @@ public void GetHostAndPort_HostHeader_ReturnsCorrectHostAndPort(string httpSchem

[Theory]
[InlineData(null, "")]
#pragma warning disable CA1861 // Avoid constant arrays as arguments
[InlineData(new string[] { }, "")]
[InlineData(new[] { "value1" }, "?name=value1")]
[InlineData(new[] { "value$a" }, "?name=value%24a")]
[InlineData(new[] { "value 1" }, "?name=value+1")]
[InlineData(new[] { "value1", "value2" }, "?name=value1&name=value2")]
#pragma warning restore CA1861 // Avoid constant arrays as arguments
public void GetQueryString_APIGatewayProxyRequest_CorrectQueryString(IList<string> values, string expectedQueryString)
{
var request = new APIGatewayProxyRequest();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ public void ShouldCollectTelemetryWhenFilterEvaluatesToTrueByProviderName()

public void Dispose() => this.connection.Dispose();

private static DbConnection CreateInMemoryDatabase()
private static SqliteConnection CreateInMemoryDatabase()
{
var connection = new SqliteConnection("Filename=:memory:");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
# This should be run from the root of the repo:
# docker build --file test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests/Dockerfile .

ARG BUILD_SDK_VERSION=7.0
ARG TEST_SDK_VERSION=7.0
ARG BUILD_SDK_VERSION=8.0
ARG TEST_SDK_VERSION=8.0

FROM mcr.microsoft.com/dotnet/sdk:${BUILD_SDK_VERSION} AS build
ARG PUBLISH_CONFIGURATION=Release
ARG PUBLISH_FRAMEWORK=net7.0
ARG PUBLISH_FRAMEWORK=net8.0
WORKDIR /repo
COPY . ./
WORKDIR "/repo/test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ namespace OpenTelemetry.Instrumentation.StackExchangeRedis.Implementation;
public class RedisProfilerEntryToActivityConverterTests : IDisposable
{
private readonly ConnectionMultiplexer connection;
private readonly IDisposable tracerProvider;
private readonly TracerProvider tracerProvider;

public RedisProfilerEntryToActivityConverterTests()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<Description>Unit test project for OpenTelemetry StackExchangeRedis instrumentation</Description>
<!-- OmniSharp/VS Code requires TargetFrameworks to be in descending order for IntelliSense and analysis. -->
<TargetFrameworks Condition="$(TARGET_FRAMEWORK) == ''">net7.0;net6.0</TargetFrameworks>
<TargetFrameworks Condition="$(TARGET_FRAMEWORK) == ''">net8.0;net7.0;net6.0</TargetFrameworks>
<TargetFrameworks Condition="$(TARGET_FRAMEWORK) == '' and $(OS) == 'Windows_NT'">$(TargetFrameworks);net462</TargetFrameworks>
<TargetFrameworks Condition="$(TARGET_FRAMEWORK) != ''">$(TARGET_FRAMEWORK)</TargetFrameworks>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,13 @@ public void SuccessfulCommandTest(string value)
};
connectionOptions.EndPoints.Add(RedisEndPoint);

IConnectionMultiplexer? connection = null;
ConnectionMultiplexer? connection = null;
var activityProcessor = new Mock<BaseProcessor<Activity>>();
var sampler = new TestSampler();
using (Sdk.CreateTracerProviderBuilder()
.ConfigureServices(services =>
{
services.TryAddSingleton(sp =>
services.TryAddSingleton<IConnectionMultiplexer>(sp =>
{
return connection = ConnectionMultiplexer.Connect(connectionOptions);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,12 @@ public async void TestEcsMetadataV4Ec2()
Assert.Equal(resourceAttributes[AWSSemanticConventions.AttributeEcsTaskArn], "arn:aws:ecs:us-west-2:111122223333:task/default/158d1c8083dd49d6b527399fd6414f5c");
Assert.Equal(resourceAttributes[AWSSemanticConventions.AttributeEcsTaskFamily], "curltest");
Assert.Equal(resourceAttributes[AWSSemanticConventions.AttributeEcsTaskRevision], "26");
#pragma warning disable CA1861 // Avoid constant arrays as arguments
Assert.NotStrictEqual(resourceAttributes[AWSSemanticConventions.AttributeLogGroupNames], new string[] { "/ecs/metadata" });
Assert.NotStrictEqual(resourceAttributes[AWSSemanticConventions.AttributeLogGroupArns], new string[] { "arn:aws:logs:us-west-2:111122223333:log-group:/ecs/metadata" });
Assert.NotStrictEqual(resourceAttributes[AWSSemanticConventions.AttributeLogStreamNames], new string[] { "ecs/curl/8f03e41243824aea923aca126495f665" });
Assert.NotStrictEqual(resourceAttributes[AWSSemanticConventions.AttributeLogStreamArns], new string[] { "arn:aws:logs:us-west-2:111122223333:log-group:/ecs/metadata:log-stream:ecs/curl/8f03e41243824aea923aca126495f665" });
#pragma warning restore CA1861 // Avoid constant arrays as arguments
}
}

Expand All @@ -117,10 +119,12 @@ public async void TestEcsMetadataV4Fargate()
Assert.Equal(resourceAttributes[AWSSemanticConventions.AttributeEcsTaskArn], "arn:aws:ecs:us-west-2:111122223333:task/default/e9028f8d5d8e4f258373e7b93ce9a3c3");
Assert.Equal(resourceAttributes[AWSSemanticConventions.AttributeEcsTaskFamily], "curltest");
Assert.Equal(resourceAttributes[AWSSemanticConventions.AttributeEcsTaskRevision], "3");
#pragma warning disable CA1861 // Avoid constant arrays as arguments
Assert.NotStrictEqual(resourceAttributes[AWSSemanticConventions.AttributeLogGroupNames], new string[] { "/ecs/containerlogs" });
Assert.NotStrictEqual(resourceAttributes[AWSSemanticConventions.AttributeLogGroupArns], new string[] { "arn:aws:logs:us-west-2:111122223333:log-group:/ecs/containerlogs" });
Assert.NotStrictEqual(resourceAttributes[AWSSemanticConventions.AttributeLogStreamNames], new string[] { "ecs/curl/cd189a933e5849daa93386466019ab50" });
Assert.NotStrictEqual(resourceAttributes[AWSSemanticConventions.AttributeLogStreamArns], new string[] { "arn:aws:logs:us-west-2:111122223333:log-group:/ecs/containerlogs:log-stream:ecs/curl/cd189a933e5849daa93386466019ab50" });
#pragma warning restore CA1861 // Avoid constant arrays as arguments
}
}

Expand Down
Loading