Fix IDE0090: 'using' statement can be simplified. (#3017)

This commit is contained in:
Travis Illig 2022-03-10 21:32:41 -08:00 committed by GitHub
parent 58f13ba7e2
commit d55de344f1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 170 additions and 244 deletions

View File

@ -64,6 +64,7 @@ dotnet_sort_system_directives_first = true
csharp_prefer_braces = true:silent
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true
csharp_prefer_simple_using_statement = true:suggestion
dotnet_style_readonly_field = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion

View File

@ -35,14 +35,8 @@ public class Program
.AddMyExporter()
.Build();
using (var foo = DemoSource.StartActivity("Foo"))
{
using (var bar = DemoSource.StartActivity("Bar"))
{
using (var baz = DemoSource.StartActivity("Baz"))
{
}
}
}
using var foo = DemoSource.StartActivity("Foo");
using var bar = DemoSource.StartActivity("Bar");
using var baz = DemoSource.StartActivity("Baz");
}
}

View File

@ -31,11 +31,9 @@ public class Program
.AddConsoleExporter()
.Build();
using (var activity = MyActivitySource.StartActivity("SayHello"))
{
activity?.SetTag("foo", 1);
activity?.SetTag("bar", "Hello, World!");
activity?.SetTag("baz", new int[] { 1, 2, 3 });
}
using var activity = MyActivitySource.StartActivity("SayHello");
activity?.SetTag("foo", 1);
activity?.SetTag("bar", "Hello, World!");
activity?.SetTag("baz", new int[] { 1, 2, 3 });
}
}

View File

@ -15,7 +15,7 @@
// </copyright>
namespace Examples.AspNetCore.Controllers;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
[ApiController]

View File

@ -57,15 +57,13 @@ namespace Examples.Console
// The above line is required only in applications
// which decide to use OpenTelemetry.
using (var sample = new InstrumentationWithActivitySource())
{
sample.Start();
using var sample = new InstrumentationWithActivitySource();
sample.Start();
System.Console.WriteLine("Traces are being created and exported " +
"to the collection passed in the background. " +
"Press ENTER to stop.");
System.Console.ReadLine();
}
System.Console.WriteLine("Traces are being created and exported " +
"to the collection passed in the background. " +
"Press ENTER to stop.");
System.Console.ReadLine();
}
}
}

View File

@ -53,10 +53,8 @@ namespace Examples.Console
parentScope.Span.SetOperationName("parent span new name");
// The child scope will automatically use parentScope as its parent.
using (IScope childScope = tracer.BuildSpan("Child").StartActive(finishSpanOnDispose: true))
{
childScope.Span.SetTag("Child Tag", "Child Tag Value").SetTag("ch", "value").SetTag("more", "attributes");
}
using IScope childScope = tracer.BuildSpan("Child").StartActive(finishSpanOnDispose: true);
childScope.Span.SetTag("Child Tag", "Child Tag Value").SetTag("ch", "value").SetTag("more", "attributes");
}
System.Console.WriteLine("Press Enter key to exit.");

View File

@ -81,33 +81,31 @@ namespace Examples.Console
// Start another activity. If another activity was already started, it'll use that activity as the parent activity.
// In this example, the main method already started a activity, so that'll be the parent activity, and this will be
// a child activity.
using (Activity activity = activitySource.StartActivity("DoWork"))
using Activity activity = activitySource.StartActivity("DoWork");
try
{
try
{
db.StringSet("key", "value " + DateTime.Now.ToLongDateString());
db.StringSet("key", "value " + DateTime.Now.ToLongDateString());
System.Console.WriteLine("Doing busy work");
Thread.Sleep(1000);
System.Console.WriteLine("Doing busy work");
Thread.Sleep(1000);
// run a command, in this case a GET
var myVal = db.StringGet("key");
// run a command, in this case a GET
var myVal = db.StringGet("key");
System.Console.WriteLine(myVal);
}
catch (ArgumentOutOfRangeException e)
{
activity.SetStatus(Status.Error.WithDescription(e.ToString()));
}
System.Console.WriteLine(myVal);
}
catch (ArgumentOutOfRangeException e)
{
activity.SetStatus(Status.Error.WithDescription(e.ToString()));
}
// Annotate our activity to capture metadata about our operation
var attributes = new Dictionary<string, object>
// Annotate our activity to capture metadata about our operation
var attributes = new Dictionary<string, object>
{
{ "use", "demo" },
};
ActivityTagsCollection eventTags = new ActivityTagsCollection(attributes);
activity.AddEvent(new ActivityEvent("Invoking DoWork", default, eventTags));
}
ActivityTagsCollection eventTags = new ActivityTagsCollection(attributes);
activity.AddEvent(new ActivityEvent("Invoking DoWork", default, eventTags));
}
}
}

View File

@ -65,26 +65,24 @@ namespace Utils.Messaging
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/messaging.md#span-name
var activityName = $"{ea.RoutingKey} receive";
using (var activity = ActivitySource.StartActivity(activityName, ActivityKind.Consumer, parentContext.ActivityContext))
using var activity = ActivitySource.StartActivity(activityName, ActivityKind.Consumer, parentContext.ActivityContext);
try
{
try
{
var message = Encoding.UTF8.GetString(ea.Body.Span.ToArray());
var message = Encoding.UTF8.GetString(ea.Body.Span.ToArray());
this.logger.LogInformation($"Message received: [{message}]");
this.logger.LogInformation($"Message received: [{message}]");
activity?.SetTag("message", message);
activity?.SetTag("message", message);
// The OpenTelemetry messaging specification defines a number of attributes. These attributes are added here.
RabbitMqHelper.AddMessagingTags(activity);
// The OpenTelemetry messaging specification defines a number of attributes. These attributes are added here.
RabbitMqHelper.AddMessagingTags(activity);
// Simulate some work
Thread.Sleep(1000);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Message processing failed.");
}
// Simulate some work
Thread.Sleep(1000);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Message processing failed.");
}
}

View File

@ -55,42 +55,40 @@ namespace Utils.Messaging
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/messaging.md#span-name
var activityName = $"{RabbitMqHelper.TestQueueName} send";
using (var activity = ActivitySource.StartActivity(activityName, ActivityKind.Producer))
using var activity = ActivitySource.StartActivity(activityName, ActivityKind.Producer);
var props = this.channel.CreateBasicProperties();
// Depending on Sampling (and whether a listener is registered or not), the
// activity above may not be created.
// If it is created, then propagate its context.
// If it is not created, the propagate the Current context,
// if any.
ActivityContext contextToInject = default;
if (activity != null)
{
var props = this.channel.CreateBasicProperties();
// Depending on Sampling (and whether a listener is registered or not), the
// activity above may not be created.
// If it is created, then propagate its context.
// If it is not created, the propagate the Current context,
// if any.
ActivityContext contextToInject = default;
if (activity != null)
{
contextToInject = activity.Context;
}
else if (Activity.Current != null)
{
contextToInject = Activity.Current.Context;
}
// Inject the ActivityContext into the message headers to propagate trace context to the receiving service.
Propagator.Inject(new PropagationContext(contextToInject, Baggage.Current), props, this.InjectTraceContextIntoBasicProperties);
// The OpenTelemetry messaging specification defines a number of attributes. These attributes are added here.
RabbitMqHelper.AddMessagingTags(activity);
var body = $"Published message: DateTime.Now = {DateTime.Now}.";
this.channel.BasicPublish(
exchange: RabbitMqHelper.DefaultExchangeName,
routingKey: RabbitMqHelper.TestQueueName,
basicProperties: props,
body: Encoding.UTF8.GetBytes(body));
this.logger.LogInformation($"Message sent: [{body}]");
return body;
contextToInject = activity.Context;
}
else if (Activity.Current != null)
{
contextToInject = Activity.Current.Context;
}
// Inject the ActivityContext into the message headers to propagate trace context to the receiving service.
Propagator.Inject(new PropagationContext(contextToInject, Baggage.Current), props, this.InjectTraceContextIntoBasicProperties);
// The OpenTelemetry messaging specification defines a number of attributes. These attributes are added here.
RabbitMqHelper.AddMessagingTags(activity);
var body = $"Published message: DateTime.Now = {DateTime.Now}.";
this.channel.BasicPublish(
exchange: RabbitMqHelper.DefaultExchangeName,
routingKey: RabbitMqHelper.TestQueueName,
basicProperties: props,
body: Encoding.UTF8.GetBytes(body));
this.logger.LogInformation($"Message sent: [{body}]");
return body;
}
catch (Exception ex)
{

View File

@ -114,93 +114,71 @@ namespace Benchmarks.Trace
[Benchmark]
public void NoListener()
{
using (var activity = this.sourceWithNoListener.StartActivity("Benchmark"))
{
// this activity won't be created as there is no listener
}
// this activity won't be created as there is no listener
using var activity = this.sourceWithNoListener.StartActivity("Benchmark");
}
[Benchmark]
public void PropagationDataListner()
{
using (var activity = this.sourceWithPropagationDataListner.StartActivity("Benchmark"))
{
// this activity will be created and feed into an ActivityListener that simply drops everything on the floor
}
// this activity will be created and feed into an ActivityListener that simply drops everything on the floor
using var activity = this.sourceWithPropagationDataListner.StartActivity("Benchmark");
}
[Benchmark]
public void AllDataListner()
{
using (var activity = this.sourceWithAllDataListner.StartActivity("Benchmark"))
{
// this activity will be created and feed into an ActivityListener that simply drops everything on the floor
}
// this activity will be created and feed into an ActivityListener that simply drops everything on the floor
using var activity = this.sourceWithAllDataListner.StartActivity("Benchmark");
}
[Benchmark]
public void AllDataAndRecordedListner()
{
using (var activity = this.sourceWithAllDataAndRecordedListner.StartActivity("Benchmark"))
{
// this activity will be created and feed into an ActivityListener that simply drops everything on the floor
}
// this activity will be created and feed into an ActivityListener that simply drops everything on the floor
using var activity = this.sourceWithAllDataAndRecordedListner.StartActivity("Benchmark");
}
[Benchmark]
public void OneProcessor()
{
using (var activity = this.sourceWithOneProcessor.StartActivity("Benchmark"))
{
}
using var activity = this.sourceWithOneProcessor.StartActivity("Benchmark");
}
[Benchmark]
public void TwoProcessors()
{
using (var activity = this.sourceWithTwoProcessors.StartActivity("Benchmark"))
{
}
using var activity = this.sourceWithTwoProcessors.StartActivity("Benchmark");
}
[Benchmark]
public void ThreeProcessors()
{
using (var activity = this.sourceWithThreeProcessors.StartActivity("Benchmark"))
{
}
using var activity = this.sourceWithThreeProcessors.StartActivity("Benchmark");
}
[Benchmark]
public void OneInstrumentation()
{
using (var activity = this.sourceWithOneLegacyActivityOperationNameSubscription.StartActivity("Benchmark"))
{
}
using var activity = this.sourceWithOneLegacyActivityOperationNameSubscription.StartActivity("Benchmark");
}
[Benchmark]
public void TwoInstrumentations()
{
using (var activity = this.sourceWithTwoLegacyActivityOperationNameSubscriptions.StartActivity("Benchmark"))
{
}
using var activity = this.sourceWithTwoLegacyActivityOperationNameSubscriptions.StartActivity("Benchmark");
}
[Benchmark]
public void LegacyActivity_ExactMatchMode()
{
using (var activity = new Activity("ExactMatch.OperationName1").Start())
{
}
using var activity = new Activity("ExactMatch.OperationName1").Start();
}
[Benchmark]
public void LegacyActivity_WildcardMatchMode()
{
using (var activity = new Activity("WildcardMatch.OperationName1").Start())
{
}
using var activity = new Activity("WildcardMatch.OperationName1").Start();
}
internal class DummyActivityProcessor : BaseProcessor<Activity>

View File

@ -58,34 +58,26 @@ namespace Benchmarks.Trace
[Benchmark]
public void NoListener()
{
using (var activity = this.tracerWithNoListener.StartActiveSpan("Benchmark"))
{
// this activity won't be created as there is no listener
}
// this activity won't be created as there is no listener
using var activity = this.tracerWithNoListener.StartActiveSpan("Benchmark");
}
[Benchmark]
public void OneProcessor()
{
using (var activity = this.tracerWithOneProcessor.StartActiveSpan("Benchmark"))
{
}
using var activity = this.tracerWithOneProcessor.StartActiveSpan("Benchmark");
}
[Benchmark]
public void TwoProcessors()
{
using (var activity = this.tracerWithTwoProcessors.StartActiveSpan("Benchmark"))
{
}
using var activity = this.tracerWithTwoProcessors.StartActiveSpan("Benchmark");
}
[Benchmark]
public void ThreeProcessors()
{
using (var activity = this.tracerWithThreeProcessors.StartActiveSpan("Benchmark"))
{
}
using var activity = this.tracerWithThreeProcessors.StartActiveSpan("Benchmark");
}
internal class DummyActivityProcessor : BaseProcessor<Activity>

View File

@ -389,13 +389,11 @@ namespace OpenTelemetry.Instrumentation.AspNet.Tests
{
stream = typeof(WebConfigTransformTest).Assembly.GetManifestResourceStream(transformationResourceName);
var document = new XmlTransformableDocument();
using (var transformation = new XmlTransformation(stream, null))
{
stream = null;
document.LoadXml(originalConfiguration);
transformation.Apply(document);
result = XDocument.Parse(document.OuterXml);
}
using var transformation = new XmlTransformation(stream, null);
stream = null;
document.LoadXml(originalConfiguration);
transformation.Apply(document);
result = XDocument.Parse(document.OuterXml);
}
finally
{

View File

@ -419,13 +419,11 @@ namespace OpenTelemetry.Instrumentation.AspNet.Tests
{
stream = typeof(WebConfigTransformTest).Assembly.GetManifestResourceStream(transformationResourceName);
var document = new XmlTransformableDocument();
using (var transformation = new XmlTransformation(stream, null))
{
stream = null;
document.LoadXml(originalConfiguration);
transformation.Apply(document);
result = XDocument.Parse(document.OuterXml);
}
using var transformation = new XmlTransformation(stream, null);
stream = null;
document.LoadXml(originalConfiguration);
transformation.Apply(document);
result = XDocument.Parse(document.OuterXml);
}
finally
{

View File

@ -340,12 +340,10 @@ namespace OpenTelemetry.Instrumentation.Grpc.Tests
.AddProcessor(processor.Object)
.Build())
{
using (var activity = source.StartActivity("parent"))
{
var channel = GrpcChannel.ForAddress(uri);
var client = new Greeter.GreeterClient(channel);
var rs = client.SayHello(new HelloRequest(), headers);
}
using var activity = source.StartActivity("parent");
var channel = GrpcChannel.ForAddress(uri);
var client = new Greeter.GreeterClient(channel);
var rs = client.SayHello(new HelloRequest(), headers);
}
Assert.Equal(7, processor.Invocations.Count); // SetParentProvider/OnShutdown/Dispose called.
@ -404,14 +402,12 @@ namespace OpenTelemetry.Instrumentation.Grpc.Tests
.AddProcessor(processor.Object)
.Build())
{
using (var activity = source.StartActivity("parent"))
using var activity = source.StartActivity("parent");
using (SuppressInstrumentationScope.Begin())
{
using (SuppressInstrumentationScope.Begin())
{
var channel = GrpcChannel.ForAddress(uri);
var client = new Greeter.GreeterClient(channel);
var rs = client.SayHello(new HelloRequest());
}
var channel = GrpcChannel.ForAddress(uri);
var client = new Greeter.GreeterClient(channel);
var rs = client.SayHello(new HelloRequest());
}
}

View File

@ -323,11 +323,9 @@ namespace OpenTelemetry.Instrumentation.Http.Tests
.Build())
{
using var c = new HttpClient();
using (var inMemoryEventListener = new InMemoryEventListener(HttpInstrumentationEventSource.Log))
{
await c.GetAsync(this.url);
Assert.Single(inMemoryEventListener.Events.Where((e) => e.EventId == 4));
}
using var inMemoryEventListener = new InMemoryEventListener(HttpInstrumentationEventSource.Log);
await c.GetAsync(this.url);
Assert.Single(inMemoryEventListener.Events.Where((e) => e.EventId == 4));
}
Assert.Equal(4, processor.Invocations.Count); // SetParentProvider/OnShutdown/Dispose/OnStart called.

View File

@ -43,22 +43,21 @@ namespace OpenTelemetry.Instrumentation.W3cTraceContext.Tests
public void W3CTraceContextTestSuite(string value)
{
// Arrange
using (var server = new InProcessServer(this.output))
{
// Act
// Run Python script in test folder of W3C Trace Context repository
string result = RunCommand("python", "trace-context/test/test.py http://127.0.0.1:5000/api/forward");
using var server = new InProcessServer(this.output);
// Assert
// Assert on the last line
// TODO: fix W3C Trace Context test suite
// ASP NET Core 2.1: FAILED (failures=1)
// ASP NET Core 3.1: FAILED (failures=3)
// ASP NET Core 5.0: FAILED (failures=3)
string lastLine = ParseLastLine(result);
this.output.WriteLine("result:" + result);
Assert.StartsWith("FAILED", lastLine);
}
// Act
// Run Python script in test folder of W3C Trace Context repository
string result = RunCommand("python", "trace-context/test/test.py http://127.0.0.1:5000/api/forward");
// Assert
// Assert on the last line
// TODO: fix W3C Trace Context test suite
// ASP NET Core 2.1: FAILED (failures=1)
// ASP NET Core 3.1: FAILED (failures=3)
// ASP NET Core 5.0: FAILED (failures=3)
string lastLine = ParseLastLine(result);
this.output.WriteLine("result:" + result);
Assert.StartsWith("FAILED", lastLine);
}
private static string RunCommand(string command, string args)

View File

@ -67,11 +67,9 @@ namespace OpenTelemetry.Trace.Tests
var activity = new Activity("test");
using (var processor = new CompositeProcessor<Activity>(new[] { p1 }))
{
Assert.Throws<Exception>(() => { processor.OnStart(activity); });
Assert.Throws<Exception>(() => { processor.OnEnd(activity); });
}
using var processor = new CompositeProcessor<Activity>(new[] { p1 });
Assert.Throws<Exception>(() => { processor.OnStart(activity); });
Assert.Throws<Exception>(() => { processor.OnEnd(activity); });
}
[Fact]
@ -80,12 +78,10 @@ namespace OpenTelemetry.Trace.Tests
using var p1 = new TestActivityProcessor(null, null);
using var p2 = new TestActivityProcessor(null, null);
using (var processor = new CompositeProcessor<Activity>(new[] { p1, p2 }))
{
processor.Shutdown();
Assert.True(p1.ShutdownCalled);
Assert.True(p2.ShutdownCalled);
}
using var processor = new CompositeProcessor<Activity>(new[] { p1, p2 });
processor.Shutdown();
Assert.True(p1.ShutdownCalled);
Assert.True(p2.ShutdownCalled);
}
[Theory]
@ -97,13 +93,11 @@ namespace OpenTelemetry.Trace.Tests
using var p1 = new TestActivityProcessor(null, null);
using var p2 = new TestActivityProcessor(null, null);
using (var processor = new CompositeProcessor<Activity>(new[] { p1, p2 }))
{
processor.ForceFlush(timeout);
using var processor = new CompositeProcessor<Activity>(new[] { p1, p2 });
processor.ForceFlush(timeout);
Assert.True(p1.ForceFlushCalled);
Assert.True(p2.ForceFlushCalled);
}
Assert.True(p1.ForceFlushCalled);
Assert.True(p2.ForceFlushCalled);
}
}
}

View File

@ -140,12 +140,10 @@ namespace OpenTelemetry.Trace.Tests
using (var parent = activitySource.StartActivity("parent", ActivityKind.Client))
{
Assert.Equal(parent.TraceId, testSampler.LatestSamplingParameters.TraceId);
using (var child = activitySource.StartActivity("child"))
{
Assert.Equal(child.TraceId, testSampler.LatestSamplingParameters.TraceId);
Assert.Equal(parent.TraceId, child.TraceId);
Assert.Equal(parent.SpanId, child.ParentSpanId);
}
using var child = activitySource.StartActivity("child");
Assert.Equal(child.TraceId, testSampler.LatestSamplingParameters.TraceId);
Assert.Equal(parent.TraceId, child.TraceId);
Assert.Equal(parent.SpanId, child.ParentSpanId);
}
var customContext = new ActivityContext(
@ -178,19 +176,17 @@ namespace OpenTelemetry.Trace.Tests
Assert.Equal(expectedParentSpanId, fromCustomContextAsString.ParentSpanId);
}
using (var fromInvalidW3CIdParent =
activitySource.StartActivity("customContext", ActivityKind.Client, "InvalidW3CIdParent"))
{
// Verify that StartActivity returns an instance of Activity.
Assert.NotNull(fromInvalidW3CIdParent);
// Verify that StartActivity returns an instance of Activity.
using var fromInvalidW3CIdParent =
activitySource.StartActivity("customContext", ActivityKind.Client, "InvalidW3CIdParent");
Assert.NotNull(fromInvalidW3CIdParent);
// Verify that the TestSampler was invoked and received the correct params.
Assert.Equal(fromInvalidW3CIdParent.TraceId, testSampler.LatestSamplingParameters.TraceId);
// Verify that the TestSampler was invoked and received the correct params.
Assert.Equal(fromInvalidW3CIdParent.TraceId, testSampler.LatestSamplingParameters.TraceId);
// OpenTelemetry ActivityContext does not support non W3C Ids.
Assert.Null(fromInvalidW3CIdParent.ParentId);
Assert.Equal(default(ActivitySpanId), fromInvalidW3CIdParent.ParentSpanId);
}
// OpenTelemetry ActivityContext does not support non W3C Ids.
Assert.Null(fromInvalidW3CIdParent.ParentId);
Assert.Equal(default(ActivitySpanId), fromInvalidW3CIdParent.ParentSpanId);
}
[Theory]
@ -213,14 +209,12 @@ namespace OpenTelemetry.Trace.Tests
.SetSampler(testSampler)
.Build();
using (var rootActivity = activitySource.StartActivity("root"))
using var rootActivity = activitySource.StartActivity("root");
Assert.NotNull(rootActivity);
Assert.Equal(rootActivity.TraceId, testSampler.LatestSamplingParameters.TraceId);
if (sampling != SamplingDecision.Drop)
{
Assert.NotNull(rootActivity);
Assert.Equal(rootActivity.TraceId, testSampler.LatestSamplingParameters.TraceId);
if (sampling != SamplingDecision.Drop)
{
Assert.Contains(new KeyValuePair<string, object>("tagkeybysampler", "tagvalueaddedbysampler"), rootActivity.TagObjects);
}
Assert.Contains(new KeyValuePair<string, object>("tagkeybysampler", "tagvalueaddedbysampler"), rootActivity.TagObjects);
}
}
@ -273,12 +267,10 @@ namespace OpenTelemetry.Trace.Tests
Assert.False(activity.IsAllDataRequested);
Assert.False(activity.Recorded);
using (var innerActivity = activitySource.StartActivity("inner"))
{
// This is not a root activity.
// If sampling returns false, no activity is created at all.
Assert.Null(innerActivity);
}
// This is not a root activity.
// If sampling returns false, no activity is created at all.
using var innerActivity = activitySource.StartActivity("inner");
Assert.Null(innerActivity);
}
}
@ -294,10 +286,8 @@ namespace OpenTelemetry.Trace.Tests
.SetSampler(testSampler)
.Build();
using (var activity = activitySource.StartActivity("root"))
{
Assert.Null(activity);
}
using var activity = activitySource.StartActivity("root");
Assert.Null(activity);
}
[Fact]