Skip to content

Commit

Permalink
Updates for .NET 8 code analysis - Part 1 (#1443)
Browse files Browse the repository at this point in the history
  • Loading branch information
utpilla authored Nov 22, 2023
1 parent 39224da commit 5167fbe
Show file tree
Hide file tree
Showing 19 changed files with 41 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public TransportProtocol Protocol
if (this._parts.ContainsKey(nameof(this.EtwSession)))
{
_ = this._parts.TryGetValue(nameof(this.PrivatePreviewEnableTraceLoggingDynamic), out var privatePreviewEnableTraceLoggingDynamic);
if (privatePreviewEnableTraceLoggingDynamic != null && privatePreviewEnableTraceLoggingDynamic.ToUpperInvariant() == bool.TrueString.ToUpperInvariant())
if (privatePreviewEnableTraceLoggingDynamic != null && privatePreviewEnableTraceLoggingDynamic.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))
{
return TransportProtocol.EtwTld;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public static MeterProviderBuilder AddGenevaMetricExporter(this MeterProviderBui
});
}

private static MetricReader BuildGenevaMetricExporter(GenevaMetricExporterOptions options, Action<GenevaMetricExporterOptions> configure = null)
private static PeriodicExportingMetricReader BuildGenevaMetricExporter(GenevaMetricExporterOptions options, Action<GenevaMetricExporterOptions> configure = null)
{
configure?.Invoke(options);
return new PeriodicExportingMetricReader(new GenevaMetricExporter(options), options.MetricExportIntervalMilliseconds)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ public void Dispose()

private static readonly string INVALID_SPAN_ID = default(ActivitySpanId).ToHexString();

private static readonly IReadOnlyDictionary<string, string> CS40_PART_B_MAPPING = new Dictionary<string, string>
private static readonly Dictionary<string, string> CS40_PART_B_MAPPING = new Dictionary<string, string>
{
["db.system"] = "dbSystem",
["db.name"] = "dbName",
Expand Down Expand Up @@ -435,9 +435,9 @@ public void Dispose()

private readonly IDataTransport m_dataTransport;

private readonly IReadOnlyDictionary<string, object> m_customFields;
private readonly Dictionary<string, object> m_customFields;

private readonly IReadOnlyDictionary<string, object> m_dedicatedFields;
private readonly Dictionary<string, object> m_dedicatedFields;

private bool isDisposed;
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ internal sealed class TldLogExporter : TldExporter, IDisposable
private readonly byte partAFieldsCount = 1; // At least one field: time
private readonly bool shouldPassThruTableMappings;
private readonly string defaultEventName = "Log";
private readonly IReadOnlyDictionary<string, object> customFields;
private readonly IReadOnlyDictionary<string, string> tableMappings;
private readonly Dictionary<string, object> customFields;
private readonly Dictionary<string, string> tableMappings;
private readonly Tuple<byte[], byte[]> repeatedPartAFields;
private readonly ExceptionStackExportMode exceptionStackExportMode;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ internal sealed class TldTraceExporter : TldExporter, IDisposable

private static readonly string INVALID_SPAN_ID = default(ActivitySpanId).ToHexString();

private static readonly IReadOnlyDictionary<string, string> CS40_PART_B_MAPPING = new Dictionary<string, string>
private static readonly Dictionary<string, string> CS40_PART_B_MAPPING = new Dictionary<string, string>
{
["db.system"] = "dbSystem",
["db.name"] = "dbName",
Expand All @@ -54,7 +54,7 @@ internal sealed class TldTraceExporter : TldExporter, IDisposable

private readonly string partAName = "Span";
private readonly byte partAFieldsCount = 3; // At least three fields: time, ext_dt_traceId, ext_dt_spanId
private readonly IReadOnlyDictionary<string, object> m_customFields;
private readonly Dictionary<string, object> m_customFields;
private readonly Tuple<byte[], byte[]> repeatedPartAFields;

private readonly EventProvider eventProvider;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,14 @@ public IDisposable Add(T callback)

lock (this.lockObject)
{
#if NET7_0_OR_GREATER
ObjectDisposedException.ThrowIf(this.disposed, nameof(CallbackManager<T>));
#else
if (this.disposed)
{
throw new ObjectDisposedException(nameof(CallbackManager<T>));
}
#endif

this.root = (T)Delegate.Combine(this.root, callback);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ public bool Send(in TransportSendRequest sendRequest)
}
}

private HttpContent BuildRequestContent(Stream stream)
private NonDisposingStreamContent BuildRequestContent(Stream stream)
{
switch (this.compressionType)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,9 @@ internal BaseProcessor<LogRecord> BuildProcessor()

private OneCollectorExporter<LogRecord> BuildExporter()
{
#pragma warning disable CA2000 // Dispose objects before losing scope
var exporter = new OneCollectorExporter<LogRecord>(this.CreateSink());
#pragma warning restore CA2000 // Dispose objects before losing scope

try
{
Expand All @@ -222,7 +224,7 @@ private OneCollectorExporter<LogRecord> BuildExporter()
return exporter;
}

private ISink<LogRecord> CreateSink()
private WriteDirectlyToTransportSink<LogRecord> CreateSink()
{
this.exporterOptions.Validate();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
<PackageReference Include="System.Text.Json" Version="$(SystemTextJsonPkgVer)" Condition="'$(TargetFramework)' != 'net7.0' AND '$(TargetFramework)' != 'net6.0'" />
</ItemGroup>

<ItemGroup>
<Reference Include="System.Net.Http" Condition="'$(TargetFramework)' == 'net462'" />
</ItemGroup>

<ItemGroup>
<Compile Include="$(RepoRoot)\src\Shared\Guard.cs" Link="Includes\Guard.cs" />
<Compile Include="$(RepoRoot)\src\Shared\IsExternalInit.cs" Link="Includes\IsExternalInit.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ private bool CheckStorageSize()
return true;
}

private PersistentBlob? CreateFileBlob(byte[] buffer, int leasePeriodMilliseconds = 0)
private FileBlob? CreateFileBlob(byte[] buffer, int leasePeriodMilliseconds = 0)
{
if (!this.CheckStorageSize())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,11 @@ public Resource Detect()
string? websiteResourceGroup = Environment.GetEnvironmentVariable(ResourceAttributeConstants.AppServiceResourceGroupEnvVar);
string websiteOwnerName = Environment.GetEnvironmentVariable(ResourceAttributeConstants.AppServiceOwnerNameEnvVar) ?? string.Empty;

#if NET6_0_OR_GREATER
int idx = websiteOwnerName.IndexOf('+', StringComparison.Ordinal);
#else
int idx = websiteOwnerName.IndexOf("+", StringComparison.Ordinal);
#endif
string subscriptionId = idx > 0 ? websiteOwnerName.Substring(0, idx) : websiteOwnerName;

if (string.IsNullOrEmpty(websiteResourceGroup) || string.IsNullOrEmpty(subscriptionId))
Expand Down
2 changes: 1 addition & 1 deletion src/Shared/PropertyFetcher.AOT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ public abstract bool TryFetch(
// 2. Then, the declared object type is passed as a generic parameter to a generic method on PropertyFetcher<T> (or nested type.)
// Therefore, calling into MakeGenericMethod will only require specifying one parameter - the declared object type.
// The declared object type is guaranteed to be a reference type (throw on value type.) Thus, MakeGenericMethod is AOT compatible.
private static PropertyFetch CreateInstantiated<TDeclaredObject>(PropertyInfo propertyInfo)
private static PropertyFetchInstantiated<TDeclaredObject> CreateInstantiated<TDeclaredObject>(PropertyInfo propertyInfo)
where TDeclaredObject : class
=> new PropertyFetchInstantiated<TDeclaredObject>(propertyInfo);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,6 @@ private static EventAttribute GetEventAttribute(MethodInfo eventMethod)
private static IEnumerable<MethodInfo> GetEventMethods(EventSource eventSource)
{
MethodInfo[] methods = eventSource.GetType().GetMethods();
return methods.Where(m => m.GetCustomAttributes(typeof(EventAttribute), false).Any());
return methods.Where(m => m.GetCustomAttributes(typeof(EventAttribute), false).Length != 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="$(BenchmarkDotNetPkgVer)" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="OpenTelemetry.Exporter.InMemory" Version="$(OpenTelemetryExporterInMemoryLatestPreReleasePkgVer)" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="[6.0.0,)" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

namespace OpenTelemetry.Exporter.Geneva.Tests;

#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
public class GenevaMetricExporterTests
{
[Fact]
Expand Down Expand Up @@ -1421,3 +1422,4 @@ private static UserdataV2 GetSerializedData(Metric metric, GenevaMetricExporter
return result;
}
}
#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
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,9 @@ public void TLDTraceExporter_Success_Windows()
{
activity?.SetTag("foo", 1);
activity?.SetTag("bar", "Hello, World!");
#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
activity?.SetTag("baz", new int[] { 1, 2, 3 });
#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
activity?.SetStatus(ActivityStatusCode.Ok);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
<!--KaitaiStruct.Runtime.CSharp which is used to deserialize metrics data is not a strong-named assembly.
StrongNamer signs any unsigned assemblies present in the project dependencies -->
<PackageReference Include="StrongNamer" Version="0.2.5" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
<PackageReference Include="OpenTelemetry.Exporter.InMemory" Version="$(OpenTelemetryExporterInMemoryLatestPreReleasePkgVer)" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Exporter.OneCollector\OpenTelemetry.Exporter.OneCollector.csproj" />
</ItemGroup>

<ItemGroup>
<Reference Include="System.Net.Http" Condition="'$(TargetFrameworkIdentifier)' != '.NETCoreApp'" />
</ItemGroup>

<ItemGroup>
<Compile Include="$(RepoRoot)\test\OpenTelemetry.Contrib.Tests.Shared\SkipUnlessEnvVarFoundFactAttribute.cs" Link="Includes\SkipUnlessEnvVarFoundFactAttribute.cs" />
<Compile Include="$(RepoRoot)\test\OpenTelemetry.Contrib.Tests.Shared\SkipUnlessEnvVarFoundTheoryAttribute.cs" Link="Includes\SkipUnlessEnvVarFoundTheoryAttribute.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,13 @@ public void CpuTimeMetricsAreCaptured()
{
foreach (var tag in points.Current.Tags)
{
if (tag.Key == "state" && tag.Value.ToString() == "user")
Assert.NotNull(tag.Value);

if (tag.Key == "state" && tag.Value!.ToString() == "user")
{
userTimeCaptured = true;
}
else if (tag.Key == "state" && tag.Value.ToString() == "system")
else if (tag.Key == "state" && tag.Value!.ToString() == "system")
{
systemTimeCaptured = true;
}
Expand Down

0 comments on commit 5167fbe

Please sign in to comment.