diff --git a/benchmarks/Elastic.Apm.Benchmarks/MetricsBenchmarks.cs b/benchmarks/Elastic.Apm.Benchmarks/MetricsBenchmarks.cs index 49cbca062..41db0b685 100644 --- a/benchmarks/Elastic.Apm.Benchmarks/MetricsBenchmarks.cs +++ b/benchmarks/Elastic.Apm.Benchmarks/MetricsBenchmarks.cs @@ -58,7 +58,7 @@ public void CollectTotalCpuTime2X() [Benchmark] public void CollectTotalAndFreeMemory2X() { - var mockPayloadSender = new FreeAndTotalMemoryProvider( new List()); + var mockPayloadSender = new FreeAndTotalMemoryProvider(new List()); mockPayloadSender.GetSamples(); mockPayloadSender.GetSamples(); diff --git a/benchmarks/Elastic.Apm.Benchmarks/Program.cs b/benchmarks/Elastic.Apm.Benchmarks/Program.cs index 55ebba2c5..73c56fb0f 100644 --- a/benchmarks/Elastic.Apm.Benchmarks/Program.cs +++ b/benchmarks/Elastic.Apm.Benchmarks/Program.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/benchmarks/Elastic.Apm.Benchmarks/TracerBenchmarks.cs b/benchmarks/Elastic.Apm.Benchmarks/TracerBenchmarks.cs index 75555f1eb..f5d251316 100644 --- a/benchmarks/Elastic.Apm.Benchmarks/TracerBenchmarks.cs +++ b/benchmarks/Elastic.Apm.Benchmarks/TracerBenchmarks.cs @@ -59,14 +59,16 @@ public void SimpleTransactionsWith1SpanWithoutStackTrace() public void Simple100Transaction10Spans() => _agent.Tracer.CaptureTransaction("transaction", "perfTransaction", transaction => { - for (var j = 0; j < 10; j++) transaction.CaptureSpan("span", "perfSpan", () => { }); + for (var j = 0; j < 10; j++) + transaction.CaptureSpan("span", "perfSpan", () => { }); }); [Benchmark] public void DebugLogSimpleTransaction10Spans() => _agent.Tracer.CaptureTransaction("transaction", "perfTransaction", transaction => { - for (var j = 0; j < 10; j++) transaction.CaptureSpan("span", "perfSpan", () => { }); + for (var j = 0; j < 10; j++) + transaction.CaptureSpan("span", "perfSpan", () => { }); }); } } diff --git a/benchmarks/Elastic.Apm.Benchmarks/WildcardMatcherBenchmark.cs b/benchmarks/Elastic.Apm.Benchmarks/WildcardMatcherBenchmark.cs index 5b7e13003..f7d73621a 100644 --- a/benchmarks/Elastic.Apm.Benchmarks/WildcardMatcherBenchmark.cs +++ b/benchmarks/Elastic.Apm.Benchmarks/WildcardMatcherBenchmark.cs @@ -19,7 +19,8 @@ public void Setup() { _str = string.Empty; var random = new Random(); - for (var i = 0; i < 1000; i++) _str += random.Next(10).ToString(); + for (var i = 0; i < 1000; i++) + _str += random.Next(10).ToString(); } [Benchmark] diff --git a/dotnet-tools.json b/dotnet-tools.json index e5fd17baf..95b93235a 100644 --- a/dotnet-tools.json +++ b/dotnet-tools.json @@ -13,6 +13,12 @@ "commands": [ "minver" ] + }, + "dotnet-format": { + "version": "5.1.250801", + "commands": [ + "dotnet-format" + ] } } } \ No newline at end of file diff --git a/sample/ApiSamples/Program.cs b/sample/ApiSamples/Program.cs index c8888a9c6..f13d06712 100644 --- a/sample/ApiSamples/Program.cs +++ b/sample/ApiSamples/Program.cs @@ -301,7 +301,9 @@ public static void SampleSpanWithCustomContextFillAll() { span.Context.Db = new Database { - Statement = "GET /_all/_search?q=tag:wow", Type = Database.TypeElasticsearch, Instance = "MyInstance" + Statement = "GET /_all/_search?q=tag:wow", + Type = Database.TypeElasticsearch, + Instance = "MyInstance" }; }); }); diff --git a/sample/Elastic.Apm.Azure.ServiceBus.Sample/Program.cs b/sample/Elastic.Apm.Azure.ServiceBus.Sample/Program.cs index 35ce5ff60..634c80c07 100644 --- a/sample/Elastic.Apm.Azure.ServiceBus.Sample/Program.cs +++ b/sample/Elastic.Apm.Azure.ServiceBus.Sample/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Threading.Tasks; using Azure.Messaging.ServiceBus; @@ -25,8 +25,8 @@ private static async Task Main(string[] args) var connectionString = args[0]; _client = new ServiceBusClient(connectionString); - _queueName = "foo"; //Guid.NewGuid().ToString("D"); - + _queueName = "foo"; //Guid.NewGuid().ToString("D"); + await ReadMessages(); Console.WriteLine("Press any key to continue..."); @@ -40,8 +40,8 @@ private static async Task SendSingleMessage() var sender = _client.CreateSender(_queueName); await Agent.Tracer.CaptureTransaction("Send AzureServiceBus Single Message", "messaging", async () => - { - await sender.SendMessageAsync(new ServiceBusMessage($"test message - single")).ConfigureAwait(false); + { + await sender.SendMessageAsync(new ServiceBusMessage($"test message - single")).ConfigureAwait(false); }); Console.WriteLine("Messages sent"); @@ -86,7 +86,8 @@ private static async Task SendMessages() await Agent.Tracer.CaptureTransaction("Send AzureServiceBus Messages", "messaging", async () => { - for (var i = 0; i < 10; i++) await sender.SendMessageAsync(new ServiceBusMessage($"test message {i}")).ConfigureAwait(false); + for (var i = 0; i < 10; i++) + await sender.SendMessageAsync(new ServiceBusMessage($"test message {i}")).ConfigureAwait(false); }); Console.WriteLine("Messages sent"); diff --git a/sample/ElasticsearchSample/Program.cs b/sample/ElasticsearchSample/Program.cs index d6b19a7ac..da593d368 100644 --- a/sample/ElasticsearchSample/Program.cs +++ b/sample/ElasticsearchSample/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using Elastic.Apm; using Elastic.Apm.Api; diff --git a/sample/HttpListenerSample/Program.cs b/sample/HttpListenerSample/Program.cs index 45a678b85..d6e7d2f51 100644 --- a/sample/HttpListenerSample/Program.cs +++ b/sample/HttpListenerSample/Program.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/sample/StackExchangeRedisSample/Program.cs b/sample/StackExchangeRedisSample/Program.cs index 7acc7f8fb..d62cdf468 100644 --- a/sample/StackExchangeRedisSample/Program.cs +++ b/sample/StackExchangeRedisSample/Program.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using Elastic.Apm; using Elastic.Apm.Api; using Elastic.Apm.StackExchange.Redis; @@ -18,16 +18,16 @@ public static async Task Main(string[] args) connection.UseElasticApm(); for (var i = 0; i < 10; i++) - { - // async + { + // async await Agent.Tracer.CaptureTransaction("Set and Get String", ApiConstants.TypeDb, async () => { var database = connection.GetDatabase(); await database.StringSetAsync($"string{i}", i); - await database.StringGetAsync($"string{i}"); - - // fire and forget commands may not end up in the profiling session before - // transaction end, and the profiling session is finished. + await database.StringGetAsync($"string{i}"); + + // fire and forget commands may not end up in the profiling session before + // transaction end, and the profiling session is finished. await database.StringSetAsync($"string{i}", i, flags: CommandFlags.FireAndForget); await database.StringGetAsync($"string{i}", CommandFlags.FireAndForget); }); diff --git a/src/Elastic.Apm.Specification/ImplementationProperty.cs b/src/Elastic.Apm.Specification/ImplementationProperty.cs index 4007c2719..a9036b2b3 100644 --- a/src/Elastic.Apm.Specification/ImplementationProperty.cs +++ b/src/Elastic.Apm.Specification/ImplementationProperty.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; namespace Elastic.Apm.Specification -{ +{ /// /// A property defined on a type that implements the APM server specification /// @@ -17,26 +17,26 @@ public ImplementationProperty(string name, Type propertyType, Type declaringType Name = name; PropertyType = propertyType; DeclaringType = declaringType; - } - + } + /// /// The name of the property /// - public string Name { get; } - + public string Name { get; } + /// /// The type of the property /// - public Type PropertyType { get; } - + public Type PropertyType { get; } + /// /// The type that declares the property /// - public Type DeclaringType { get; } - + public Type DeclaringType { get; } + /// /// The max length that the property value can have /// - public int? MaxLength { get; set; } + public int? MaxLength { get; set; } } } diff --git a/src/Elastic.Apm.Specification/JsonSchemaExtensions.cs b/src/Elastic.Apm.Specification/JsonSchemaExtensions.cs index 06bc8be72..efeaf9c5d 100644 --- a/src/Elastic.Apm.Specification/JsonSchemaExtensions.cs +++ b/src/Elastic.Apm.Specification/JsonSchemaExtensions.cs @@ -1,15 +1,15 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.IO; using NJsonSchema; namespace Elastic.Apm.Specification { public static class JsonSchemaExtensions - { + { /// /// Gets the schema $id if it exists, the name of the property if the schema represents a property, /// or the file name of the schema document path. diff --git a/src/Elastic.Apm.Specification/TypeValidationError.cs b/src/Elastic.Apm.Specification/TypeValidationError.cs index 5ff73469c..a2e16305e 100644 --- a/src/Elastic.Apm.Specification/TypeValidationError.cs +++ b/src/Elastic.Apm.Specification/TypeValidationError.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; namespace Elastic.Apm.Specification diff --git a/src/Elastic.Apm.Specification/TypeValidationResult.cs b/src/Elastic.Apm.Specification/TypeValidationResult.cs index 3fd921e9f..7f30ddd6e 100644 --- a/src/Elastic.Apm.Specification/TypeValidationResult.cs +++ b/src/Elastic.Apm.Specification/TypeValidationResult.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; diff --git a/src/Elastic.Apm.Specification/Validation.cs b/src/Elastic.Apm.Specification/Validation.cs index 1a9c3add9..4d52be6dc 100644 --- a/src/Elastic.Apm.Specification/Validation.cs +++ b/src/Elastic.Apm.Specification/Validation.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + namespace Elastic.Apm.Specification -{ +{ /// /// Determines how validation is performed /// public enum Validation - { + { /// /// Validates the type against the specification. A type must be a valid implementation of the specification, but /// it may be only a subset of the properties i.e. schema properties of type "null" may not be implemented. /// - TypeToSpec, + TypeToSpec, /// /// Validates the specification against the type. A type must match the specification exactly in order to be valid /// diff --git a/src/Elastic.Apm.Specification/Validator.cs b/src/Elastic.Apm.Specification/Validator.cs index 34b692475..8a911e905 100644 --- a/src/Elastic.Apm.Specification/Validator.cs +++ b/src/Elastic.Apm.Specification/Validator.cs @@ -1,8 +1,8 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; -using System.Linq; +using System.Linq; #if !NETSTANDARD using System.Net; #endif @@ -21,7 +21,7 @@ using NJsonSchema; namespace Elastic.Apm.Specification -{ +{ /// /// Validates types against the APM server specification /// @@ -91,74 +91,75 @@ public Validator(string directory) } } - public static async Task DownloadAsync(string branch, string destination) - { - if (Directory.Exists(destination)) - { - try - { - Directory.Delete(destination, true); - } - catch (Exception e) - { - throw new Exception($"Exception deleting directory '{destination}', {e.Message}", e); - } - } - - using var client = new HttpClient(); + public static async Task DownloadAsync(string branch, string destination) + { + if (Directory.Exists(destination)) + { + try + { + Directory.Delete(destination, true); + } + catch (Exception e) + { + throw new Exception($"Exception deleting directory '{destination}', {e.Message}", e); + } + } + + using var client = new HttpClient(); #if !NETSTANDARD // force use of TLS 1.2 on older Full Framework, in order to call GitHub API ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; #endif - - client.DefaultRequestHeaders.UserAgent.Clear(); - client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("apm-agent-dotnet", "1")); - - // use the GitHub api to download the tar.gz and extract the specs from the stream. - // This is considerably faster than downloading many small files. - var response = await client.GetAsync($"https://api.github.com/repos/elastic/apm-server/tarball/{branch}") - .ConfigureAwait(false); - - using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); - using var gzipStream = new GZipStream(stream, CompressionMode.Decompress); - using var tarStream = new TarInputStream(gzipStream, Encoding.UTF8); - - while (true) - { - var entry = tarStream.GetNextEntry(); - if (entry == null) break; - - if (entry.TarHeader.TypeFlag == TarHeader.LF_LINK || entry.TarHeader.TypeFlag == TarHeader.LF_SYMLINK) - continue; - - var name = entry.Name; - var match = SpecPathRegex.Match(name); - - // only interested in the spec files - if (!match.Success) - continue; - - name = match.Groups["path"].Value; - name = name.Replace('/', Path.DirectorySeparatorChar); - - var destFile = Path.Combine(destination, name); - var parentDirectory = Path.GetDirectoryName(destFile); - - try - { - // ReSharper disable once AssignNullToNotNullAttribute - Directory.CreateDirectory(parentDirectory); - } - catch (Exception e) - { - throw new Exception($"Exception creating directory '{parentDirectory}', {e.Message}", e); - } - - using var fileStream = File.Create(destFile); - tarStream.CopyEntryContents(fileStream); - } - } - + + client.DefaultRequestHeaders.UserAgent.Clear(); + client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("apm-agent-dotnet", "1")); + + // use the GitHub api to download the tar.gz and extract the specs from the stream. + // This is considerably faster than downloading many small files. + var response = await client.GetAsync($"https://api.github.com/repos/elastic/apm-server/tarball/{branch}") + .ConfigureAwait(false); + + using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + using var gzipStream = new GZipStream(stream, CompressionMode.Decompress); + using var tarStream = new TarInputStream(gzipStream, Encoding.UTF8); + + while (true) + { + var entry = tarStream.GetNextEntry(); + if (entry == null) + break; + + if (entry.TarHeader.TypeFlag == TarHeader.LF_LINK || entry.TarHeader.TypeFlag == TarHeader.LF_SYMLINK) + continue; + + var name = entry.Name; + var match = SpecPathRegex.Match(name); + + // only interested in the spec files + if (!match.Success) + continue; + + name = match.Groups["path"].Value; + name = name.Replace('/', Path.DirectorySeparatorChar); + + var destFile = Path.Combine(destination, name); + var parentDirectory = Path.GetDirectoryName(destFile); + + try + { + // ReSharper disable once AssignNullToNotNullAttribute + Directory.CreateDirectory(parentDirectory); + } + catch (Exception e) + { + throw new Exception($"Exception creating directory '{parentDirectory}', {e.Message}", e); + } + + using var fileStream = File.Create(destFile); + tarStream.CopyEntryContents(fileStream); + } + } + /// /// Loads the schema for the given specification id. Downloads the schema if it not already downloaded. /// @@ -184,8 +185,8 @@ public async Task LoadSchemaAsync(string specificationId) { throw new JsonSchemaException($"Cannot load schema from path {path}, {e.Message}", e); } - } - + } + /// /// Gets the specification id for the given type. /// @@ -215,8 +216,8 @@ public string GetSpecificationIdForType(Type type) } return specAttributes.Single().Path; - } - + } + /// /// Validates an agent type with the APM server specification. The validation options determine /// how validation is performed. @@ -247,8 +248,8 @@ private async Task ValidateAsync(Type type, string specifi ValidateProperties(type, inheritedSchema, result); return result; - } - + } + /// /// Get the properties for the given specification type, using the APM agent's serialization components. /// @@ -264,11 +265,11 @@ private static ImplementationProperty[] GetProperties(Type specType) JsonObjectContract contract; try - { - // the json schema may indicate a type is an "object", but the agent may model it in some other way - // e.g. samples on metricset is modelled as a collection. In these scenarios, we won't be dealing with - // an object contract and won't be able to statically determine validity of the type to the schema through reflection. - // The only way to validate these against the schema is to serialize the types. + { + // the json schema may indicate a type is an "object", but the agent may model it in some other way + // e.g. samples on metricset is modelled as a collection. In these scenarios, we won't be dealing with + // an object contract and won't be able to statically determine validity of the type to the schema through reflection. + // The only way to validate these against the schema is to serialize the types. contract = (JsonObjectContract)resolver.ResolveContract(specType); } catch (InvalidCastException e) @@ -325,9 +326,9 @@ private static void ValidateProperties(Type specType, JsonSchema schema, TypeVal { ValidateProperties(specType, anyOfSchema, properties, anyOfResults[index]); ++index; - } - - // at least one must be successful + } + + // at least one must be successful if (!anyOfResults.Any(r => r.Success)) { var errors = anyOfResults.Select(r => r.ToString()); @@ -348,9 +349,9 @@ private static void ValidateProperties(Type specType, JsonSchema schema, TypeVal { ValidateProperties(specType, oneOfSchema, properties, oneOfResults[index]); ++index; - } - - // only one must be successful + } + + // only one must be successful if (!oneOfResults.Any(r => r.Success)) { var errors = oneOfResults.Select(r => r.ToString()); @@ -385,8 +386,8 @@ private static void ValidateProperties(Type specType, JsonSchema schema, Impleme var name = kv.Value.Name; var specTypeProperty = properties.SingleOrDefault(p => p.Name == name); if (specTypeProperty == null) - { - // No "type" means any type, which maps to None + { + // No "type" means any type, which maps to None if (schemaProperty.Type.HasFlag(JsonObjectType.None) || schemaProperty.Type.HasFlag(JsonObjectType.Null)) { if (result.Validation == Validation.SpecToType) @@ -396,11 +397,11 @@ private static void ValidateProperties(Type specType, JsonSchema schema, Impleme result.AddError(TypeValidationError.NotFound(specType, schema.GetNameOrSpecificationId(), name)); continue; - } - - // check certain .NET types first before defaulting to the JSON schema flags. - // A property might be represented as more than one type e.g. ["integer", "string", "null], - // so it's better to look at the .NET type first and try to look for the associated JSON schema flag. + } + + // check certain .NET types first before defaulting to the JSON schema flags. + // A property might be represented as more than one type e.g. ["integer", "string", "null], + // so it's better to look at the .NET type first and try to look for the associated JSON schema flag. switch (specTypeProperty.PropertyType.FullName) { case "System.UInt16": @@ -470,10 +471,10 @@ private static void ValidateProperties(Type specType, JsonSchema schema, Impleme name)); } break; - default: - // Are there multiple types? If so, based on the .NET type not being a primitive type, we would expect the presence of the - // schema "object" or "array" type in the majority of cases, so check these first. - // For types with custom serialization, the schema type may be a primitive type, so we can't easily statically validate it. + default: + // Are there multiple types? If so, based on the .NET type not being a primitive type, we would expect the presence of the + // schema "object" or "array" type in the majority of cases, so check these first. + // For types with custom serialization, the schema type may be a primitive type, so we can't easily statically validate it. if (HasMultipleNonNullTypes(schemaProperty.Type)) { if (schemaProperty.Type.HasFlag(JsonObjectType.Object)) @@ -510,8 +511,8 @@ private static void ValidateProperties(Type specType, JsonSchema schema, Impleme break; } } - } - + } + /// /// Check if the JSON schema type has more than one value, other than "null" /// @@ -519,13 +520,13 @@ private static void ValidateProperties(Type specType, JsonSchema schema, Impleme /// private static bool HasMultipleNonNullTypes(JsonObjectType type) { - var typeFlags = type; - - // remove null flag if it exists, and check to see if we have more than one flag + var typeFlags = type; + + // remove null flag if it exists, and check to see if we have more than one flag if (typeFlags.HasFlag(JsonObjectType.Null)) - typeFlags &= ~JsonObjectType.Null; - - // is there still more than one flag? Check to see if it's a power of two + typeFlags &= ~JsonObjectType.Null; + + // is there still more than one flag? Check to see if it's a power of two return (typeFlags & (typeFlags - 1)) != 0; } @@ -630,8 +631,8 @@ TypeValidationResult result } private static bool IsNullableType(Type type) => - type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); - + type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); + /// /// Check if type implements /// diff --git a/src/Elastic.Apm/Agent.cs b/src/Elastic.Apm/Agent.cs index 77cee1d81..9f2fe9d73 100644 --- a/src/Elastic.Apm/Agent.cs +++ b/src/Elastic.Apm/Agent.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -145,7 +145,8 @@ public static class Agent private static bool CheckAndAddFilter(Action action) { - if (!(Instance.PayloadSender is PayloadSenderV2 payloadSenderV2)) return false; + if (!(Instance.PayloadSender is PayloadSenderV2 payloadSenderV2)) + return false; action(payloadSenderV2); return true; diff --git a/src/Elastic.Apm/AgentComponents.cs b/src/Elastic.Apm/AgentComponents.cs index 40d33081c..051f3cac1 100644 --- a/src/Elastic.Apm/AgentComponents.cs +++ b/src/Elastic.Apm/AgentComponents.cs @@ -109,9 +109,9 @@ public class AgentComponents : IApmAgent, IDisposable } #endif PayloadSender = payloadSender - ?? new PayloadSenderV2(Logger, ConfigurationStore.CurrentSnapshot, Service, system, - ApmServerInfo, - isEnabled: ConfigurationReader.Enabled, serverInfoCallback: serverInfoCallback); + ?? new PayloadSenderV2(Logger, ConfigurationStore.CurrentSnapshot, Service, system, + ApmServerInfo, + isEnabled: ConfigurationReader.Enabled, serverInfoCallback: serverInfoCallback); if (ConfigurationReader.Enabled) breakdownMetricsProvider ??= new BreakdownMetricsProvider(Logger); @@ -251,9 +251,11 @@ internal static IApmLogger CheckForProfilerLogger(IApmLogger fallbackLogger, Log public void Dispose() { - if (MetricsCollector is IDisposable disposableMetricsCollector) disposableMetricsCollector.Dispose(); + if (MetricsCollector is IDisposable disposableMetricsCollector) + disposableMetricsCollector.Dispose(); - if (PayloadSender is IDisposable disposablePayloadSender) disposablePayloadSender.Dispose(); + if (PayloadSender is IDisposable disposablePayloadSender) + disposablePayloadSender.Dispose(); CentralConfigurationFetcher?.Dispose(); } diff --git a/src/Elastic.Apm/Api/Cloud.cs b/src/Elastic.Apm/Api/Cloud.cs index 8bc99dc1c..2daee9994 100644 --- a/src/Elastic.Apm/Api/Cloud.cs +++ b/src/Elastic.Apm/Api/Cloud.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Elastic.Apm.Api.Constraints; using Elastic.Apm.Libraries.Newtonsoft.Json; namespace Elastic.Apm.Api -{ +{ /// /// Fields related to the cloud or infrastructure the events are coming from. /// - // TODO: Add Spec attribute once https://github.com/elastic/apm-agent-dotnet/pull/984 is merged. + // TODO: Add Spec attribute once https://github.com/elastic/apm-agent-dotnet/pull/984 is merged. public class Cloud { public CloudAccount Account { get; set; } @@ -22,8 +22,8 @@ public class Cloud [JsonProperty("availability_zone")] public string AvailabilityZone { get; set; } - public CloudMachine Machine { get; set; } - + public CloudMachine Machine { get; set; } + /// /// The cloud provider, for example, aws, gcp, azure. /// @@ -33,19 +33,19 @@ public class Cloud [MaxLength] public string Region { get; set; } - public CloudProject Project { get; set; } - + public CloudProject Project { get; set; } + /// /// The service that is monitored on cloud. /// public CloudService Service { get; set; } - } - + } + /// /// The service that is monitored on cloud. /// public class CloudService - { + { /// /// Name of the cloud service, intended to distinguish services running on different /// platforms within a provider, eg AWS EC2 vs Lambda, GCP GCE vs App Engine, Azure VM vs App Server. @@ -55,31 +55,31 @@ public class CloudService } public class CloudProject - { + { /// /// Cloud project name /// [MaxLength] - public string Name { get; set; } - + public string Name { get; set; } + /// /// Cloud project id /// [MaxLength] public string Id { get; set; } - } - + } + /// /// An instance in a cloud provider /// public class CloudInstance - { + { /// /// Instance ID of the host machine. /// [MaxLength] - public string Id { get; set; } - + public string Id { get; set; } + /// /// Instance name of the host machine. /// @@ -88,7 +88,7 @@ public class CloudInstance } public class CloudAccount - { + { /// /// The cloud account or organization id used to identify different entities in a multi-tenant environment. /// @@ -96,8 +96,8 @@ public class CloudAccount /// Examples: AWS account id, Google Cloud ORG Id, or other unique identifier. /// [MaxLength] - public string Id { get; set; } - + public string Id { get; set; } + /// /// The cloud account name /// @@ -106,7 +106,7 @@ public class CloudAccount } public class CloudMachine - { + { /// /// Machine type of the host machine. /// diff --git a/src/Elastic.Apm/Api/CloudContext.cs b/src/Elastic.Apm/Api/CloudContext.cs index 719191c74..cae310867 100644 --- a/src/Elastic.Apm/Api/CloudContext.cs +++ b/src/Elastic.Apm/Api/CloudContext.cs @@ -1,10 +1,10 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + namespace Elastic.Apm.Api -{ +{ /// /// Data related to the cloud or infrastructure the events are coming from. /// @@ -14,12 +14,12 @@ public class CloudContext } public struct CloudOrigin - { + { /// /// The cloud account or organization id used to identify different entities in a multi-tenant environment. /// - public string Account { get; set; } - + public string Account { get; set; } + /// /// The cloud account or organization id used to identify different entities in a multi-tenant environment. /// diff --git a/src/Elastic.Apm/Api/Constraints/MaxLengthAttribute.cs b/src/Elastic.Apm/Api/Constraints/MaxLengthAttribute.cs index fae0f00c6..0f1227412 100644 --- a/src/Elastic.Apm/Api/Constraints/MaxLengthAttribute.cs +++ b/src/Elastic.Apm/Api/Constraints/MaxLengthAttribute.cs @@ -1,31 +1,31 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; namespace Elastic.Apm.Api.Constraints -{ +{ /// /// Specifies the maximum length of string data allowed in a property, based on the APM server specification. /// [AttributeUsage(AttributeTargets.Property)] public sealed class MaxLengthAttribute : Attribute - { + { /// /// The maximum length. /// - public int Length { get; } - + public int Length { get; } + /// /// Initializes a new instance of /// with a maximum length of /// public MaxLengthAttribute() : this(Consts.PropertyMaxLength) { - } - + } + /// /// Initializes a new instance of with a given maximum length /// diff --git a/src/Elastic.Apm/Api/Constraints/RequiredAttribute.cs b/src/Elastic.Apm/Api/Constraints/RequiredAttribute.cs index 54f2ddb75..48c4cfe45 100644 --- a/src/Elastic.Apm/Api/Constraints/RequiredAttribute.cs +++ b/src/Elastic.Apm/Api/Constraints/RequiredAttribute.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; namespace Elastic.Apm.Api.Constraints -{ +{ /// /// Specifies that a data field value is required. /// diff --git a/src/Elastic.Apm/Api/Context.cs b/src/Elastic.Apm/Api/Context.cs index 415685ed3..448ac7a97 100644 --- a/src/Elastic.Apm/Api/Context.cs +++ b/src/Elastic.Apm/Api/Context.cs @@ -4,9 +4,9 @@ using System; using System.Collections.Generic; +using Elastic.Apm.Libraries.Newtonsoft.Json; using Elastic.Apm.Model; using Elastic.Apm.Report.Serialization; -using Elastic.Apm.Libraries.Newtonsoft.Json; namespace Elastic.Apm.Api { diff --git a/src/Elastic.Apm/Api/Destination.cs b/src/Elastic.Apm/Api/Destination.cs index 801031116..debfd1943 100644 --- a/src/Elastic.Apm/Api/Destination.cs +++ b/src/Elastic.Apm/Api/Destination.cs @@ -58,9 +58,12 @@ public DestinationService Service internal void CopyMissingPropertiesFrom(Destination src) { - if (!_address.HasValue) _address = src._address; - if (!_port.HasValue) _port = src._port; - if (!_service.HasValue) _service = src._service; + if (!_address.HasValue) + _address = src._address; + if (!_port.HasValue) + _port = src._port; + if (!_service.HasValue) + _service = src._service; } /// diff --git a/src/Elastic.Apm/Api/Label.cs b/src/Elastic.Apm/Api/Label.cs index 6a4d5b135..aedf760f6 100644 --- a/src/Elastic.Apm/Api/Label.cs +++ b/src/Elastic.Apm/Api/Label.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/Api/Message.cs b/src/Elastic.Apm/Api/Message.cs index 1749f77a7..5a799707c 100644 --- a/src/Elastic.Apm/Api/Message.cs +++ b/src/Elastic.Apm/Api/Message.cs @@ -1,58 +1,58 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections.Generic; using Elastic.Apm.Api.Constraints; namespace Elastic.Apm.Api -{ +{ /// /// Holds details related to message receiving and publishing if the captured event integrates with a messaging system /// public class Message - { + { /// /// Body of the received message /// - public string Body { get; set; } - + public string Body { get; set; } + /// /// Headers received with the message /// - public Dictionary Headers { get; set; } - + public Dictionary Headers { get; set; } + /// - public Age Age { get; set; } - + public Age Age { get; set; } + /// - public Queue Queue { get; set; } - + public Queue Queue { get; set; } + /// /// optional routing key of the received message as set on the queuing system, such as in RabbitMQ. /// public string RoutingKey { get; set; } - } - + } + /// /// Age of the message. If the monitored messaging framework provides a timestamp for the message, agents may use it. /// Otherwise, the sending agent can add a timestamp in milliseconds since the Unix epoch to the message's metadata to be retrieved by the /// receiving agent. If a timestamp is not available, agents should omit this field. /// public class Age - { + { /// /// Age of the message in milliseconds. /// public long Ms { get; set; } - } - + } + /// /// Information about the message queue where the message is received. /// public class Queue - { + { /// /// Name of the message queue where the message is received /// diff --git a/src/Elastic.Apm/Api/Outcome.cs b/src/Elastic.Apm/Api/Outcome.cs index b6403b4c0..2c3405b58 100644 --- a/src/Elastic.Apm/Api/Outcome.cs +++ b/src/Elastic.Apm/Api/Outcome.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/Api/Request.cs b/src/Elastic.Apm/Api/Request.cs index cc7ad7561..b06e2ef91 100644 --- a/src/Elastic.Apm/Api/Request.cs +++ b/src/Elastic.Apm/Api/Request.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/Api/Response.cs b/src/Elastic.Apm/Api/Response.cs index cea2579a3..4aa248efa 100644 --- a/src/Elastic.Apm/Api/Response.cs +++ b/src/Elastic.Apm/Api/Response.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections.Generic; using System.Linq; using Elastic.Apm.Libraries.Newtonsoft.Json; namespace Elastic.Apm.Api -{ +{ /// /// Encapsulates Response related information that can be attached to an through /// @@ -17,8 +17,8 @@ public class Response { public bool Finished { get; set; } - public Dictionary Headers { get; set; } - + public Dictionary Headers { get; set; } + /// /// The HTTP status code of the response. /// @@ -28,7 +28,7 @@ public class Response internal Response DeepCopy() { var newItem = (Response)MemberwiseClone(); - if(Headers != null) + if (Headers != null) newItem.Headers = Headers.ToDictionary(entry => entry.Key, entry => entry.Value); return newItem; } diff --git a/src/Elastic.Apm/Api/SpanContext.cs b/src/Elastic.Apm/Api/SpanContext.cs index ed8eab417..c0f005795 100644 --- a/src/Elastic.Apm/Api/SpanContext.cs +++ b/src/Elastic.Apm/Api/SpanContext.cs @@ -5,8 +5,8 @@ using System; using System.Collections.Generic; using Elastic.Apm.Helpers; -using Elastic.Apm.Model; using Elastic.Apm.Libraries.Newtonsoft.Json; +using Elastic.Apm.Model; namespace Elastic.Apm.Api { diff --git a/src/Elastic.Apm/Api/SpanService.cs b/src/Elastic.Apm/Api/SpanService.cs index 9d7dc904e..91e368691 100644 --- a/src/Elastic.Apm/Api/SpanService.cs +++ b/src/Elastic.Apm/Api/SpanService.cs @@ -58,7 +58,8 @@ public string ToDestinationServiceResource() { if (!string.IsNullOrEmpty(Type)) sb.Append(Type); - if (string.IsNullOrEmpty(Name)) return sb.ToString(); + if (string.IsNullOrEmpty(Name)) + return sb.ToString(); if (sb.Length > 0) sb.Append("/"); @@ -69,17 +70,22 @@ public string ToDestinationServiceResource() public bool Equals(Target other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + return false; + if (ReferenceEquals(this, other)) + return true; return Type == other.Type && Name == other.Name; } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; + if (ReferenceEquals(null, obj)) + return false; + if (ReferenceEquals(this, obj)) + return true; + if (obj.GetType() != GetType()) + return false; return Equals((Target)obj); } diff --git a/src/Elastic.Apm/Api/SpecificationAttribute.cs b/src/Elastic.Apm/Api/SpecificationAttribute.cs index d6be4452a..de9b431ab 100644 --- a/src/Elastic.Apm/Api/SpecificationAttribute.cs +++ b/src/Elastic.Apm/Api/SpecificationAttribute.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; namespace Elastic.Apm.Api -{ +{ /// /// Defines the apm server specification that the type adheres to /// [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class)] public class SpecificationAttribute : Attribute { - public SpecificationAttribute(string path) => Path = path; - + public SpecificationAttribute(string path) => Path = path; + /// /// Path of the specification, relative to the apm-server directory /// diff --git a/src/Elastic.Apm/ApmAgentExtensions.cs b/src/Elastic.Apm/ApmAgentExtensions.cs index c528c7fea..539d61395 100644 --- a/src/Elastic.Apm/ApmAgentExtensions.cs +++ b/src/Elastic.Apm/ApmAgentExtensions.cs @@ -71,7 +71,8 @@ internal class CompositeDisposable : IDisposable /// This instance of public CompositeDisposable Add(IDisposable disposable) { - if (_isDisposed) throw new ObjectDisposedException(nameof(CompositeDisposable)); + if (_isDisposed) + throw new ObjectDisposedException(nameof(CompositeDisposable)); _disposables.Add(disposable); return this; @@ -79,14 +80,17 @@ public CompositeDisposable Add(IDisposable disposable) public void Dispose() { - if (_isDisposed) return; + if (_isDisposed) + return; lock (_lock) { - if (_isDisposed) return; + if (_isDisposed) + return; _isDisposed = true; - foreach (var d in _disposables) d?.Dispose(); + foreach (var d in _disposables) + d?.Dispose(); } } } diff --git a/src/Elastic.Apm/BackendComm/BackendCommUtils.cs b/src/Elastic.Apm/BackendComm/BackendCommUtils.cs index b420a3c1b..d174f7287 100644 --- a/src/Elastic.Apm/BackendComm/BackendCommUtils.cs +++ b/src/Elastic.Apm/BackendComm/BackendCommUtils.cs @@ -96,7 +96,8 @@ private static Uri CombineAbsoluteAndRelativeUrls(Uri baseAbsoluteUrl, string re // if the relative part of baseUri is to be preserved in the constructed Uri. var baseAbsoluteUrlAdapted = baseAbsoluteUrl; var baseAbsoluteUrlAsStr = baseAbsoluteUrl.ToString(); - if (!baseAbsoluteUrlAsStr.EndsWith("/")) baseAbsoluteUrlAdapted = new Uri(baseAbsoluteUrlAsStr + "/", UriKind.Absolute); + if (!baseAbsoluteUrlAsStr.EndsWith("/")) + baseAbsoluteUrlAdapted = new Uri(baseAbsoluteUrlAsStr + "/", UriKind.Absolute); return new Uri(baseAbsoluteUrlAdapted, relativeUrl); } } @@ -104,7 +105,7 @@ private static Uri CombineAbsoluteAndRelativeUrls(Uri baseAbsoluteUrl, string re private static void ConfigServicePoint(Uri serverUrlBase, IApmLogger logger) => ConfigServicePointOnceHelper.IfNotInited?.Init(() => { -// ServicePointManager is obsolete + // ServicePointManager is obsolete #pragma warning disable SYSLIB0014 var servicePoint = ServicePointManager.FindServicePoint(serverUrlBase); #pragma warning restore SYSLIB0014 @@ -131,7 +132,8 @@ private static HttpClientHandler CreateHttpClientHandler(IConfiguration configur { serverCertificateCustomValidationCallback = (_, _, _, policyError) => { - if (policyError == SslPolicyErrors.None) return true; + if (policyError == SslPolicyErrors.None) + return true; logger.Trace()?.Log("Certificate validation failed. Policy error {PolicyError}", policyError); return true; @@ -146,7 +148,8 @@ private static HttpClientHandler CreateHttpClientHandler(IConfiguration configur serverCertificateCustomValidationCallback = (_, certificate, _, policyError) => { - if (policyError == SslPolicyErrors.None) return true; + if (policyError == SslPolicyErrors.None) + return true; if (certificate is null) { @@ -182,7 +185,8 @@ private static HttpClientHandler CreateHttpClientHandler(IConfiguration configur // set a default callback to log the policy error serverCertificateCustomValidationCallback = (_, _, _, policyError) => { - if (policyError == SslPolicyErrors.None) return true; + if (policyError == SslPolicyErrors.None) + return true; logger.Trace()?.Log("Certificate validation failed. Policy error {PolicyError}", policyError); return false; diff --git a/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfiguration.cs b/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfiguration.cs index a7646d30e..b16526e1e 100644 --- a/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfiguration.cs +++ b/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfiguration.cs @@ -34,11 +34,11 @@ internal class CentralConfiguration : AbstractConfigurationReader, IConfiguratio LogLevel = GetSimpleConfigurationValue(DynamicConfigurationOption.LogLevel, ParseLogLevel); SpanStackTraceMinDurationInMilliseconds = GetSimpleConfigurationValue(DynamicConfigurationOption.SpanStackTraceMinDuration, ParseSpanStackTraceMinDurationInMilliseconds); -// Disable obsolete-warning + // Disable obsolete-warning #pragma warning disable CS0618 SpanFramesMinDurationInMilliseconds = GetSimpleConfigurationValue(DynamicConfigurationOption.SpanFramesMinDuration, ParseSpanFramesMinDurationInMilliseconds); -// Disable obsolete-warning + // Disable obsolete-warning #pragma warning restore CS0618 StackTraceLimit = GetSimpleConfigurationValue(DynamicConfigurationOption.StackTraceLimit, ParseStackTraceLimit); Recording = GetSimpleConfigurationValue(DynamicConfigurationOption.Recording, ParseRecording); @@ -110,12 +110,16 @@ public override string ToString() { var builder = new ToStringBuilder($"[ETag: `{ETag}']"); - if (CaptureBody != null) builder.Add(nameof(CaptureBody), CaptureBody); + if (CaptureBody != null) + builder.Add(nameof(CaptureBody), CaptureBody); if (CaptureBodyContentTypes != null) builder.Add(nameof(CaptureBodyContentTypes), string.Join(", ", CaptureBodyContentTypes.Select(x => $"`{x}'"))); - if (TransactionMaxSpans.HasValue) builder.Add(nameof(TransactionMaxSpans), TransactionMaxSpans.Value); - if (TransactionSampleRate.HasValue) builder.Add(nameof(TransactionSampleRate), TransactionSampleRate.Value); - if (Recording.HasValue) builder.Add(nameof(Recording), Recording.Value); + if (TransactionMaxSpans.HasValue) + builder.Add(nameof(TransactionMaxSpans), TransactionMaxSpans.Value); + if (TransactionSampleRate.HasValue) + builder.Add(nameof(TransactionSampleRate), TransactionSampleRate.Value); + if (Recording.HasValue) + builder.Add(nameof(Recording), Recording.Value); return builder.ToString(); } diff --git a/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfigurationFetcher.cs b/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfigurationFetcher.cs index 2d0922bf4..ce9ab8323 100644 --- a/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfigurationFetcher.cs +++ b/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfigurationFetcher.cs @@ -58,7 +58,8 @@ Service service var isCentralConfigOptEqDefault = _initialSnapshot.CentralConfig == ConfigConsts.DefaultValues.CentralConfig; var centralConfigStatus = _initialSnapshot.CentralConfig ? "enabled" : "disabled"; - if (!isCentralConfigOptEqDefault) centralConfigStatus = centralConfigStatus.ToUpper(); + if (!isCentralConfigOptEqDefault) + centralConfigStatus = centralConfigStatus.ToUpper(); _logger.IfLevel(isCentralConfigOptEqDefault ? LogLevel.Debug : LogLevel.Information) ?.Log("Central configuration feature is {CentralConfigStatus} because CentralConfig option's value is {CentralConfigOptionValue}" + " (default value is {CentralConfigOptionDefaultValue})" @@ -75,7 +76,8 @@ Service service }; } - if (!_initialSnapshot.CentralConfig) return; + if (!_initialSnapshot.CentralConfig) + return; _configurationStore = configurationStore; @@ -172,7 +174,8 @@ protected override void WorkLoopIteration() private HttpRequestMessage BuildHttpRequest(EntityTagHeaderValue eTag) { var httpRequest = new HttpRequestMessage(HttpMethod.Get, _getConfigAbsoluteUrl); - if (eTag != null) httpRequest.Headers.IfNoneMatch.Add(eTag); + if (eTag != null) + httpRequest.Headers.IfNoneMatch.Add(eTag); return httpRequest; } diff --git a/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfigurationResponseParser.cs b/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfigurationResponseParser.cs index 1d96576df..34ffd7ee3 100644 --- a/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfigurationResponseParser.cs +++ b/src/Elastic.Apm/BackendComm/CentralConfig/CentralConfigurationResponseParser.cs @@ -36,7 +36,8 @@ string httpResponseBody var waitInfo = ExtractWaitInfo(httpResponse); try { - if (!InterpretResponseStatusCode(httpResponse, waitInfo)) return (null, waitInfo); + if (!InterpretResponseStatusCode(httpResponse, waitInfo)) + return (null, waitInfo); if (httpResponse?.Headers?.ETag == null) throw new CentralConfigurationFetcher.FailedToFetchConfigException("Response from APM Server doesn't have ETag header", waitInfo); @@ -98,7 +99,8 @@ private static CentralConfigurationFetcher.WaitInfoS ExtractWaitInfo(HttpRespons private bool InterpretResponseStatusCode(HttpResponseMessage httpResponse, CentralConfigurationFetcher.WaitInfoS waitInfo) { - if (httpResponse.IsSuccessStatusCode) return true; + if (httpResponse.IsSuccessStatusCode) + return true; var severity = LogLevel.Error; var statusAsString = $"HTTP status code is {httpResponse.ReasonPhrase} ({(int)httpResponse.StatusCode})"; diff --git a/src/Elastic.Apm/BackendComm/CentralConfig/RuntimeConfigurationSnapshot.cs b/src/Elastic.Apm/BackendComm/CentralConfig/RuntimeConfigurationSnapshot.cs index 003b8e72e..4ffe1dc2d 100644 --- a/src/Elastic.Apm/BackendComm/CentralConfig/RuntimeConfigurationSnapshot.cs +++ b/src/Elastic.Apm/BackendComm/CentralConfig/RuntimeConfigurationSnapshot.cs @@ -21,7 +21,7 @@ internal class RuntimeConfigurationSnapshot : IConfiguration, IConfigurationDesc private readonly IConfigurationReader _mainConfiguration; internal RuntimeConfigurationSnapshot(IConfigurationReader mainConfiguration) - : this(mainConfiguration, null) {} + : this(mainConfiguration, null) { } internal RuntimeConfigurationSnapshot(IConfigurationReader mainConfiguration, CentralConfiguration? dynamicConfiguration) { _mainConfiguration = mainConfiguration; diff --git a/src/Elastic.Apm/Cloud/AwsCloudMetadataProvider.cs b/src/Elastic.Apm/Cloud/AwsCloudMetadataProvider.cs index 903561f4c..c2ace932b 100644 --- a/src/Elastic.Apm/Cloud/AwsCloudMetadataProvider.cs +++ b/src/Elastic.Apm/Cloud/AwsCloudMetadataProvider.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Elastic.Apm.Api; -using Elastic.Apm.Logging; using Elastic.Apm.Libraries.Newtonsoft.Json; using Elastic.Apm.Libraries.Newtonsoft.Json.Linq; +using Elastic.Apm.Logging; namespace Elastic.Apm.Cloud -{ +{ /// /// Provides cloud metadata for Amazon Web Services (AWS) /// @@ -35,11 +35,11 @@ internal AwsCloudMetadataProvider(IApmLogger logger, HttpMessageHandler handler) { _handler = handler; _logger = logger.Scoped(nameof(AwsCloudMetadataProvider)); - } - + } + /// - public string Provider { get; } = Name; - + public string Provider { get; } = Name; + /// public async Task GetMetadataAsync() { @@ -53,7 +53,8 @@ public async Task GetMetadataAsync() var responseMessage = await client.SendAsync(requestMessage).ConfigureAwait(false); awsToken = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); } - if (string.IsNullOrWhiteSpace(awsToken)) return null; + if (string.IsNullOrWhiteSpace(awsToken)) + return null; JObject metadata; using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, MetadataUri)) diff --git a/src/Elastic.Apm/Cloud/AzureAppServiceMetadataProvider.cs b/src/Elastic.Apm/Cloud/AzureAppServiceMetadataProvider.cs index e59898277..b9e1e916f 100644 --- a/src/Elastic.Apm/Cloud/AzureAppServiceMetadataProvider.cs +++ b/src/Elastic.Apm/Cloud/AzureAppServiceMetadataProvider.cs @@ -1,15 +1,15 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections; using System.Threading.Tasks; using Elastic.Apm.Api; using Elastic.Apm.Logging; namespace Elastic.Apm.Cloud -{ +{ /// /// Provides cloud metadata for Microsoft Azure App Services /// @@ -35,10 +35,10 @@ public Task GetMetadataAsync() var websiteSiteName = helper.GetEnvironmentVariable(AzureEnvironmentVariables.WebsiteSiteName); var websiteInstanceId = helper.GetEnvironmentVariable(AzureEnvironmentVariables.WebsiteInstanceId); - if (helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteOwnerName, websiteOwnerName) || - helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteResourceGroup, websiteResourceGroup) || - helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteSiteName, websiteSiteName) || - helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteInstanceId, websiteInstanceId)) + if (helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteOwnerName, websiteOwnerName) || + helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteResourceGroup, websiteResourceGroup) || + helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteSiteName, websiteSiteName) || + helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteInstanceId, websiteInstanceId)) return Task.FromResult(null); var tokens = helper.TokenizeWebSiteOwnerName(websiteOwnerName); diff --git a/src/Elastic.Apm/Cloud/AzureCloudMetadataProvider.cs b/src/Elastic.Apm/Cloud/AzureCloudMetadataProvider.cs index 32f709d13..f9196b84d 100644 --- a/src/Elastic.Apm/Cloud/AzureCloudMetadataProvider.cs +++ b/src/Elastic.Apm/Cloud/AzureCloudMetadataProvider.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Elastic.Apm.Api; -using Elastic.Apm.Logging; using Elastic.Apm.Libraries.Newtonsoft.Json; using Elastic.Apm.Libraries.Newtonsoft.Json.Linq; +using Elastic.Apm.Logging; namespace Elastic.Apm.Cloud -{ +{ /// /// Provides cloud metadata for Microsoft Azure VM /// @@ -34,11 +34,11 @@ internal AzureCloudMetadataProvider(IApmLogger logger, HttpMessageHandler handle public AzureCloudMetadataProvider(IApmLogger logger) : this(logger, new HttpClientHandler()) { - } - + } + /// - public string Provider { get; } = Name; - + public string Provider { get; } = Name; + /// public async Task GetMetadataAsync() { diff --git a/src/Elastic.Apm/Cloud/AzureFunctionsMetadataProvider.cs b/src/Elastic.Apm/Cloud/AzureFunctionsMetadataProvider.cs index 265c65f5e..37a39a721 100644 --- a/src/Elastic.Apm/Cloud/AzureFunctionsMetadataProvider.cs +++ b/src/Elastic.Apm/Cloud/AzureFunctionsMetadataProvider.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections; using System.Threading.Tasks; using Elastic.Apm.Api; @@ -20,8 +20,8 @@ internal struct AzureFunctionsMetaData internal string SubscriptionId { get; set; } internal string FunctionsWorkerRuntime { get; set; } internal string WebsiteInstanceId { get; set; } - } - + } + /// /// Provides cloud metadata for Microsoft Azure Functions /// @@ -55,14 +55,15 @@ public AzureFunctionsMetadataProvider(IApmLogger logger, IDictionary environment helper.GetEnvironmentVariable(AzureEnvironmentVariables.FunctionsWorkerRuntime); var websiteInstanceId = helper.GetEnvironmentVariable(AzureEnvironmentVariables.WebsiteInstanceId); - if (helper.NullOrEmptyVariable(AzureEnvironmentVariables.FunctionsExtensionVersion, - functionsExtensionVersion) || - helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteOwnerName, websiteOwnerName) || - helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteSiteName, websiteSiteName)) + if (helper.NullOrEmptyVariable(AzureEnvironmentVariables.FunctionsExtensionVersion, + functionsExtensionVersion) || + helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteOwnerName, websiteOwnerName) || + helper.NullOrEmptyVariable(AzureEnvironmentVariables.WebsiteSiteName, websiteSiteName)) return new AzureFunctionsMetaData { IsValid = false }; var tokens = helper.TokenizeWebSiteOwnerName(websiteOwnerName); - if (!tokens.HasValue) return new AzureFunctionsMetaData { IsValid = false }; + if (!tokens.HasValue) + return new AzureFunctionsMetaData { IsValid = false }; if (string.IsNullOrEmpty(regionName)) regionName = tokens.Value.Region; diff --git a/src/Elastic.Apm/Cloud/CloudMetadataProviderCollection.cs b/src/Elastic.Apm/Cloud/CloudMetadataProviderCollection.cs index 11431e6d7..927ad3f25 100644 --- a/src/Elastic.Apm/Cloud/CloudMetadataProviderCollection.cs +++ b/src/Elastic.Apm/Cloud/CloudMetadataProviderCollection.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.ObjectModel; using System.Threading.Tasks; @@ -12,7 +12,7 @@ using static Elastic.Apm.Config.ConfigConsts; namespace Elastic.Apm.Cloud -{ +{ /// /// A collection of that provide metadata for cloud platforms /// @@ -27,18 +27,18 @@ public CloudMetadataProviderCollection(string cloudProvider, IApmLogger logger) internal CloudMetadataProviderCollection(string cloudProvider, IApmLogger logger, IEnvironmentVariables environmentVariables) { - environmentVariables ??= new EnvironmentVariables(logger); - // - // First check, whether we are in a specific habitat (e.g. Azure Functions). - // + environmentVariables ??= new EnvironmentVariables(logger); + // + // First check, whether we are in a specific habitat (e.g. Azure Functions). + // if (AgentFeaturesProvider.Get(logger).Check(AgentFeature.AzureFunctionsCloudMetaDataDiscovery)) { Add(new AzureFunctionsMetadataProvider(logger, environmentVariables.GetEnvironmentVariables())); return; - } - // - // Now, let's look at the (generic) configuration. - // + } + // + // Now, let's look at the (generic) configuration. + // switch (cloudProvider?.ToLowerInvariant()) { case SupportedValues.CloudProviderAws: @@ -47,34 +47,34 @@ internal CloudMetadataProviderCollection(string cloudProvider, IApmLogger logger case SupportedValues.CloudProviderGcp: Add(new GcpCloudMetadataProvider(logger)); break; - case SupportedValues.CloudProviderAzure: - { - Add(new AzureCloudMetadataProvider(logger)); - var environment = environmentVariables.GetEnvironmentVariables(); - Add(new AzureAppServiceMetadataProvider(logger, environment)); - Add(new AzureFunctionsMetadataProvider(logger, environment)); - break; - } + case SupportedValues.CloudProviderAzure: + { + Add(new AzureCloudMetadataProvider(logger)); + var environment = environmentVariables.GetEnvironmentVariables(); + Add(new AzureAppServiceMetadataProvider(logger, environment)); + Add(new AzureFunctionsMetadataProvider(logger, environment)); + break; + } case SupportedValues.CloudProviderNone: break; case SupportedValues.CloudProviderAuto: case "": - case null: - { - // keyed collection is ordered - Add(new AwsCloudMetadataProvider(logger)); - Add(new GcpCloudMetadataProvider(logger)); - Add(new AzureCloudMetadataProvider(logger)); - var environment = environmentVariables.GetEnvironmentVariables(); - Add(new AzureAppServiceMetadataProvider(logger, environment)); - Add(new AzureFunctionsMetadataProvider(logger, environment)); - break; - } + case null: + { + // keyed collection is ordered + Add(new AwsCloudMetadataProvider(logger)); + Add(new GcpCloudMetadataProvider(logger)); + Add(new AzureCloudMetadataProvider(logger)); + var environment = environmentVariables.GetEnvironmentVariables(); + Add(new AzureAppServiceMetadataProvider(logger, environment)); + Add(new AzureFunctionsMetadataProvider(logger, environment)); + break; + } default: throw new ArgumentException($"Unknown cloud provider {cloudProvider}", nameof(cloudProvider)); } - } - + } + /// /// Retrieves the cloud metadata for the given provider(s) /// diff --git a/src/Elastic.Apm/Cloud/EnvironmentBasedAzureMetadataHelper.cs b/src/Elastic.Apm/Cloud/EnvironmentBasedAzureMetadataHelper.cs index 041293cba..64c05d45a 100644 --- a/src/Elastic.Apm/Cloud/EnvironmentBasedAzureMetadataHelper.cs +++ b/src/Elastic.Apm/Cloud/EnvironmentBasedAzureMetadataHelper.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections; using Elastic.Apm.Helpers; @@ -11,7 +11,7 @@ namespace Elastic.Apm.Cloud { internal static class AzureEnvironmentVariables - { + { /// /// Value of the form {subscription id}+{app service plan resource group}-{region}webspace /// @@ -26,8 +26,8 @@ internal static class AzureEnvironmentVariables internal const string RegionName = "REGION_NAME"; internal const string FunctionsExtensionVersion = "FUNCTIONS_EXTENSION_VERSION"; internal const string FunctionsWorkerRuntime = "FUNCTIONS_WORKER_RUNTIME"; - } - + } + /// /// Helper type for Azure metadata providers that operate on environment variables. /// @@ -49,7 +49,8 @@ internal EnvironmentBasedAzureMetadataHelper(string name, IApmLogger logger, IDi internal bool NullOrEmptyVariable(string key, string value) { - if (!string.IsNullOrEmpty(value)) return false; + if (!string.IsNullOrEmpty(value)) + return false; _logger.Trace()?.Log( $"Unable to get '{_name}' cloud metadata as no '{key}' environment variable exists. The application is likely not running in '{_name}'"); diff --git a/src/Elastic.Apm/Cloud/GcpCloudMetadataProvider.cs b/src/Elastic.Apm/Cloud/GcpCloudMetadataProvider.cs index d33e28941..beb9532d7 100644 --- a/src/Elastic.Apm/Cloud/GcpCloudMetadataProvider.cs +++ b/src/Elastic.Apm/Cloud/GcpCloudMetadataProvider.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Globalization; using System.IO; @@ -10,12 +10,12 @@ using System.Text; using System.Threading.Tasks; using Elastic.Apm.Api; -using Elastic.Apm.Logging; using Elastic.Apm.Libraries.Newtonsoft.Json; using Elastic.Apm.Libraries.Newtonsoft.Json.Linq; +using Elastic.Apm.Logging; namespace Elastic.Apm.Cloud -{ +{ /// /// Provides cloud metadata for Google Cloud Platform (GCP) /// @@ -35,11 +35,11 @@ internal GcpCloudMetadataProvider(IApmLogger logger, HttpMessageHandler handler) public GcpCloudMetadataProvider(IApmLogger logger) : this(logger, new HttpClientHandler()) { - } - + } + /// - public string Provider { get; } = Name; - + public string Provider { get; } = Name; + /// public async Task GetMetadataAsync() { diff --git a/src/Elastic.Apm/Cloud/ICloudMetadataProvider.cs b/src/Elastic.Apm/Cloud/ICloudMetadataProvider.cs index 376d87d14..fefe69d9d 100644 --- a/src/Elastic.Apm/Cloud/ICloudMetadataProvider.cs +++ b/src/Elastic.Apm/Cloud/ICloudMetadataProvider.cs @@ -1,22 +1,22 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; namespace Elastic.Apm.Cloud -{ +{ /// /// Provides metadata for a cloud provider /// public interface ICloudMetadataProvider - { + { /// /// The name of the cloud provider /// - string Provider { get; } - + string Provider { get; } + /// /// Retrieves the cloud metadata for the provider /// diff --git a/src/Elastic.Apm/Config/AbstractConfigurationReader.cs b/src/Elastic.Apm/Config/AbstractConfigurationReader.cs index f9bf83f29..959eb9972 100644 --- a/src/Elastic.Apm/Config/AbstractConfigurationReader.cs +++ b/src/Elastic.Apm/Config/AbstractConfigurationReader.cs @@ -25,7 +25,8 @@ public abstract class AbstractConfigurationReader private readonly ConfigurationDefaults _defaults; protected AbstractConfigurationReader(IApmLogger logger, string dbgDerivedClassName) : this(logger, - new ConfigurationDefaults { DebugName = dbgDerivedClassName }) { } + new ConfigurationDefaults { DebugName = dbgDerivedClassName }) + { } internal AbstractConfigurationReader(IApmLogger logger, ConfigurationDefaults defaults) { @@ -39,10 +40,12 @@ internal AbstractConfigurationReader(IApmLogger logger, ConfigurationDefaults de protected internal static bool TryParseLogLevel(string value, out LogLevel level) { level = default; - if (string.IsNullOrEmpty(value)) return false; + if (string.IsNullOrEmpty(value)) + return false; var retLevel = DefaultLogLevel(); - if (!retLevel.HasValue) return false; + if (!retLevel.HasValue) + return false; level = retLevel.Value; return true; @@ -51,24 +54,32 @@ protected internal static bool TryParseLogLevel(string value, out LogLevel level { switch (value.ToLowerInvariant()) { - case "trace": return LogLevel.Trace; - case "debug": return LogLevel.Debug; + case "trace": + return LogLevel.Trace; + case "debug": + return LogLevel.Debug; case "information": - case "info": return LogLevel.Information; - case "warning": return LogLevel.Warning; - case "error": return LogLevel.Error; - case "critical": return LogLevel.Critical; + case "info": + return LogLevel.Information; + case "warning": + return LogLevel.Warning; + case "error": + return LogLevel.Error; + case "critical": + return LogLevel.Critical; case "off": case "none": return LogLevel.None; - default: return null; + default: + return null; } } } protected IReadOnlyList ParseSanitizeFieldNames(ConfigurationKeyValue kv) { - if (kv?.Value == null) return DefaultValues.SanitizeFieldNames; + if (kv?.Value == null) + return DefaultValues.SanitizeFieldNames; try { @@ -76,7 +87,8 @@ protected IReadOnlyList ParseSanitizeFieldNames(ConfigurationKe var sanitizeFieldNames = kv.Value.Split(',').Where(n => !string.IsNullOrEmpty(n)).ToList(); var retVal = new List(sanitizeFieldNames.Count); - foreach (var item in sanitizeFieldNames) retVal.Add(WildcardMatcher.ValueOf(item.Trim())); + foreach (var item in sanitizeFieldNames) + retVal.Add(WildcardMatcher.ValueOf(item.Trim())); return retVal; } catch (Exception e) @@ -88,7 +100,8 @@ protected IReadOnlyList ParseSanitizeFieldNames(ConfigurationKe protected IReadOnlyList ParseDisableMetrics(ConfigurationKeyValue kv) { - if (kv?.Value == null) return DefaultValues.DisableMetrics; + if (kv?.Value == null) + return DefaultValues.DisableMetrics; try { @@ -96,7 +109,8 @@ protected IReadOnlyList ParseDisableMetrics(ConfigurationKeyVal var disableMetrics = kv.Value.Split(',').Where(n => !string.IsNullOrEmpty(n)).ToList(); var retVal = new List(disableMetrics.Count); - foreach (var item in disableMetrics) retVal.Add(WildcardMatcher.ValueOf(item.Trim())); + foreach (var item in disableMetrics) + retVal.Add(WildcardMatcher.ValueOf(item.Trim())); return retVal; } catch (Exception e) @@ -151,7 +165,8 @@ protected IReadOnlyList ParseIgnoreMessageQueues(ConfigurationK var ignoreMessageQueues = kv.Value.Split(',').Where(n => !string.IsNullOrWhiteSpace(n)).ToList(); var retVal = new List(ignoreMessageQueues.Count); - foreach (var item in ignoreMessageQueues) retVal.Add(WildcardMatcher.ValueOf(item.Trim())); + foreach (var item in ignoreMessageQueues) + retVal.Add(WildcardMatcher.ValueOf(item.Trim())); return retVal; } catch (Exception e) @@ -163,28 +178,32 @@ protected IReadOnlyList ParseIgnoreMessageQueues(ConfigurationK protected string ParseSecretToken(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return null; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return null; return kv.Value; } protected string ParseServerCert(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return null; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return null; return kv.Value; } protected string ParseApiKey(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return null; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return null; return kv.Value; } protected bool ParseEnabled(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return true; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return true; if (bool.TryParse(kv.Value, out var isEnabledParsed)) return isEnabledParsed; @@ -195,7 +214,8 @@ protected bool ParseEnabled(ConfigurationKeyValue kv) protected bool ParseOpenTelemetryBridgeEnabled(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return DefaultValues.OpenTelemetryBridgeEnabled; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return DefaultValues.OpenTelemetryBridgeEnabled; if (bool.TryParse(kv.Value, out var isOTelEnabled)) return isOTelEnabled; @@ -209,7 +229,8 @@ protected bool ParseOpenTelemetryBridgeEnabled(ConfigurationKeyValue kv) protected bool ParseRecording(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return true; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return true; if (bool.TryParse(kv.Value, out var isRecording)) return isRecording; @@ -241,7 +262,8 @@ protected string ParseTraceContinuationStrategy(ConfigurationKeyValue kv) protected bool ParseTraceContextIgnoreSampledFalse(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return DefaultValues.TraceContextIgnoreSampledFalse; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return DefaultValues.TraceContextIgnoreSampledFalse; // ReSharper disable once SimplifyConditionalTernaryExpression return bool.TryParse(kv.Value, out var value) ? value : DefaultValues.TraceContextIgnoreSampledFalse; @@ -252,7 +274,8 @@ protected bool ParseTraceContextIgnoreSampledFalse(ConfigurationKeyValue kv) protected bool ParseVerifyServerCert(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return DefaultValues.VerifyServerCert; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return DefaultValues.VerifyServerCert; // ReSharper disable once SimplifyConditionalTernaryExpression return bool.TryParse(kv.Value, out var value) ? value : DefaultValues.VerifyServerCert; @@ -262,7 +285,8 @@ protected bool ParseVerifyServerCert(ConfigurationKeyValue kv) protected LogLevel ParseLogLevel(ConfigurationKeyValue kv) { - if (TryParseLogLevel(kv?.Value, out var level)) return level; + if (TryParseLogLevel(kv?.Value, out var level)) + return level; if (kv?.Value == null) _logger?.Debug()?.Log("No log level provided. Defaulting to log level '{DefaultLogLevel}'", DefaultValues.LogLevel); @@ -416,7 +440,8 @@ protected int ParseStackTraceLimit(ConfigurationKeyValue kv) protected IReadOnlyList ParseTransactionIgnoreUrls(ConfigurationKeyValue kv) { - if (kv?.Value == null) return DefaultValues.TransactionIgnoreUrls; + if (kv?.Value == null) + return DefaultValues.TransactionIgnoreUrls; try { @@ -424,7 +449,8 @@ protected IReadOnlyList ParseTransactionIgnoreUrls(Configuratio var transactionIgnoreUrls = kv.Value.Split(',').Where(n => !string.IsNullOrEmpty(n)).ToList(); var retVal = new List(transactionIgnoreUrls.Count); - foreach (var item in transactionIgnoreUrls) retVal.Add(WildcardMatcher.ValueOf(item.Trim())); + foreach (var item in transactionIgnoreUrls) + retVal.Add(WildcardMatcher.ValueOf(item.Trim())); return retVal; } catch (Exception e) @@ -437,7 +463,8 @@ protected IReadOnlyList ParseTransactionIgnoreUrls(Configuratio protected bool ParseSpanCompressionEnabled(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return DefaultValues.SpanCompressionEnabled; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return DefaultValues.SpanCompressionEnabled; if (bool.TryParse(kv.Value, out var isSpanCompressionEnable)) return isSpanCompressionEnable; @@ -750,15 +777,18 @@ private static AssemblyName DiscoverEntryAssemblyName() internal static string DiscoverDefaultServiceName() { var entryAssemblyName = DiscoverEntryAssemblyName(); - if (entryAssemblyName != null) return entryAssemblyName.Name; + if (entryAssemblyName != null) + return entryAssemblyName.Name; var stackFrames = new StackTrace().GetFrames(); - if (stackFrames == null) return null; + if (stackFrames == null) + return null; foreach (var frame in stackFrames) { var currentAssemblyName = frame?.GetMethod()?.DeclaringType?.Assembly.GetName(); - if (currentAssemblyName != null && !IsMsOrElastic(currentAssemblyName.GetPublicKeyToken())) return currentAssemblyName.Name; + if (currentAssemblyName != null && !IsMsOrElastic(currentAssemblyName.GetPublicKeyToken())) + return currentAssemblyName.Name; } return null; @@ -817,7 +847,8 @@ protected string ParseServiceVersion(ConfigurationKeyValue kv) { var versionInConfig = kv.Value; - if (!string.IsNullOrEmpty(versionInConfig)) return versionInConfig; + if (!string.IsNullOrEmpty(versionInConfig)) + return versionInConfig; _logger?.Info()?.Log("The agent was started without a service version. The service version will be automatically discovered."); @@ -837,14 +868,16 @@ protected string ParseServiceVersion(ConfigurationKeyValue kv) protected string ParseEnvironment(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return null; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return null; return kv.Value; } protected string ParseServiceNodeName(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrWhiteSpace(kv.Value)) return null; + if (kv == null || string.IsNullOrWhiteSpace(kv.Value)) + return null; return kv.Value; } @@ -986,7 +1019,8 @@ protected List ParseCaptureBodyContentTypes(ConfigurationKeyValue kv) { var valueToParse = kv.Value; - if (string.IsNullOrEmpty(valueToParse)) valueToParse = DefaultValues.CaptureBodyContentTypes; + if (string.IsNullOrEmpty(valueToParse)) + valueToParse = DefaultValues.CaptureBodyContentTypes; return valueToParse.Split(',').Select(p => p.Trim()).ToList(); } @@ -1041,7 +1075,8 @@ private bool ParseBoolOption(ConfigurationKeyValue kv, bool defaultValue, string protected string ParseHostName(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return null; + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return null; return kv.Value; } @@ -1100,7 +1135,8 @@ protected string ParseHostName(ConfigurationKeyValue kv) internal static string ToLogString(IReadOnlyDictionary stringToStringMap) { - if (stringToStringMap == null) return ObjectExtensions.NullAsString; + if (stringToStringMap == null) + return ObjectExtensions.NullAsString; // [count: 3]: [0]: `key0': `value0', [1]: `key1': `value1', [2]: `key2': `value2' var result = new StringBuilder(); @@ -1119,7 +1155,8 @@ internal static string ToLogString(IReadOnlyDictionary stringToS protected IReadOnlyList ParseExcludedNamespaces(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return LogAndReturnDefault().AsReadOnly(); + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return LogAndReturnDefault().AsReadOnly(); var list = kv.Value.Split(',').ToList(); @@ -1134,7 +1171,8 @@ List LogAndReturnDefault() protected IReadOnlyList ParseApplicationNamespaces(ConfigurationKeyValue kv) { - if (kv == null || string.IsNullOrEmpty(kv.Value)) return LogAndReturnDefault().AsReadOnly(); + if (kv == null || string.IsNullOrEmpty(kv.Value)) + return LogAndReturnDefault().AsReadOnly(); var list = kv.Value.Split(',').ToList(); @@ -1151,7 +1189,8 @@ private static bool TryParseUri(string u, out Uri uri) { // https://stackoverflow.com/a/33573337 uri = null; - if (!Uri.TryCreate(u, UriKind.Absolute, out uri)) return false; + if (!Uri.TryCreate(u, UriKind.Absolute, out uri)) + return false; return uri.IsWellFormedOriginalString() && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps); } diff --git a/src/Elastic.Apm/Config/ConfigurationKeyValue.cs b/src/Elastic.Apm/Config/ConfigurationKeyValue.cs index 924320975..70d440f0f 100644 --- a/src/Elastic.Apm/Config/ConfigurationKeyValue.cs +++ b/src/Elastic.Apm/Config/ConfigurationKeyValue.cs @@ -33,7 +33,8 @@ private string ValueForLogging { get { - if (string.IsNullOrWhiteSpace(Value)) return Consts.NotProvided; + if (string.IsNullOrWhiteSpace(Value)) + return Consts.NotProvided; string UrlString(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) ? uri.Sanitize().ToString() : value; diff --git a/src/Elastic.Apm/Config/ConfigurationLogger.cs b/src/Elastic.Apm/Config/ConfigurationLogger.cs index 084c37803..8699c79e8 100644 --- a/src/Elastic.Apm/Config/ConfigurationLogger.cs +++ b/src/Elastic.Apm/Config/ConfigurationLogger.cs @@ -42,10 +42,10 @@ internal static class ConfigurationLogger internal static DefaultKeyValue GetDefaultValueForLogging(ConfigurationOption option, IConfigurationReader config) => option switch { - ServerUrl => new (option, config.ServerUrl.AbsoluteUri, nameof(GetDefaultValueForLogging)), - ServiceName => new (option, config.ServiceName, nameof(GetDefaultValueForLogging)), - ServiceVersion => new (option, config.ServiceVersion, nameof(GetDefaultValueForLogging)), - ConfigurationOption.LogLevel => new (option, config.LogLevel.ToString(), nameof(GetDefaultValueForLogging)), + ServerUrl => new(option, config.ServerUrl.AbsoluteUri, nameof(GetDefaultValueForLogging)), + ServiceName => new(option, config.ServiceName, nameof(GetDefaultValueForLogging)), + ServiceVersion => new(option, config.ServiceVersion, nameof(GetDefaultValueForLogging)), + ConfigurationOption.LogLevel => new(option, config.LogLevel.ToString(), nameof(GetDefaultValueForLogging)), _ => null, }; @@ -57,7 +57,8 @@ option switch public static void PrintAgentLogPreamble(IApmLogger logger, IConfigurationReader configurationReader) { - if (logger?.Info() == null) return; + if (logger?.Info() == null) + return; try { @@ -83,7 +84,8 @@ public static void PrintAgentLogPreamble(IApmLogger logger, IConfigurationReader public static void PrintAgentConfiguration(IApmLogger logger, IConfigurationReader configurationReader) { - if (logger?.Info() == null) return; + if (logger?.Info() == null) + return; try { var info = logger.Info()!.Value; diff --git a/src/Elastic.Apm/Config/EnvironmentConfiguration.cs b/src/Elastic.Apm/Config/EnvironmentConfiguration.cs index 22962a50c..3c85447d9 100644 --- a/src/Elastic.Apm/Config/EnvironmentConfiguration.cs +++ b/src/Elastic.Apm/Config/EnvironmentConfiguration.cs @@ -17,9 +17,9 @@ internal class NullConfigurationKeyValueProvider : IConfigurationKeyValueProvide internal class EnvironmentConfiguration : FallbackToEnvironmentConfigurationBase, IConfiguration { - private static readonly ConfigurationDefaults ConfigurationDefaults = new () { DebugName = nameof(EnvironmentConfiguration) }; + private static readonly ConfigurationDefaults ConfigurationDefaults = new() { DebugName = nameof(EnvironmentConfiguration) }; // We force base.KeyValueProvider to always return null so the base class always falls back to environment variables - private static readonly NullConfigurationKeyValueProvider NullProvider = new (); + private static readonly NullConfigurationKeyValueProvider NullProvider = new(); public EnvironmentConfiguration(IApmLogger logger = null) : base(logger, ConfigurationDefaults, NullProvider) { } } diff --git a/src/Elastic.Apm/Config/ProfilerLogConfig.cs b/src/Elastic.Apm/Config/ProfilerLogConfig.cs index c2d371f43..5af70ca99 100644 --- a/src/Elastic.Apm/Config/ProfilerLogConfig.cs +++ b/src/Elastic.Apm/Config/ProfilerLogConfig.cs @@ -50,7 +50,7 @@ string GetSafeEnvironmentVariable(string key) var logLevel = v.ToLowerInvariant() switch { "trace" => LogLevel.Trace, - "debug" =>LogLevel.Debug, + "debug" => LogLevel.Debug, "info" => LogLevel.Information, "warn" => LogLevel.Warning, "error" => LogLevel.Error, diff --git a/src/Elastic.Apm/Consts.cs b/src/Elastic.Apm/Consts.cs index b50a116a3..0fb126506 100644 --- a/src/Elastic.Apm/Consts.cs +++ b/src/Elastic.Apm/Consts.cs @@ -1,7 +1,7 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + namespace Elastic.Apm { internal static class Consts diff --git a/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListener.cs b/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListener.cs index f9a94223b..bf99dbfe3 100644 --- a/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListener.cs +++ b/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListener.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListenerCoreImpl.cs b/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListenerCoreImpl.cs index 838e5de52..6f6d7aee6 100644 --- a/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListenerCoreImpl.cs +++ b/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListenerCoreImpl.cs @@ -36,7 +36,7 @@ protected override bool RequestTryGetHeader(HttpRequestMessage request, string h protected override void RequestHeadersAdd(HttpRequestMessage request, string headerName, string headerValue) { - if(!string.IsNullOrEmpty(headerValue)) + if (!string.IsNullOrEmpty(headerValue)) request.Headers.Add(headerName, headerValue); } diff --git a/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListenerFullFrameworkImpl.cs b/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListenerFullFrameworkImpl.cs index fc5a0c5ef..c855632ed 100644 --- a/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListenerFullFrameworkImpl.cs +++ b/src/Elastic.Apm/DiagnosticListeners/HttpDiagnosticListenerFullFrameworkImpl.cs @@ -29,7 +29,7 @@ public HttpDiagnosticListenerFullFrameworkImpl(IApmAgent agent) protected override void RequestHeadersAdd(HttpWebRequest request, string headerName, string headerValue) { - if(!string.IsNullOrEmpty(headerValue)) + if (!string.IsNullOrEmpty(headerValue)) request.Headers.Add(headerName, headerValue); } diff --git a/src/Elastic.Apm/DiagnosticListeners/HttpTraceConfiguration.cs b/src/Elastic.Apm/DiagnosticListeners/HttpTraceConfiguration.cs index 0a3b1d597..f15096ecc 100644 --- a/src/Elastic.Apm/DiagnosticListeners/HttpTraceConfiguration.cs +++ b/src/Elastic.Apm/DiagnosticListeners/HttpTraceConfiguration.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections; using System.Collections.Generic; @@ -15,8 +15,8 @@ internal class HttpTraceConfiguration private readonly ReaderWriterLockSlim _tracersLock = new ReaderWriterLockSlim(); private readonly List _tracers = new List(); private volatile bool _captureSpan; - private volatile bool _subscribed; - + private volatile bool _subscribed; + /// /// Whether a Http diagnostic listener has subscribed to HTTP requests. /// @@ -24,8 +24,8 @@ public bool Subscribed { get => _subscribed; set => _subscribed = value; - } - + } + /// /// Whether a HTTP span should be captured. /// A HTTP diagnostic listener is used to listen for all HTTP requests, but it may be started @@ -36,14 +36,14 @@ public bool CaptureSpan { get => _captureSpan; set => _captureSpan = value; - } - + } + /// /// Determines if there are any HTTP span tracers registered. /// Avoids allocating a if there are none to enumerate /// - public bool HasTracers => _tracers.Count > 0; - + public bool HasTracers => _tracers.Count > 0; + /// /// Gets the HTTP span tracers, entering a read lock that is exited when the /// is disposed. @@ -53,8 +53,8 @@ public HttpTracers GetTracers() { _tracersLock.EnterReadLock(); return new HttpTracers(_tracers, _tracersLock); - } - + } + /// /// Adds a http span tracer to the collection, within a write lock /// @@ -70,8 +70,8 @@ public void AddTracer(IHttpSpanTracer tracer) { _tracersLock.ExitWriteLock(); } - } - + } + /// /// A collection of http tracers to enumerate /// diff --git a/src/Elastic.Apm/DiagnosticListeners/IHttpSpanTracer.cs b/src/Elastic.Apm/DiagnosticListeners/IHttpSpanTracer.cs index 540b9a620..a93bdec0d 100644 --- a/src/Elastic.Apm/DiagnosticListeners/IHttpSpanTracer.cs +++ b/src/Elastic.Apm/DiagnosticListeners/IHttpSpanTracer.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using Elastic.Apm.Api; namespace Elastic.Apm.DiagnosticListeners -{ +{ /// /// Utility interface for the generic HTTP request capturing mechanism. /// For specific HTTP calls, it can handle the creation of the span and it /// can also completely suppress span creation. /// internal interface IHttpSpanTracer - { + { /// /// Determines if a HTTP request is a match for this tracer. This should be /// a quick check @@ -23,8 +23,8 @@ internal interface IHttpSpanTracer /// the HTTP request url /// A delegate to retrieve a HTTP header /// true if the request is match, false otherwise - bool IsMatch(string method, Uri requestUrl, Func headerGetter); - + bool IsMatch(string method, Uri requestUrl, Func headerGetter); + /// /// Starts a new span /// @@ -33,8 +33,8 @@ internal interface IHttpSpanTracer /// the HTTP request url /// A delegate to retrieve a HTTP header /// A new instance of a . Can return null - ISpan StartSpan(IApmAgent agent, string method, Uri requestUrl, Func headerGetter); - + ISpan StartSpan(IApmAgent agent, string method, Uri requestUrl, Func headerGetter); + /// /// Determines if a span should be captured for the given HTTP all. /// diff --git a/src/Elastic.Apm/DiagnosticListeners/KnownListners.cs b/src/Elastic.Apm/DiagnosticListeners/KnownListners.cs index 024fa8900..69126a476 100644 --- a/src/Elastic.Apm/DiagnosticListeners/KnownListners.cs +++ b/src/Elastic.Apm/DiagnosticListeners/KnownListners.cs @@ -17,7 +17,9 @@ internal static class KnownListeners public static HashSet KnownListenersList => new() { - MicrosoftAspNetCoreHostingHttpRequestIn, SystemNetHttpHttpRequestOut, SystemNetHttpDesktopHttpRequestOut, + MicrosoftAspNetCoreHostingHttpRequestIn, + SystemNetHttpHttpRequestOut, + SystemNetHttpDesktopHttpRequestOut, ApmTransactionActivityName }; } diff --git a/src/Elastic.Apm/DiagnosticSource/DiagnosticInitializer.cs b/src/Elastic.Apm/DiagnosticSource/DiagnosticInitializer.cs index 123e207a7..af64858ea 100644 --- a/src/Elastic.Apm/DiagnosticSource/DiagnosticInitializer.cs +++ b/src/Elastic.Apm/DiagnosticSource/DiagnosticInitializer.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/DiagnosticSource/IDiagnosticListener.cs b/src/Elastic.Apm/DiagnosticSource/IDiagnosticListener.cs index 2e0349861..9f65a1163 100644 --- a/src/Elastic.Apm/DiagnosticSource/IDiagnosticListener.cs +++ b/src/Elastic.Apm/DiagnosticSource/IDiagnosticListener.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/DistributedTracing/TraceContext.cs b/src/Elastic.Apm/DistributedTracing/TraceContext.cs index 404be44f1..7cfe4106f 100644 --- a/src/Elastic.Apm/DistributedTracing/TraceContext.cs +++ b/src/Elastic.Apm/DistributedTracing/TraceContext.cs @@ -41,11 +41,13 @@ internal static DistributedTracingData TryExtractTracingData(string traceParentV { var bestAttempt = false; - if (string.IsNullOrWhiteSpace(traceParentValue)) return null; + if (string.IsNullOrWhiteSpace(traceParentValue)) + return null; traceParentValue = traceParentValue.Trim(); - if (traceParentValue.Length < VersionPrefixIdLength || traceParentValue[VersionPrefixIdLength - 1] != '-') return null; + if (traceParentValue.Length < VersionPrefixIdLength || traceParentValue[VersionPrefixIdLength - 1] != '-') + return null; try { @@ -63,7 +65,8 @@ internal static DistributedTracingData TryExtractTracingData(string traceParentV return null; } - if (traceParentValue.Length < VersionAndTraceIdLength || traceParentValue[VersionAndTraceIdLength - 1] != '-') return null; + if (traceParentValue.Length < VersionAndTraceIdLength || traceParentValue[VersionAndTraceIdLength - 1] != '-') + return null; string traceId; try @@ -83,7 +86,8 @@ internal static DistributedTracingData TryExtractTracingData(string traceParentV } if (traceParentValue.Length < VersionAndTraceIdAndSpanIdLength - || traceParentValue[VersionAndTraceIdAndSpanIdLength - 1] != '-') return null; + || traceParentValue[VersionAndTraceIdAndSpanIdLength - 1] != '-') + return null; string parentId; try @@ -100,7 +104,8 @@ internal static DistributedTracingData TryExtractTracingData(string traceParentV return null; } - if (traceParentValue.Length < VersionAndTraceIdAndSpanIdLength + OptionsLength) return null; + if (traceParentValue.Length < VersionAndTraceIdAndSpanIdLength + OptionsLength) + return null; byte traceFlags; try @@ -112,7 +117,8 @@ internal static DistributedTracingData TryExtractTracingData(string traceParentV return null; } - if (!bestAttempt && traceParentValue.Length != VersionAndTraceIdAndSpanIdLength + OptionsLength) return null; + if (!bestAttempt && traceParentValue.Length != VersionAndTraceIdAndSpanIdLength + OptionsLength) + return null; // ReSharper disable once InvertIf - imo that would make it hard to read. if (bestAttempt) @@ -181,11 +187,14 @@ private static byte HexStringTwoCharToByte(string src, int start = 0) int HexCharToInt(char c) { - if (c >= '0' && c <= '9') return c - '0'; + if (c >= '0' && c <= '9') + return c - '0'; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; - if (c >= 'A' && c <= 'F') return c - 'A' + 10; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; throw new ArgumentOutOfRangeException("Invalid character: " + c); } diff --git a/src/Elastic.Apm/DistributedTracing/TraceState.cs b/src/Elastic.Apm/DistributedTracing/TraceState.cs index 6f5272453..89559145f 100644 --- a/src/Elastic.Apm/DistributedTracing/TraceState.cs +++ b/src/Elastic.Apm/DistributedTracing/TraceState.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; -using System.Globalization; +using System.Globalization; #if NETSTANDARD2_0 || NETFRAMEWORK -using System.Linq; +using System.Linq; #endif using System.Text; using System.Threading; namespace Elastic.Apm.DistributedTracing -{ +{ /// /// Handles tracestate /// @@ -51,8 +51,8 @@ public TraceState() { _tracestate = new List(); _sizeLimit = DefaultSizeLimit; - } - + } + /// /// Sets the sample rate. If a sample rate has already been set, the existing sample rate is removed /// and the new sample rate appended to the front of tracestate. @@ -88,29 +88,29 @@ private string MutateTracestate(double sampleRate) c = headerValue[end++]; if (end < headerValue.Length) - end--; - - // Get the elastic vendor from the header value - var elasticVendor = headerValue.Substring(start, end - start); - - // if the character before the vendor is a separator, remove it + end--; + + // Get the elastic vendor from the header value + var elasticVendor = headerValue.Substring(start, end - start); + + // if the character before the vendor is a separator, remove it if (start > 0 && headerValue[start - 1] == VendorSeparator) - start--; - - // if the character after the vendor is a separator, remove it + start--; + + // if the character after the vendor is a separator, remove it if (start == 0 && end < headerValue.Length && headerValue[end] == VendorSeparator) - end++; - - // Remove the elastic vendor from the header value - headerValue = headerValue.Remove(start, end - start); - - // if the header is now an empty string, simply remove it + end++; + + // Remove the elastic vendor from the header value + headerValue = headerValue.Remove(start, end - start); + + // if the header is now an empty string, simply remove it if (headerValue == string.Empty) _tracestate.RemoveAt(_headerIndex); else - _tracestate[_headerIndex] = headerValue; - - // now replace the sample rate in the elastic vendor + _tracestate[_headerIndex] = headerValue; + + // now replace the sample rate in the elastic vendor var sampleRateIndex = elasticVendor.IndexOf(SampleRatePrefix, StringComparison.Ordinal); if (sampleRateIndex > -1) { @@ -136,8 +136,8 @@ private string MutateTracestate(double sampleRate) } return GetHeaderValue(sampleRate); - } - + } + /// /// Adds a text header to tracestate /// @@ -163,8 +163,8 @@ public void AddTextHeader(string headerValue) c = headerValue[valueEnd++]; if (valueEnd < headerValue.Length) - { - // end due to separator char that needs to be trimmed + { + // end due to separator char that needs to be trimmed valueEnd--; } } @@ -173,12 +173,12 @@ public void AddTextHeader(string headerValue) out var value)) { if (value >= 0 && value <= 1) - { - // ensure proper rounding of sample rate to minimize storage - // even if configuration should not allow this, any upstream value might require rounding - var rounded = Sampler.RoundToPrecision(value); - - // ReSharper disable once CompareOfFloatsByEqualityOperator + { + // ensure proper rounding of sample rate to minimize storage + // even if configuration should not allow this, any upstream value might require rounding + var rounded = Sampler.RoundToPrecision(value); + + // ReSharper disable once CompareOfFloatsByEqualityOperator if (rounded != value) { if (_rewriteBuffer is null) @@ -201,8 +201,8 @@ public void AddTextHeader(string headerValue) if (esVendorPresent) _headerIndex = _tracestate.Count - 1; - } - + } + /// /// Validates the tracestate value /// @@ -216,13 +216,14 @@ public static string ValidateTracestate(string traceState) var listMembers = traceState.Split(VendorSeparator); var set = new HashSet(); - if (listMembers.Length == 0 || listMembers.Length > 32) return null; + if (listMembers.Length == 0 || listMembers.Length > 32) + return null; var sb = new StringBuilder(); foreach (var listMember in listMembers) - { - // TODO: Span-ify + { + // TODO: Span-ify var item = listMember.Split('='); if (item.Length > 2) return null; @@ -247,7 +248,8 @@ public static string ValidateTracestate(string traceState) if (vendorFormatKey[1].Length == 0 || string.IsNullOrEmpty(vendorFormatKey[1]) || vendorFormatKey[1].Length > 14) return null; - if (!IsValidKey(vendorFormatKey[0]) || !IsValidKey(vendorFormatKey[1])) return null; + if (!IsValidKey(vendorFormatKey[0]) || !IsValidKey(vendorFormatKey[1])) + return null; } else { @@ -269,16 +271,17 @@ public static string ValidateTracestate(string traceState) } private static bool IsValidKey(string str) - { - // ReSharper disable once LoopCanBeConvertedToQuery + { + // ReSharper disable once LoopCanBeConvertedToQuery for (var i = 0; i < str.Length; i++) { var c = str[i]; - var isOk = c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c == '_' || c == '-' || c == '*' || c == '/' || c == '\t' - //OWS rule: if we hit a ' ', then it must be next to a '\t' + var isOk = c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c == '_' || c == '-' || c == '*' || c == '/' || c == '\t' + //OWS rule: if we hit a ' ', then it must be next to a '\t' || c == ' ' && (i > 0 && str[i - 1] == '\t' || i < str.Length - 2 && str[i + 1] == '\t'); - if (!isOk) return false; + if (!isOk) + return false; } return true; @@ -286,37 +289,39 @@ private static bool IsValidKey(string str) private static bool IsValidValue(string str) { - if (string.IsNullOrEmpty(str)) return false; - - // ReSharper disable once LoopCanBeConvertedToQuery + if (string.IsNullOrEmpty(str)) + return false; + + // ReSharper disable once LoopCanBeConvertedToQuery for (var i = 0; i < str.Length; i++) { var c = str[i]; - var isOk = c >= 0x20 && c <= 0x7E || c == '\t' && c != ',' && c != '=' - //OWS rule: if we hit a ' ', then it must be next to a '\t' + var isOk = c >= 0x20 && c <= 0x7E || c == '\t' && c != ',' && c != '=' + //OWS rule: if we hit a ' ', then it must be next to a '\t' || c == ' ' && (i > 0 && str[i - 1] == '\t' || i < str.Length - 2 && str[i + 1] == '\t'); - if (!isOk) return false; + if (!isOk) + return false; } return true; - } - + } + /// /// Gets the tracestate header value for the agent /// /// The sample rate /// The tracestate header - public static string GetHeaderValue(double sampleRate) => FullPrefix + sampleRate.ToString(CultureInfo.InvariantCulture); - + public static string GetHeaderValue(double sampleRate) => FullPrefix + sampleRate.ToString(CultureInfo.InvariantCulture); + /// /// Creates the tracestate text header to send in outgoing requests /// /// The tracestate text header public string ToTextHeader() => _tracestate.Count == 0 ? null - : TracestateBuilder.Instance.Build(_tracestate, SizeLimit); - + : TracestateBuilder.Instance.Build(_tracestate, SizeLimit); + /// /// Per thread used to concatenate tracestate header. /// @@ -335,8 +340,8 @@ public string Build(List tracestate, int sizeLimit) var builder = GetStringBuilder(); for (int i = 0, size = tracestate.Count; i < size; i++) { - var value = tracestate[i]; - // ignore null entries to allow removing entries without resizing collection + var value = tracestate[i]; + // ignore null entries to allow removing entries without resizing collection if (value != null) AppendTracestateHeaderValue(value, builder, sizeLimit); } @@ -352,17 +357,17 @@ private static void AppendTracestateHeaderValue(string headerValue, StringBuilde requiredLength++; if (builder.Length + requiredLength <= sizeLimit) - { - // header fits completely + { + // header fits completely if (needsComma) builder.Append(VendorSeparator); builder.Append(headerValue); } else - { - // only part of header might be included - // When trimming due to size limit, we must include complete entries + { + // only part of header might be included + // When trimming due to size limit, we must include complete entries var endIndex = 0; for (var i = headerValue.Length - 1; i >= 0; i--) { diff --git a/src/Elastic.Apm/Features/AgentFeatures.cs b/src/Elastic.Apm/Features/AgentFeatures.cs index f93a49602..5879e3b16 100644 --- a/src/Elastic.Apm/Features/AgentFeatures.cs +++ b/src/Elastic.Apm/Features/AgentFeatures.cs @@ -35,7 +35,7 @@ internal bool Check(AgentFeature agentFeature) return enabled; } - internal string Name { get; } + internal string Name { get; } } internal class DefaultAgentFeatures : AgentFeatures diff --git a/src/Elastic.Apm/Filters/SpanStackTraceCapturingFilter.cs b/src/Elastic.Apm/Filters/SpanStackTraceCapturingFilter.cs index 4936f9c0c..a6f08707d 100644 --- a/src/Elastic.Apm/Filters/SpanStackTraceCapturingFilter.cs +++ b/src/Elastic.Apm/Filters/SpanStackTraceCapturingFilter.cs @@ -29,9 +29,11 @@ internal class SpanStackTraceCapturingFilter public ISpan Filter(ISpan iSpan) { - if (!(iSpan is Span span)) return iSpan; + if (!(iSpan is Span span)) + return iSpan; - if (span.RawStackTrace == null) return span; + if (span.RawStackTrace == null) + return span; StackFrame[] trace; try diff --git a/src/Elastic.Apm/Filters/TransactionIgnoreUrlsFilter.cs b/src/Elastic.Apm/Filters/TransactionIgnoreUrlsFilter.cs index b6182e3f9..b6ef1754a 100644 --- a/src/Elastic.Apm/Filters/TransactionIgnoreUrlsFilter.cs +++ b/src/Elastic.Apm/Filters/TransactionIgnoreUrlsFilter.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/Helpers/AgentSpinLock.cs b/src/Elastic.Apm/Helpers/AgentSpinLock.cs index 2dfac62cb..cf6718d3a 100644 --- a/src/Elastic.Apm/Helpers/AgentSpinLock.cs +++ b/src/Elastic.Apm/Helpers/AgentSpinLock.cs @@ -43,7 +43,8 @@ internal bool TryAcquire() /// If this lock is not currently in acquired state internal void Release() { - if (!IsAcquired) throw new InvalidOperationException("Attempt to release lock that is not acquired"); + if (!IsAcquired) + throw new InvalidOperationException("Attempt to release lock that is not acquired"); _isAcquiredBoolValueAsInt = FalseValueAsInt; } @@ -65,7 +66,8 @@ internal Acquisition(AgentSpinLock agentSpinLock, bool isAcquired) public void Dispose() { - if (IsAcquired) _agentSpinLock.Release(); + if (IsAcquired) + _agentSpinLock.Release(); } } } diff --git a/src/Elastic.Apm/Helpers/AgentTimeInstant.cs b/src/Elastic.Apm/Helpers/AgentTimeInstant.cs index 01427ec93..11c2512be 100644 --- a/src/Elastic.Apm/Helpers/AgentTimeInstant.cs +++ b/src/Elastic.Apm/Helpers/AgentTimeInstant.cs @@ -22,7 +22,8 @@ internal AgentTimeInstant(IAgentTimer sourceAgentTimer, TimeSpan elapsedSinceTim public override bool Equals(object otherObj) { - if (otherObj is AgentTimeInstant other) return Equals(other); + if (otherObj is AgentTimeInstant other) + return Equals(other); return false; } @@ -74,7 +75,8 @@ public override bool Equals(object otherObj) private static void VerifyInstantsAreCompatible(AgentTimeInstant i1, AgentTimeInstant i2, [CallerMemberName] string caller = null) { - if (i1.IsCompatibleWith(i2._sourceAgentTimer)) return; + if (i1.IsCompatibleWith(i2._sourceAgentTimer)) + return; var opName = caller == null ? "an operation" : $"operation {caller}"; throw new InvalidOperationException($"It's illegal to perform {opName} on two AgentTimeInstant instances " + diff --git a/src/Elastic.Apm/Helpers/AgentTimer.cs b/src/Elastic.Apm/Helpers/AgentTimer.cs index b1bac9c53..0999ee4f5 100644 --- a/src/Elastic.Apm/Helpers/AgentTimer.cs +++ b/src/Elastic.Apm/Helpers/AgentTimer.cs @@ -36,7 +36,8 @@ private async Task DelayAsyncImpl(AgentTimeInstant until, CancellationToken canc var now = Now; var delayRemainder = until - now; - if (delayRemainder <= TimeSpan.Zero) return; + if (delayRemainder <= TimeSpan.Zero) + return; await Task.Delay(delayRemainder, cancellationToken); } diff --git a/src/Elastic.Apm/Helpers/Assertion.cs b/src/Elastic.Apm/Helpers/Assertion.cs index 70863193d..6a7f6c070 100644 --- a/src/Elastic.Apm/Helpers/Assertion.cs +++ b/src/Elastic.Apm/Helpers/Assertion.cs @@ -52,12 +52,14 @@ internal class Impl internal void DoIfEnabled(Action doAction) { - if (IsEnabled) doAction(SingletonAssertIfEnabled); + if (IsEnabled) + doAction(SingletonAssertIfEnabled); } internal void DoIf_O_n_LevelEnabled(Action doAction) { - if (Is_O_n_LevelEnabled) doAction(SingletonAssertIfEnabled); + if (Is_O_n_LevelEnabled) + doAction(SingletonAssertIfEnabled); } } @@ -65,7 +67,8 @@ internal struct AssertIfEnabled { internal void That(bool condition, string message) { - if (!condition) throw new AssertionFailedException(message); + if (!condition) + throw new AssertionFailedException(message); } } } diff --git a/src/Elastic.Apm/Helpers/DbConnectionStringParser.cs b/src/Elastic.Apm/Helpers/DbConnectionStringParser.cs index d9cc288cd..0f2c4d016 100644 --- a/src/Elastic.Apm/Helpers/DbConnectionStringParser.cs +++ b/src/Elastic.Apm/Helpers/DbConnectionStringParser.cs @@ -43,7 +43,8 @@ internal Destination ExtractDestination(string dbConnectionString, out bool wasF wasFoundInCache = false; destination = ParseConnectionString(dbConnectionString); - if (_cacheCount < MaxCacheSize && _cache.TryAdd(dbConnectionString, destination)) Interlocked.Increment(ref _cacheCount); + if (_cacheCount < MaxCacheSize && _cache.TryAdd(dbConnectionString, destination)) + Interlocked.Increment(ref _cacheCount); return destination; } @@ -128,7 +129,8 @@ internal void ParseFlatKeyValuePairs(string flatKeyValuePairs) private void ParseKeyValue(string keyValue) { - if (string.IsNullOrWhiteSpace(keyValue)) return; + if (string.IsNullOrWhiteSpace(keyValue)) + return; var keyValueSplit = keyValue.Split(new[] { KeyValueSeparator }, 2); if (keyValueSplit.Length < 2) @@ -145,7 +147,8 @@ private void ParseKeyValue(string keyValue) // Skip unknown keys if (!_keyToPropertySetter.TryGetValue(key, out var valueParser)) { - if (!HasNestedStructure(value)) return; + if (!HasNestedStructure(value)) + return; // Unless value for an unknown key has nested structure // then we want to go into the value to see if we find known keys @@ -187,10 +190,12 @@ private static int FindMatchingClosingDelimiter(string str, int openingDelimiter var currentDelimiterIndex = openingDelimiterIndex; while (true) { - if (currentDelimiterIndex == str.Length - 1) break; + if (currentDelimiterIndex == str.Length - 1) + break; currentDelimiterIndex = str.IndexOfAny(NestedDelimiters, currentDelimiterIndex + 1); - if (currentDelimiterIndex == -1) break; + if (currentDelimiterIndex == -1) + break; if (str[currentDelimiterIndex] == NestedOpeningDelimiter) { @@ -199,7 +204,8 @@ private static int FindMatchingClosingDelimiter(string str, int openingDelimiter } --nestingDepth; - if (nestingDepth != 0) continue; + if (nestingDepth != 0) + continue; matchingClosingDelimiterIndex = currentDelimiterIndex; break; @@ -221,7 +227,8 @@ private void ParseNestedStructure(string value) Assertion.IfEnabled?.That(HasNestedStructure(value), $"This method should called only on values with nested structure. Provided value: `{value}'."); - if (_currentNestingDepth + 1 > MaxNestingDepth) return; + if (_currentNestingDepth + 1 > MaxNestingDepth) + return; ++_currentNestingDepth; var currentSubKeyValueOpenDelimiterIndex = 0; @@ -232,11 +239,13 @@ private void ParseNestedStructure(string value) currentSubKeyValueOpenDelimiterIndex + 1, currentSubKeyValueCloseDelimiterIndex - (currentSubKeyValueOpenDelimiterIndex + 1))); - if (currentSubKeyValueCloseDelimiterIndex == value.Length - 1) break; + if (currentSubKeyValueCloseDelimiterIndex == value.Length - 1) + break; currentSubKeyValueOpenDelimiterIndex = value.IndexOf(NestedOpeningDelimiter, currentSubKeyValueCloseDelimiterIndex + 1); - if (currentSubKeyValueOpenDelimiterIndex == -1) break; + if (currentSubKeyValueOpenDelimiterIndex == -1) + break; } --_currentNestingDepth; @@ -247,7 +256,8 @@ private void ParseNestedStructure(string value) private void ParseAddressKeyWithNestedStructureValue(string value) { // If we already found address part of destination we don't need to parse anymore - if (_destination.AddressHasValue) return; + if (_destination.AddressHasValue) + return; if (!HasNestedStructure(value)) { @@ -262,7 +272,8 @@ private void ParseAddressKeyWithNestedStructureValue(string value) private void ParseServerValue(string valueArg) { // Some DB connection string formats allow multiple addresses - we use only the first one - if (_destination.AddressHasValue) return; + if (_destination.AddressHasValue) + return; var value = TrimDiscardable(valueArg); @@ -280,7 +291,8 @@ private void ParseServerValue(string valueArg) } var dbInstanceSeparatorIndex = value.IndexOf(ServerNameDbInstanceSeparator); - if (dbInstanceSeparatorIndex != -1) value = value.Substring(0, dbInstanceSeparatorIndex); + if (dbInstanceSeparatorIndex != -1) + value = value.Substring(0, dbInstanceSeparatorIndex); ParseServerWithOptionalPort(value); } @@ -314,17 +326,21 @@ private static string TrimDiscardableSuffix(string value) // IPv6 can contain `/' and we don't want to discard a part of the address var lastSlashIndex = value.LastIndexOf('/'); - if (lastSlashIndex == -1) return value; + if (lastSlashIndex == -1) + return value; var foundNonHexDigit = false; - for (var i = lastSlashIndex + 1 ; i < value.Length ; ++i ) + for (var i = lastSlashIndex + 1; i < value.Length; ++i) { - if (! TextUtils.IsLatinLetter(value[i])) return value; - if (!foundNonHexDigit && !TextUtils.IsHex(value[i])) foundNonHexDigit = true; + if (!TextUtils.IsLatinLetter(value[i])) + return value; + if (!foundNonHexDigit && !TextUtils.IsHex(value[i])) + foundNonHexDigit = true; } // If the suffix part after / is not empty and it's a valid hex number - we don't want to trim it - if (lastSlashIndex < value.Length - 1 && !foundNonHexDigit) return value; + if (lastSlashIndex < value.Length - 1 && !foundNonHexDigit) + return value; return value.Substring(0, lastSlashIndex); } @@ -408,7 +424,7 @@ private void ParsePortValue(string valueToParse) if (string.IsNullOrWhiteSpace(valueToParse)) throw new FormatException($"Port part of server value is white space only/empty string. valueToParse: `{valueToParse}'."); - if (! int.TryParse(valueToParse, NumberStyles.Integer, CultureInfo.InvariantCulture, out var port)) + if (!int.TryParse(valueToParse, NumberStyles.Integer, CultureInfo.InvariantCulture, out var port)) throw new FormatException($"Failed to parse port part of server value. valueToParse: `{valueToParse}'."); if (port < 0) diff --git a/src/Elastic.Apm/Helpers/DbgInstanceNameGenerator.cs b/src/Elastic.Apm/Helpers/DbgInstanceNameGenerator.cs index f2edff5e8..6fa1e7613 100644 --- a/src/Elastic.Apm/Helpers/DbgInstanceNameGenerator.cs +++ b/src/Elastic.Apm/Helpers/DbgInstanceNameGenerator.cs @@ -18,7 +18,8 @@ internal string Generate(string prefix = null) { var result = new StringBuilder(); - if (prefix != null) result.Append(prefix); + if (prefix != null) + result.Append(prefix); var currentId = Interlocked.Increment(ref _lastId); result.Append(currentId); diff --git a/src/Elastic.Apm/Helpers/DisposableHelper.cs b/src/Elastic.Apm/Helpers/DisposableHelper.cs index c21df9e2c..dfe70966b 100644 --- a/src/Elastic.Apm/Helpers/DisposableHelper.cs +++ b/src/Elastic.Apm/Helpers/DisposableHelper.cs @@ -24,7 +24,8 @@ internal bool DoOnce(IApmLogger loggerArg, string dbgOwnerDesc, Action ownerDisp var stateBeforeTry = TryChangeStateAtomically(State.BeforeDispose, State.DuringDispose); switch (stateBeforeTry) { - case State.BeforeDispose: break; + case State.BeforeDispose: + break; case State.DuringDispose: logger.Critical()?.Log(string.Format(AnotherCallStillInProgressMsg, "{DisposableDesc}"), dbgOwnerDesc); diff --git a/src/Elastic.Apm/Helpers/EnvironmentVariables.cs b/src/Elastic.Apm/Helpers/EnvironmentVariables.cs index 77e5495e1..6a1fc9593 100644 --- a/src/Elastic.Apm/Helpers/EnvironmentVariables.cs +++ b/src/Elastic.Apm/Helpers/EnvironmentVariables.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections; using Elastic.Apm.Logging; diff --git a/src/Elastic.Apm/Helpers/ExceptionUtils.cs b/src/Elastic.Apm/Helpers/ExceptionUtils.cs index 908ddbe3d..4d0e2e937 100644 --- a/src/Elastic.Apm/Helpers/ExceptionUtils.cs +++ b/src/Elastic.Apm/Helpers/ExceptionUtils.cs @@ -32,7 +32,8 @@ internal static class ExceptionUtils { logger.Debug()?.LogException(ex, MethodExitingCancelledMsgFmt, dbgCallerMethodName); - if (!shouldSwallowCancellation) throw; + if (!shouldSwallowCancellation) + throw; } catch (Exception ex) { diff --git a/src/Elastic.Apm/Helpers/GrpcHelper.cs b/src/Elastic.Apm/Helpers/GrpcHelper.cs index 66eb14788..ac02608b0 100644 --- a/src/Elastic.Apm/Helpers/GrpcHelper.cs +++ b/src/Elastic.Apm/Helpers/GrpcHelper.cs @@ -1,4 +1,4 @@ -using Elastic.Apm.Api; +using Elastic.Apm.Api; namespace Elastic.Apm.Helpers { diff --git a/src/Elastic.Apm/Helpers/IAgentTimer.cs b/src/Elastic.Apm/Helpers/IAgentTimer.cs index 7b21f78a3..9d44b5e73 100644 --- a/src/Elastic.Apm/Helpers/IAgentTimer.cs +++ b/src/Elastic.Apm/Helpers/IAgentTimer.cs @@ -49,7 +49,8 @@ internal static class AgentTimerExtensions } finally { - if (!timeoutDelayTask.IsCompleted) timeoutDelayCts.Cancel(); + if (!timeoutDelayTask.IsCompleted) + timeoutDelayCts.Cancel(); timeoutDelayCts.Dispose(); } } @@ -87,7 +88,8 @@ internal static class AgentTimerExtensions ) { var timeStarted = agentTimer.Now; - if (await TryAwaitOrTimeout(agentTimer, taskToAwait, until, cancellationToken)) return; + if (await TryAwaitOrTimeout(agentTimer, taskToAwait, until, cancellationToken)) + return; throw new TimeoutException($"Elapsed time: {(agentTimer.Now - timeStarted).ToHms()}"); } @@ -111,7 +113,8 @@ internal static class AgentTimerExtensions var timeStarted = agentTimer.Now; var (hasTaskToAwaitCompletedBeforeTimeout, result) = await TryAwaitOrTimeout(agentTimer, taskToAwait, until, cancellationToken); - if (hasTaskToAwaitCompletedBeforeTimeout) return result; + if (hasTaskToAwaitCompletedBeforeTimeout) + return result; throw new TimeoutException($"Elapsed time: {(agentTimer.Now - timeStarted).ToHms()}"); } diff --git a/src/Elastic.Apm/Helpers/IHttpFormAdapter.cs b/src/Elastic.Apm/Helpers/IHttpFormAdapter.cs index dfce9ea86..93f756ed0 100644 --- a/src/Elastic.Apm/Helpers/IHttpFormAdapter.cs +++ b/src/Elastic.Apm/Helpers/IHttpFormAdapter.cs @@ -2,17 +2,17 @@ // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -using System.Text; using System; -using Elastic.Apm.Config; using System.Collections.Generic; +using System.Text; +using Elastic.Apm.Config; namespace Elastic.Apm.Helpers { internal interface IHttpFormAdapter : IEnumerable<(string Key, string Value)> { bool HasValue { get; } - int Count { get; } + int Count { get; } } internal static class IHttpFormAdapterExtensions diff --git a/src/Elastic.Apm/Helpers/IHttpRequestAdapter.cs b/src/Elastic.Apm/Helpers/IHttpRequestAdapter.cs index 10871253b..c628c6dda 100644 --- a/src/Elastic.Apm/Helpers/IHttpRequestAdapter.cs +++ b/src/Elastic.Apm/Helpers/IHttpRequestAdapter.cs @@ -2,8 +2,8 @@ // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -using System.IO; using System; +using System.IO; using Elastic.Apm.Config; using Elastic.Apm.Logging; diff --git a/src/Elastic.Apm/Helpers/RandomGenerator.cs b/src/Elastic.Apm/Helpers/RandomGenerator.cs index 736a4338c..08a7595b5 100644 --- a/src/Elastic.Apm/Helpers/RandomGenerator.cs +++ b/src/Elastic.Apm/Helpers/RandomGenerator.cs @@ -19,7 +19,8 @@ internal static Random GetInstance() if (inst == null) { int seed; - lock (Global) seed = Global.Next(); + lock (Global) + seed = Global.Next(); _local = inst = new Random(seed); } return inst; diff --git a/src/Elastic.Apm/Helpers/RequestBodyStreamHelper.cs b/src/Elastic.Apm/Helpers/RequestBodyStreamHelper.cs index de04b95ef..f7a0aa140 100644 --- a/src/Elastic.Apm/Helpers/RequestBodyStreamHelper.cs +++ b/src/Elastic.Apm/Helpers/RequestBodyStreamHelper.cs @@ -17,7 +17,8 @@ internal static string ToString(Stream requestBody, out bool longerThanMaxLength { longerThanMaxLength = false; - if (requestBody == null) return null; + if (requestBody == null) + return null; string body = null; diff --git a/src/Elastic.Apm/Helpers/Sanitization.cs b/src/Elastic.Apm/Helpers/Sanitization.cs index c0e1b0661..6099dc6c1 100644 --- a/src/Elastic.Apm/Helpers/Sanitization.cs +++ b/src/Elastic.Apm/Helpers/Sanitization.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; @@ -11,7 +11,7 @@ namespace Elastic.Apm.Helpers { internal static class Sanitization - { + { /// /// Sanitizes a , redacting user info from the request URI and HTTP headers that /// match any of the matchers. @@ -38,8 +38,8 @@ internal static HttpRequestMessage Sanitize(this HttpRequestMessage message, IRe } return message; - } - + } + /// /// Redacts username and password, if present /// diff --git a/src/Elastic.Apm/Helpers/StacktraceHelper.cs b/src/Elastic.Apm/Helpers/StacktraceHelper.cs index 2ce614929..6221f67db 100644 --- a/src/Elastic.Apm/Helpers/StacktraceHelper.cs +++ b/src/Elastic.Apm/Helpers/StacktraceHelper.cs @@ -59,7 +59,7 @@ internal static class StacktraceHelper ?.DeclaringType?.FullName; //see: https://github.com/elastic/apm-agent-dotnet/pull/240#discussion_r289619196 var functionName = GetRealMethodName(frame?.GetMethod()); - if(frame is EnhancedStackFrame enhancedStackFrame && enhancedStackFrame.IsRecursive) + if (frame is EnhancedStackFrame enhancedStackFrame && enhancedStackFrame.IsRecursive) functionName += $" x {enhancedStackFrame.MethodInfo.RecurseCount}"; var fileName = frame?.GetFileName(); diff --git a/src/Elastic.Apm/Helpers/StringExtensions.cs b/src/Elastic.Apm/Helpers/StringExtensions.cs index 00349a859..fb3fc6be1 100644 --- a/src/Elastic.Apm/Helpers/StringExtensions.cs +++ b/src/Elastic.Apm/Helpers/StringExtensions.cs @@ -24,8 +24,10 @@ internal static string Repeat(this string input, int count) input.ThrowIfArgumentNull(nameof(input)); count.ThrowIfArgumentNegative(nameof(count)); - if (input.IsEmpty() || count == 0) return string.Empty; - if (count == 1) return input; + if (input.IsEmpty() || count == 0) + return string.Empty; + if (count == 1) + return input; return new StringBuilder(input.Length * count).Insert(0, input, count).ToString(); } @@ -47,9 +49,11 @@ internal static string Truncate(this string input, int length = Consts.PropertyM if (input is null) return null; - if (input.Length <= length) return input; + if (input.Length <= length) + return input; - if (length <= 5) return input.Substring(0, length); + if (length <= 5) + return input.Substring(0, length); return $"{input.Substring(0, length - Ellipsis.Length)}{Ellipsis}"; } diff --git a/src/Elastic.Apm/Helpers/TextUtils.cs b/src/Elastic.Apm/Helpers/TextUtils.cs index 634e20eb2..83d7f850e 100644 --- a/src/Elastic.Apm/Helpers/TextUtils.cs +++ b/src/Elastic.Apm/Helpers/TextUtils.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -21,7 +21,8 @@ internal static string PrefixEveryLine(string input, string prefix = Indentation input.ThrowIfArgumentNull(nameof(input)); // We treat empty input as a special case because StringReader doesn't return it as an empty line - if (input.IsEmpty()) return prefix; + if (input.IsEmpty()) + return prefix; var resultBuilder = new StringBuilder(input.Length); using (var stringReader = new StringReader(input)) @@ -44,7 +45,8 @@ internal static string PrefixEveryLine(string input, string prefix = Indentation foreach (var endOfLineSeq in EndOfLineCharSequences) { - if (!input.EndsWith(endOfLineSeq)) continue; + if (!input.EndsWith(endOfLineSeq)) + continue; resultBuilder.Append(endOfLineSeq); break; @@ -59,12 +61,12 @@ internal static string PrefixEveryLine(string input, string prefix = Indentation Indent(input, Indentation.Repeat(indentationLevel)); internal static bool IsHex(char c) => - ( '0' <= c && c <= '9' ) || - ( 'a' <= c && c <= 'f' ) || - ( 'A' <= c && c <= 'F' ); + ('0' <= c && c <= '9') || + ('a' <= c && c <= 'f') || + ('A' <= c && c <= 'F'); internal static bool IsLatinLetter(char c) => - ( 'a' <= c && c <= 'z' ) || - ( 'A' <= c && c <= 'Z' ); + ('a' <= c && c <= 'z') || + ('A' <= c && c <= 'Z'); } } diff --git a/src/Elastic.Apm/Helpers/TimeExtensions.cs b/src/Elastic.Apm/Helpers/TimeExtensions.cs index e3602fbec..53131edfd 100644 --- a/src/Elastic.Apm/Helpers/TimeExtensions.cs +++ b/src/Elastic.Apm/Helpers/TimeExtensions.cs @@ -19,10 +19,14 @@ internal static string FormatForLog(this DateTimeKind dateTimeKind) { switch (dateTimeKind) { - case DateTimeKind.Utc: return "UTC"; - case DateTimeKind.Local: return "Local"; - case DateTimeKind.Unspecified: return "Unspecified"; - default: return $"UNRECOGNIZED {dateTimeKind} ({(int)dateTimeKind} as int)"; + case DateTimeKind.Utc: + return "UTC"; + case DateTimeKind.Local: + return "Local"; + case DateTimeKind.Unspecified: + return "Unspecified"; + default: + return $"UNRECOGNIZED {dateTimeKind} ({(int)dateTimeKind} as int)"; } } @@ -34,11 +38,13 @@ internal static string FormatForLog(this DateTimeKind dateTimeKind) /// internal static string ToHms(this TimeSpan timeSpan) { - if (timeSpan == TimeSpan.Zero) return "0"; + if (timeSpan == TimeSpan.Zero) + return "0"; var strBuilder = new StringBuilder(); - if (timeSpan < TimeSpan.Zero) strBuilder.Append("-"); + if (timeSpan < TimeSpan.Zero) + strBuilder.Append("-"); var hasParts = false; @@ -67,10 +73,13 @@ internal static string ToHms(this TimeSpan timeSpan) void AppendIfNotZero(int count, string unitsSuffix) { - if (count == 0) return; + if (count == 0) + return; - if (hasParts) strBuilder.Append(" "); - else hasParts = true; + if (hasParts) + strBuilder.Append(" "); + else + hasParts = true; strBuilder.Append(Math.Abs(count)).Append(unitsSuffix); } @@ -84,10 +93,12 @@ void AppendIfNotZero(int count, string unitsSuffix) /// internal static string ToHmsInSeconds(this TimeSpan timeSpan) { - if (timeSpan == TimeSpan.Zero) return "0s"; + if (timeSpan == TimeSpan.Zero) + return "0s"; var truncated = TruncateToSeconds(timeSpan); - if (truncated != TimeSpan.Zero) return truncated.ToHms(); + if (truncated != TimeSpan.Zero) + return truncated.ToHms(); return timeSpan > TimeSpan.Zero ? "<1s" : ">-1s"; } diff --git a/src/Elastic.Apm/Helpers/UrlUtils.cs b/src/Elastic.Apm/Helpers/UrlUtils.cs index 5996773a2..e9cd3e288 100644 --- a/src/Elastic.Apm/Helpers/UrlUtils.cs +++ b/src/Elastic.Apm/Helpers/UrlUtils.cs @@ -16,7 +16,7 @@ internal static class UrlUtils internal static Destination ExtractDestination(Uri url, IApmLogger logger) { if (!url.IsAbsoluteUri || url.HostNameType == UriHostNameType.Basic || - url.HostNameType == UriHostNameType.Unknown) + url.HostNameType == UriHostNameType.Unknown) { logger.Scoped($"{ThisClassName}.{DbgUtils.CurrentMethodName()}") .Debug() @@ -29,7 +29,7 @@ internal static Destination ExtractDestination(Uri url, IApmLogger logger) var host = url.Host; if (url.HostNameType == UriHostNameType.IPv6 && host.Length > 2 && host[0] == '[' && - host[host.Length - 1] == ']') + host[host.Length - 1] == ']') host = host.Substring(1, host.Length - 2); return new Destination { Address = host, Port = url.Port == -1 ? null : url.Port }; diff --git a/src/Elastic.Apm/Helpers/WildcardMatcher.cs b/src/Elastic.Apm/Helpers/WildcardMatcher.cs index dec07c09c..b02b4d147 100644 --- a/src/Elastic.Apm/Helpers/WildcardMatcher.cs +++ b/src/Elastic.Apm/Helpers/WildcardMatcher.cs @@ -60,7 +60,8 @@ public static WildcardMatcher ValueOf(string wildcardString) ignoreCase = false; matcher = matcher.Substring(CaseSensitivePrefix.Length); } - else if (matcher.StartsWith(CaseInsensitivePrefix)) matcher = matcher.Substring(CaseInsensitivePrefix.Length); + else if (matcher.StartsWith(CaseInsensitivePrefix)) + matcher = matcher.Substring(CaseInsensitivePrefix.Length); var split = matcher.Split('*'); @@ -111,7 +112,8 @@ public static WildcardMatcher ValueOf(string wildcardString) /// The first matching , or null if none match. internal static WildcardMatcher AnyMatch(IReadOnlyCollection matchers, string firstPart, string secondPart) { - if (matchers is null) return null; + if (matchers is null) + return null; for (var i = 0; i < matchers.Count; i++) { @@ -135,7 +137,8 @@ internal static WildcardMatcher AnyMatch(IReadOnlyCollection ma /// internal static int IndexOfIgnoreCase(string haystack1, string haystack2, string needle, bool ignoreCase, int start, int end) { - if (start < 0) return -1; + if (start < 0) + return -1; var totalHaystackLength = haystack1.Length + haystack2.Length; if (needle.IsEmpty() || totalHaystackLength == 0) @@ -149,7 +152,8 @@ internal static int IndexOfIgnoreCase(string haystack1, string haystack2, string for (var i = start; i < end; i++) { // Early out, if possible. - if (i + needleLength > totalHaystackLength) return -1; + if (i + needleLength > totalHaystackLength) + return -1; // Attempt to match substring starting at position i of haystack. var j = 0; @@ -160,14 +164,16 @@ internal static int IndexOfIgnoreCase(string haystack1, string haystack2, string ? char.ToLowerInvariant(CharAt(ii, haystack1, haystack2, haystack1Length)) : CharAt(ii, haystack1, haystack2, haystack1Length); var c2 = ignoreCase ? char.ToLowerInvariant(needle.ElementAt(j)) : needle.ElementAt(j); - if (c != c2) break; + if (c != c2) + break; j++; ii++; } // Walked all the way to the end of the needle, return the start // position that this was found. - if (j == needleLength) return i; + if (j == needleLength) + return i; } return -1; @@ -199,7 +205,8 @@ public override bool Matches(string s) { var matcher = _wildcardMatchers.ElementAt(i); offset = matcher.IndexOf(s, offset); - if (offset == -1) return false; + if (offset == -1) + return false; offset += matcher.Matcher.Length; } @@ -213,7 +220,8 @@ internal override bool Matches(string firstPart, string secondPart) { var wildcardMatcher = _wildcardMatchers.ElementAt(i); offset = wildcardMatcher.IndexOf(firstPart, secondPart, offset); - if (offset == -1) return false; + if (offset == -1) + return false; offset += wildcardMatcher.Matcher.Length; } @@ -272,7 +280,8 @@ public SimpleWildcardMatcher(string matcher, bool wildcardAtBeginning, bool wild public int IndexOf(string firstPart, string secondPart, int offset) { - if (secondPart == null) secondPart = ""; + if (secondPart == null) + secondPart = ""; var totalLength = firstPart.Length + secondPart.Length; if (_wildcardAtEnd && _wildcardAtBeginning) return IndexOfIgnoreCase(firstPart, secondPart, Matcher, _ignoreCase, offset, totalLength); diff --git a/src/Elastic.Apm/Logging/ConsoleLogger.cs b/src/Elastic.Apm/Logging/ConsoleLogger.cs index 1a8b14be5..1a811914a 100644 --- a/src/Elastic.Apm/Logging/ConsoleLogger.cs +++ b/src/Elastic.Apm/Logging/ConsoleLogger.cs @@ -41,7 +41,8 @@ internal static ConsoleLogger LoggerOrDefault(LogLevel? level) public void Log(LogLevel level, TState state, Exception e, Func formatter) { - if (!IsEnabled(level)) return; + if (!IsEnabled(level)) + return; TextWriter writer; switch (level) @@ -99,15 +100,22 @@ internal static string LevelToString(LogLevel level) { switch (level) { - case LogLevel.Error: return "Error"; - case LogLevel.Warning: return "Warning"; - case LogLevel.Information: return "Info"; - case LogLevel.Debug: return "Debug"; - case LogLevel.Trace: return "Trace"; - case LogLevel.Critical: return "Critical"; + case LogLevel.Error: + return "Error"; + case LogLevel.Warning: + return "Warning"; + case LogLevel.Information: + return "Info"; + case LogLevel.Debug: + return "Debug"; + case LogLevel.Trace: + return "Trace"; + case LogLevel.Critical: + return "Critical"; // ReSharper disable once RedundantCaseLabel case LogLevel.None: - default: return "None"; + default: + return "None"; } } } diff --git a/src/Elastic.Apm/Logging/LogLevel.cs b/src/Elastic.Apm/Logging/LogLevel.cs index 96f46b53c..f0d012d3b 100644 --- a/src/Elastic.Apm/Logging/LogLevel.cs +++ b/src/Elastic.Apm/Logging/LogLevel.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/Logging/LogLevelSwitch.cs b/src/Elastic.Apm/Logging/LogLevelSwitch.cs index 46fa3791c..30177a2b2 100644 --- a/src/Elastic.Apm/Logging/LogLevelSwitch.cs +++ b/src/Elastic.Apm/Logging/LogLevelSwitch.cs @@ -1,10 +1,10 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + namespace Elastic.Apm.Logging -{ +{ /// /// Dynamically controls the log level /// @@ -12,8 +12,8 @@ public class LogLevelSwitch { private volatile LogLevel _level; - public LogLevelSwitch(LogLevel level) => _level = level; - + public LogLevelSwitch(LogLevel level) => _level = level; + /// /// Gets or sets the current log level /// diff --git a/src/Elastic.Apm/Logging/LogValuesFormatter.cs b/src/Elastic.Apm/Logging/LogValuesFormatter.cs index 860755ff6..068c5eab9 100644 --- a/src/Elastic.Apm/Logging/LogValuesFormatter.cs +++ b/src/Elastic.Apm/Logging/LogValuesFormatter.cs @@ -140,7 +140,8 @@ private static int FindIndexOfAny(string format, char[] chars, int startIndex, i public string Format(object[] values) { - if (_scope != null) return Format(_scope, values); + if (_scope != null) + return Format(_scope, values); values = values ?? EmptyArray; @@ -164,14 +165,17 @@ private string Format(string scope, object[] values) private object FormatArgument(object value) { - if (value == null) return NullValue; + if (value == null) + return NullValue; // since 'string' implements IEnumerable, special case it - if (value is string) return value; + if (value is string) + return value; // if the value implements IEnumerable, build a comma separated string. var enumerable = value as IEnumerable; - if (enumerable != null) return string.Join(", ", enumerable.Cast().Select(o => o ?? NullValue)); + if (enumerable != null) + return string.Join(", ", enumerable.Cast().Select(o => o ?? NullValue)); return value; } diff --git a/src/Elastic.Apm/Logging/TraceLogger.cs b/src/Elastic.Apm/Logging/TraceLogger.cs index 45c393daa..c374e29a4 100644 --- a/src/Elastic.Apm/Logging/TraceLogger.cs +++ b/src/Elastic.Apm/Logging/TraceLogger.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -10,7 +10,7 @@ using System.Threading; namespace Elastic.Apm.Logging -{ +{ /// /// A logging implementation that logs to a with the source name Elastic.Apm /// @@ -32,7 +32,8 @@ internal class TraceLogger : IApmLogger, ILogLevelSwitchable public void Log(LogLevel level, TState state, Exception e, Func formatter) { - if (!IsEnabled(level)) return; + if (!IsEnabled(level)) + return; var message = formatter(state, e); var logLevel = LevelToString(level); @@ -95,15 +96,22 @@ internal static string LevelToString(LogLevel level) { switch (level) { - case LogLevel.Error: return "Error"; - case LogLevel.Warning: return "Warning"; - case LogLevel.Information: return "Info"; - case LogLevel.Debug: return "Debug"; - case LogLevel.Trace: return "Trace"; - case LogLevel.Critical: return "Critical"; - // ReSharper disable once RedundantCaseLabel + case LogLevel.Error: + return "Error"; + case LogLevel.Warning: + return "Warning"; + case LogLevel.Information: + return "Info"; + case LogLevel.Debug: + return "Debug"; + case LogLevel.Trace: + return "Trace"; + case LogLevel.Critical: + return "Critical"; + // ReSharper disable once RedundantCaseLabel case LogLevel.None: - default: return "None"; + default: + return "None"; } } } diff --git a/src/Elastic.Apm/Metrics/MetricSet.cs b/src/Elastic.Apm/Metrics/MetricSet.cs index 7913fe4ff..b1e33d66d 100644 --- a/src/Elastic.Apm/Metrics/MetricSet.cs +++ b/src/Elastic.Apm/Metrics/MetricSet.cs @@ -6,8 +6,8 @@ using System.Collections.Generic; using Elastic.Apm.Api; using Elastic.Apm.Api.Constraints; -using Elastic.Apm.Report.Serialization; using Elastic.Apm.Libraries.Newtonsoft.Json; +using Elastic.Apm.Report.Serialization; namespace Elastic.Apm.Metrics { @@ -39,17 +39,22 @@ public class TransactionInfo : IEquatable public bool Equals(TransactionInfo other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + return false; + if (ReferenceEquals(this, other)) + return true; return Name == other.Name && Type == other.Type; } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; + if (ReferenceEquals(null, obj)) + return false; + if (ReferenceEquals(this, obj)) + return true; + if (obj.GetType() != GetType()) + return false; return Equals((TransactionInfo)obj); } @@ -76,17 +81,22 @@ public class SpanInfo : IEquatable public bool Equals(SpanInfo other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + return false; + if (ReferenceEquals(this, other)) + return true; return Type == other.Type && SubType == other.SubType; } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; + if (ReferenceEquals(null, obj)) + return false; + if (ReferenceEquals(this, obj)) + return true; + if (obj.GetType() != GetType()) + return false; return Equals((SpanInfo)obj); } diff --git a/src/Elastic.Apm/Metrics/MetricsCollector.cs b/src/Elastic.Apm/Metrics/MetricsCollector.cs index 970fde6b6..e02229cde 100644 --- a/src/Elastic.Apm/Metrics/MetricsCollector.cs +++ b/src/Elastic.Apm/Metrics/MetricsCollector.cs @@ -144,7 +144,8 @@ private void CollectAllMetricsImpl() try { - foreach (var item in samplesFromAllProviders) _payloadSender.QueueMetrics(item); + foreach (var item in samplesFromAllProviders) + _payloadSender.QueueMetrics(item); _logger.Debug() ?.Log("Metrics collected: {data}", @@ -213,7 +214,8 @@ private List CollectMetricsFromProviders() metricsProvider.ConsecutiveNumberOfFailedReads); } - if (metricsProvider.ConsecutiveNumberOfFailedReads != MaxTryWithoutSuccess) continue; + if (metricsProvider.ConsecutiveNumberOfFailedReads != MaxTryWithoutSuccess) + continue; _logger.Info() ?.Log("Failed reading {operationName} {numberOfTimes} consecutively - the agent won't try reading {operationName} anymore", diff --git a/src/Elastic.Apm/Metrics/MetricsProvider/BreakdownMetricsProvider.cs b/src/Elastic.Apm/Metrics/MetricsProvider/BreakdownMetricsProvider.cs index ec48e92a7..2724a804c 100644 --- a/src/Elastic.Apm/Metrics/MetricsProvider/BreakdownMetricsProvider.cs +++ b/src/Elastic.Apm/Metrics/MetricsProvider/BreakdownMetricsProvider.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -98,12 +98,14 @@ public void CaptureTransaction(Transaction transaction) new MetricSet(new List { new(SpanSelfTimeCount, item.Value.Count), new(SpanSelfTimeSumUs, item.Value.TotalDuration * 1000) - }) { Span = groupKey.Span, Transaction = groupKey.Transaction }; + }) + { Span = groupKey.Span, Transaction = groupKey.Transaction }; _itemsToSend.Add(groupKey, metricSet); } else { - if (_loggedWarning) continue; + if (_loggedWarning) + continue; _logger.Warning() ?.Log( diff --git a/src/Elastic.Apm/Metrics/MetricsProvider/CgroupMetricsProvider.cs b/src/Elastic.Apm/Metrics/MetricsProvider/CgroupMetricsProvider.cs index aedd7dffb..37fd8e8e8 100644 --- a/src/Elastic.Apm/Metrics/MetricsProvider/CgroupMetricsProvider.cs +++ b/src/Elastic.Apm/Metrics/MetricsProvider/CgroupMetricsProvider.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Globalization; @@ -14,7 +14,7 @@ using Elastic.Apm.Logging; namespace Elastic.Apm.Metrics.MetricsProvider -{ +{ /// /// Provides cgroup metrics, if applicable /// @@ -44,8 +44,8 @@ internal class CgroupMetricsProvider : IMetricsProvider private readonly bool _collectMemUsageBytes; private readonly bool _collectStatsInactiveFileBytes; private readonly bool _ignoreOs; - private readonly IApmLogger _logger; - + private readonly IApmLogger _logger; + /// /// Initializes a new instance of /// @@ -53,8 +53,8 @@ internal class CgroupMetricsProvider : IMetricsProvider /// List of disabled metrics public CgroupMetricsProvider(IApmLogger logger, IReadOnlyList disabledMetrics ) - : this(ProcSelfCgroup, ProcSelfMountinfo, logger, disabledMetrics) { } - + : this(ProcSelfCgroup, ProcSelfMountinfo, logger, disabledMetrics) { } + /// /// Initializes a new instance of /// @@ -144,17 +144,17 @@ private CgroupFiles FindCGroupFiles(string procSelfCGroup, string mountInfo) { using var reader = new StreamReader(mountInfo); while ((mountLine = reader.ReadLine()) != null) - { - // cgroup v2 + { + // cgroup v2 var rootCgroupFsPath = ApplyCgroupRegex(Cgroup2MountPoint, mountLine); if (rootCgroupFsPath != null) { cgroupFiles = CreateCgroup2Files(cGroupLine, rootCgroupFsPath); if (cgroupFiles != null) return cgroupFiles; - } - - // cgroup v1 + } + + // cgroup v1 var memoryMountPath = ApplyCgroupRegex(Cgroup1MountPoint, mountLine); if (memoryMountPath != null) { @@ -176,10 +176,10 @@ private CgroupFiles FindCGroupFiles(string procSelfCGroup, string mountInfo) "{File} file does not exist. Looking for memory files in {DefaultFile}.", ProcSelfMountinfo, DefaultSysFsCgroup); - } - - - // Failed to auto-discover the cgroup fs path from mountinfo, fall back to /sys/fs/cgroup + } + + + // Failed to auto-discover the cgroup fs path from mountinfo, fall back to /sys/fs/cgroup cgroupFiles = CreateCgroup2Files(cGroupLine, DefaultSysFsCgroup); if (cgroupFiles != null) return cgroupFiles; @@ -240,8 +240,8 @@ private string GetMaxMemoryFile(string maxMemoryFile, string cgroupUnlimitedCons using var reader = new StreamReader(maxMemoryFile); var memMaxLine = reader.ReadLine(); if (cgroupUnlimitedConstant.Equals(memMaxLine, StringComparison.OrdinalIgnoreCase)) - { - // Make sure we don't send the max metric when cgroup is not bound to a memory limit + { + // Make sure we don't send the max metric when cgroup is not bound to a memory limit maxMemoryFile = null; } @@ -271,9 +271,9 @@ public IEnumerable GetSamples() GetMemoryMemLimitBytes(samples); return new List { new(TimeUtils.TimestampNow(), samples) }; - } - - // ReSharper disable once SuggestBaseTypeForParameter + } + + // ReSharper disable once SuggestBaseTypeForParameter private void GetMemoryMemLimitBytes(List samples) { if (_cGroupFiles.MaxMemoryFile is null) @@ -290,9 +290,9 @@ private void GetMemoryMemLimitBytes(List samples) { _logger.Info()?.LogException(e, "error collecting {Metric} metric", SystemProcessCgroupMemoryMemLimitBytes); } - } - - // ReSharper disable once SuggestBaseTypeForParameter + } + + // ReSharper disable once SuggestBaseTypeForParameter private void GetMemoryMemUsageBytes(List samples) { try @@ -306,9 +306,9 @@ private void GetMemoryMemUsageBytes(List samples) { _logger.Info()?.LogException(e, "error collecting {metric} metric", SystemProcessCgroupMemoryMemUsageBytes); } - } - - // ReSharper disable once SuggestBaseTypeForParameter + } + + // ReSharper disable once SuggestBaseTypeForParameter private void GetStatsInactiveFileBytesMetric(List samples) { try @@ -355,8 +355,8 @@ private void GetStatsInactiveFileBytesMetric(List samples) private bool IsSystemProcessCgroupMemoryStatsInactiveFileBytesEnabled(IReadOnlyList disabledMetrics) => !WildcardMatcher.IsAnyMatch( disabledMetrics, SystemProcessCgroupMemoryStatsInactiveFileBytes); - } - + } + /// /// Holds the collection of relevant cgroup files /// diff --git a/src/Elastic.Apm/Metrics/MetricsProvider/FreeAndTotalMemoryProvider.cs b/src/Elastic.Apm/Metrics/MetricsProvider/FreeAndTotalMemoryProvider.cs index db92acc88..fedbe3aa1 100644 --- a/src/Elastic.Apm/Metrics/MetricsProvider/FreeAndTotalMemoryProvider.cs +++ b/src/Elastic.Apm/Metrics/MetricsProvider/FreeAndTotalMemoryProvider.cs @@ -81,13 +81,15 @@ public IEnumerable GetSamples() if (line != null && line.Contains("MemAvailable:") && _collectFreeMemory) { var (suc, res) = GetEntry(line, "MemAvailable:"); - if (suc) samples.Add(new MetricSample(FreeMemory, res)); + if (suc) + samples.Add(new MetricSample(FreeMemory, res)); hasMemFree = true; } if (line != null && line.Contains("MemTotal:") && _collectTotalMemory) { var (suc, res) = GetEntry(line, "MemTotal:"); - if (suc) samples.Add(new MetricSample(TotalMemory, res)); + if (suc) + samples.Add(new MetricSample(TotalMemory, res)); hasMemTotal = true; } @@ -111,15 +113,19 @@ public IEnumerable GetSamples() var values = line.Substring(line.IndexOf(name, StringComparison.Ordinal) + name.Length); - if (string.IsNullOrWhiteSpace(values)) return (false, 0); + if (string.IsNullOrWhiteSpace(values)) + return (false, 0); var items = values.Trim().Split(' '); switch (items.Length) { - case 1 when ulong.TryParse(items[0], out var res): return (true, res); - case 2 when items[1].ToLowerInvariant() == "kb" && ulong.TryParse(items[0], out var res): return (true, res * 1024); - default: return (false, 0); + case 1 when ulong.TryParse(items[0], out var res): + return (true, res); + case 2 when items[1].ToLowerInvariant() == "kb" && ulong.TryParse(items[0], out var res): + return (true, res * 1024); + default: + return (false, 0); } } diff --git a/src/Elastic.Apm/Metrics/MetricsProvider/GcMetricsProvider.cs b/src/Elastic.Apm/Metrics/MetricsProvider/GcMetricsProvider.cs index c077e269e..6759000d3 100644 --- a/src/Elastic.Apm/Metrics/MetricsProvider/GcMetricsProvider.cs +++ b/src/Elastic.Apm/Metrics/MetricsProvider/GcMetricsProvider.cs @@ -58,7 +58,8 @@ public GcMetricsProvider(IApmLogger logger, IReadOnlyList disab _collectGcGen2Size = !WildcardMatcher.IsAnyMatch(disabledMetrics, GcGen2SizeName); _collectGcGen3Size = !WildcardMatcher.IsAnyMatch(disabledMetrics, GcGen3SizeName); _isEnabled = _collectGcCount || _collectGcTime || _collectGcGen0Size || _collectGcGen1Size || _collectGcGen2Size || _collectGcGen3Size; - if (!IsEnabled(disabledMetrics)) return; + if (!IsEnabled(disabledMetrics)) + return; _logger = logger.Scoped(DbgName); if (!PlatformDetection.IsDotNetCore && !PlatformDetection.IsDotNet) diff --git a/src/Elastic.Apm/Metrics/MetricsProvider/SystemTotalCpuProvider.cs b/src/Elastic.Apm/Metrics/MetricsProvider/SystemTotalCpuProvider.cs index d4ea70f99..0b13be9e2 100644 --- a/src/Elastic.Apm/Metrics/MetricsProvider/SystemTotalCpuProvider.cs +++ b/src/Elastic.Apm/Metrics/MetricsProvider/SystemTotalCpuProvider.cs @@ -30,11 +30,12 @@ internal class SystemTotalCpuProvider : IMetricsProvider, IDisposable public SystemTotalCpuProvider(IApmLogger logger) { _logger = logger.Scoped(nameof(SystemTotalCpuProvider)); - + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { var (success, idle, total) = ReadProcStat(); - if (!success) return; + if (!success) + return; _prevIdleTime = idle; _prevTotalTime = total; @@ -62,7 +63,8 @@ internal SystemTotalCpuProvider(IApmLogger logger, StreamReader procStatStreamRe try { var firstLine = sr.ReadLine(); - if (firstLine == null || !firstLine.ToLower().StartsWith("cpu")) return (false, 0, 0); + if (firstLine == null || !firstLine.ToLower().StartsWith("cpu")) + return (false, 0, 0); var values = firstLine.Substring(3, firstLine.Length - 3).Trim().Split(' ').ToArray(); if (values.Length < 4) @@ -90,7 +92,7 @@ private StreamReader GetProcStatAsStream() public IEnumerable GetSamples() { - if(!_initializationStarted) + if (!_initializationStarted) { // Ideally we'd do all this initialization in the .ctor // The reason to move it here is the call to `new PerformanceCounter(...)`. @@ -144,7 +146,8 @@ public IEnumerable GetSamples() if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - if (_processorTimePerfCounter == null) return null; + if (_processorTimePerfCounter == null) + return null; var val = _processorTimePerfCounter.NextValue(); @@ -157,7 +160,8 @@ public IEnumerable GetSamples() if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { var (success, idle, total) = ReadProcStat(); - if (!success) return null; + if (!success) + return null; var idleTimeDelta = idle - _prevIdleTime; var totalTimeDelta = total - _prevTotalTime; diff --git a/src/Elastic.Apm/Metrics/Windows/GlobalMemoryStatusEx.cs b/src/Elastic.Apm/Metrics/Windows/GlobalMemoryStatusEx.cs index acf4bf2e8..3c3292ee1 100644 --- a/src/Elastic.Apm/Metrics/Windows/GlobalMemoryStatusEx.cs +++ b/src/Elastic.Apm/Metrics/Windows/GlobalMemoryStatusEx.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/Model/DbSpanCommon.cs b/src/Elastic.Apm/Model/DbSpanCommon.cs index a2d1f1790..478667ed7 100644 --- a/src/Elastic.Apm/Model/DbSpanCommon.cs +++ b/src/Elastic.Apm/Model/DbSpanCommon.cs @@ -47,7 +47,8 @@ internal void EndSpan(ISpan span, IDbCommand dbCommand, Outcome outcome, TimeSpa { if (span is Span capturedSpan) { - if (duration.HasValue) capturedSpan.Duration = duration.Value.TotalMilliseconds; + if (duration.HasValue) + capturedSpan.Duration = duration.Value.TotalMilliseconds; GetDefaultProperties(dbCommand.Connection.GetType().FullName, out var spanSubtype, out var defaultPort); capturedSpan.Subtype = spanSubtype; @@ -127,12 +128,15 @@ dbCommandType switch internal Destination GetDestination(string dbConnectionString, int? defaultPort) { - if (dbConnectionString == null) return null; + if (dbConnectionString == null) + return null; var destination = _dbConnectionStringParser.ExtractDestination(dbConnectionString); - if (destination == null) return null; + if (destination == null) + return null; - if (!destination.Port.HasValue) destination.Port = defaultPort; + if (!destination.Port.HasValue) + destination.Port = defaultPort; return destination; } diff --git a/src/Elastic.Apm/Model/Error.cs b/src/Elastic.Apm/Model/Error.cs index 8ef81973e..c6086f80f 100644 --- a/src/Elastic.Apm/Model/Error.cs +++ b/src/Elastic.Apm/Model/Error.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -7,8 +7,8 @@ using Elastic.Apm.Api.Constraints; using Elastic.Apm.Config; using Elastic.Apm.Helpers; -using Elastic.Apm.Logging; using Elastic.Apm.Libraries.Newtonsoft.Json; +using Elastic.Apm.Logging; namespace Elastic.Apm.Model { diff --git a/src/Elastic.Apm/Model/ExecutionSegmentCommon.cs b/src/Elastic.Apm/Model/ExecutionSegmentCommon.cs index b806c2288..81c058d8d 100644 --- a/src/Elastic.Apm/Model/ExecutionSegmentCommon.cs +++ b/src/Elastic.Apm/Model/ExecutionSegmentCommon.cs @@ -208,11 +208,13 @@ internal static Task CaptureSpan(ISpan span, Func> func) private static string GetCulprit(Exception exception, IConfigurationReader configurationReader) { - if (exception == null) return DefaultCulprit; + if (exception == null) + return DefaultCulprit; var stackTrace = new StackTrace(exception); var frames = stackTrace.GetFrames(); - if (frames == null) return DefaultCulprit; + if (frames == null) + return DefaultCulprit; var excludedNamespaces = configurationReader.ExcludedNamespaces; var applicationNamespaces = configurationReader.ApplicationNamespaces; @@ -221,7 +223,8 @@ private static string GetCulprit(Exception exception, IConfigurationReader confi { var method = frame.GetMethod(); var fullyQualifiedTypeName = method.DeclaringType?.FullName ?? "Unknown Type"; - if (IsInApp(fullyQualifiedTypeName, excludedNamespaces, applicationNamespaces)) return fullyQualifiedTypeName; + if (IsInApp(fullyQualifiedTypeName, excludedNamespaces, applicationNamespaces)) + return fullyQualifiedTypeName; } return DefaultCulprit; @@ -231,7 +234,8 @@ private static string GetCulprit(Exception exception, IConfigurationReader confi IReadOnlyCollection applicationNamespaces ) { - if (string.IsNullOrEmpty(fullyQualifiedTypeName)) return false; + if (string.IsNullOrEmpty(fullyQualifiedTypeName)) + return false; if (applicationNamespaces.Count != 0) { diff --git a/src/Elastic.Apm/Model/LabelsDictionary.cs b/src/Elastic.Apm/Model/LabelsDictionary.cs index b46c07e7c..a42f8b37b 100644 --- a/src/Elastic.Apm/Model/LabelsDictionary.cs +++ b/src/Elastic.Apm/Model/LabelsDictionary.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Collections.Generic; using Elastic.Apm.Api; -using Elastic.Apm.Report.Serialization; using Elastic.Apm.Libraries.Newtonsoft.Json; +using Elastic.Apm.Report.Serialization; namespace Elastic.Apm.Model { @@ -30,7 +30,8 @@ internal class LabelsDictionary : Dictionary get { // merge - foreach (var key in Keys) InnerDictionary[key] = base[key]; + foreach (var key in Keys) + InnerDictionary[key] = base[key]; return InnerDictionary; } } diff --git a/src/Elastic.Apm/Model/Metadata.cs b/src/Elastic.Apm/Model/Metadata.cs index ca836507e..3eb7753c8 100644 --- a/src/Elastic.Apm/Model/Metadata.cs +++ b/src/Elastic.Apm/Model/Metadata.cs @@ -1,26 +1,26 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Elastic.Apm.Api; namespace Elastic.Apm.Model { [Specification("metadata.json")] internal class Metadata - { + { /// public Api.Cloud Cloud { get; set; } - public LabelsDictionary Labels { get; set; } = new LabelsDictionary(); - - // ReSharper disable once UnusedAutoPropertyAccessor.Global - used by Json.Net - public Service Service { get; set; } - - // ReSharper disable once UnusedAutoPropertyAccessor.Global - public Api.System System { get; set; } - + public LabelsDictionary Labels { get; set; } = new LabelsDictionary(); + + // ReSharper disable once UnusedAutoPropertyAccessor.Global - used by Json.Net + public Service Service { get; set; } + + // ReSharper disable once UnusedAutoPropertyAccessor.Global + public Api.System System { get; set; } + /// /// Method to conditionally serialize - serialize only when there is at least one label. /// See diff --git a/src/Elastic.Apm/Model/NoopSpan.cs b/src/Elastic.Apm/Model/NoopSpan.cs index d845a6e14..394524a24 100644 --- a/src/Elastic.Apm/Model/NoopSpan.cs +++ b/src/Elastic.Apm/Model/NoopSpan.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -87,14 +87,17 @@ internal class NoopSpan : ISpan public string Type { get; set; } public void CaptureError(string message, string culprit, StackFrame[] frames, string parentId = null, Dictionary labels = null - ) { } + ) + { } public void CaptureException(Exception exception, string culprit = null, bool isHandled = false, string parentId = null, Dictionary labels = null - ) { } + ) + { } public void CaptureErrorLog(ErrorLog errorLog, string parentId = null, Exception exception = null, Dictionary labels = null - ) { } + ) + { } public void CaptureSpan(string name, string type, Action capturedAction, string subType = null, string action = null, bool isExitSpan = false, IEnumerable links = null diff --git a/src/Elastic.Apm/Model/NoopTransaction.cs b/src/Elastic.Apm/Model/NoopTransaction.cs index a3493fe68..f7c17eb47 100644 --- a/src/Elastic.Apm/Model/NoopTransaction.cs +++ b/src/Elastic.Apm/Model/NoopTransaction.cs @@ -83,11 +83,13 @@ IConfiguration configuration public string Type { get; set; } public void CaptureError(string message, string culprit, StackFrame[] frames, string parentId = null, Dictionary labels = null - ) { } + ) + { } public void CaptureException(Exception exception, string culprit = null, bool isHandled = false, string parentId = null, Dictionary labels = null - ) { } + ) + { } public void CaptureSpan(string name, string type, Action capturedAction, string subType = null, string action = null, bool isExitSpan = false, IEnumerable links = null @@ -159,6 +161,7 @@ public bool TryGetLabel(string key, out T value) } public void CaptureErrorLog(ErrorLog errorLog, string parentId = null, Exception exception = null, Dictionary labels = null - ) { } + ) + { } } } diff --git a/src/Elastic.Apm/Model/Scanner.cs b/src/Elastic.Apm/Model/Scanner.cs index 3fcb21c1a..bb96f768a 100644 --- a/src/Elastic.Apm/Model/Scanner.cs +++ b/src/Elastic.Apm/Model/Scanner.cs @@ -106,14 +106,16 @@ public bool ScanToken(Token token) { if (t == token) return true; - if (t != Token.Comment) return false; + if (t != Token.Comment) + return false; } return false; } public Token Scan() { - if (!HasNext()) return Token.Eof; + if (!HasNext()) + return Token.Eof; var c = Next(); while (char.IsWhiteSpace(c) || _scannerFilter.Skip(this, c)) @@ -126,7 +128,8 @@ public Token Scan() _start = _pos - 1; if (c == '_' || char.IsLetter(c)) return ScanKeywordOrIdentifier(c != '_'); - if (char.IsDigit(c)) return ScanNumericLiteral(); + if (char.IsDigit(c)) + return ScanNumericLiteral(); switch (c) { @@ -176,7 +179,8 @@ public Token Scan() case '.': return Token.Period; case '$': - if (!HasNext()) return Token.Other; + if (!HasNext()) + return Token.Other; var nextC = Peek(); if (char.IsDigit(nextC)) @@ -237,11 +241,13 @@ private Token ScanKeywordOrIdentifier(bool maybeKeyword) var c = Peek(); if (char.IsDigit(c) || c == '_' || c == '$') maybeKeyword = false; - else if (!char.IsLetter(c)) break; + else if (!char.IsLetter(c)) + break; Next(); } - if (!maybeKeyword) return Token.Ident; + if (!maybeKeyword) + return Token.Ident; foreach (var token in TokenHelper.GetKeywordsByLength(TextLength())) { @@ -267,18 +273,21 @@ private Token ScanNumericLiteral() switch (c) { case '.': - if (hasPeriod) return Token.Number; + if (hasPeriod) + return Token.Number; Next(); hasPeriod = true; break; case 'e': case 'E': - if (hasExponent) return Token.Number; + if (hasExponent) + return Token.Number; Next(); hasExponent = true; - if (IsNextChar('+') || IsNextChar('-')) Next(); + if (IsNextChar('+') || IsNextChar('-')) + Next(); break; default: return Token.Number; @@ -370,7 +379,8 @@ private Token ScanBracketedComment() { Next(); nesting--; - if (nesting == 0) return Token.Comment; + if (nesting == 0) + return Token.Comment; } break; } diff --git a/src/Elastic.Apm/Model/SignatureParser.cs b/src/Elastic.Apm/Model/SignatureParser.cs index b87b55447..224385fcf 100644 --- a/src/Elastic.Apm/Model/SignatureParser.cs +++ b/src/Elastic.Apm/Model/SignatureParser.cs @@ -78,7 +78,8 @@ private void Parse(Scanner scanner, string query, StringBuilder signature, Strin { case Scanner.Token.Call: signature.Append("CALL"); - if (scanner.ScanUntil(Scanner.Token.Ident)) AppendIdentifiers(scanner, signature, dbLink); + if (scanner.ScanUntil(Scanner.Token.Ident)) + AppendIdentifiers(scanner, signature, dbLink); return; case Scanner.Token.Delete: signature.Append("DELETE"); @@ -151,7 +152,8 @@ private void Parse(Scanner scanner, string query, StringBuilder signature, Strin } else if (isDbLink) { - if (dbLink != null) scanner.AppendCurrentTokenText(dbLink); + if (dbLink != null) + scanner.AppendCurrentTokenText(dbLink); isDbLink = false; } // Two adjacent identifiers found after the first period. @@ -224,7 +226,8 @@ private void AppendIdentifiers(Scanner scanner, StringBuilder signature, StringB case Scanner.Token.Using: return; default: - if ("@".Equals(scanner.ToString())) isDbLink = true; + if ("@".Equals(scanner.ToString())) + isDbLink = true; break; } } diff --git a/src/Elastic.Apm/Model/Span.cs b/src/Elastic.Apm/Model/Span.cs index 5e3cfbcb8..3dbc44531 100644 --- a/src/Elastic.Apm/Model/Span.cs +++ b/src/Elastic.Apm/Model/Span.cs @@ -127,7 +127,7 @@ private Span(double duration, string id, string name, string parentId) this, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp, _parentSpan); } -// Disable obsolete-warning due to Configuration.SpanFramesMinDurationInMilliseconds access. + // Disable obsolete-warning due to Configuration.SpanFramesMinDurationInMilliseconds access. #pragma warning disable CS0618 // If the legacy setting (span_frames_min_duration) is present but the new // setting (span_stack_trace_min_duration) is not (or has a default value), the legacy setting dominates. @@ -137,9 +137,9 @@ private bool UseLegacyCaptureStackTraceSetting() // setting (span_stack_trace_min_duration) is not (or has a default value), the legacy setting dominates. const double tolerance = 0.00001; return Math.Abs(Configuration.SpanFramesMinDurationInMilliseconds - - ConfigConsts.DefaultValues.SpanFramesMinDurationInMilliseconds) > tolerance && - Math.Abs(Configuration.SpanStackTraceMinDurationInMilliseconds - - ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds) < tolerance; + ConfigConsts.DefaultValues.SpanFramesMinDurationInMilliseconds) > tolerance && + Math.Abs(Configuration.SpanStackTraceMinDurationInMilliseconds - + ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds) < tolerance; } internal bool IsCaptureStackTraceOnStartEnabled() @@ -160,12 +160,12 @@ internal bool IsCaptureStackTraceOnEndEnabled() if (UseLegacyCaptureStackTraceSetting()) { return Configuration.SpanFramesMinDurationInMilliseconds != 0 && - (Duration >= Configuration.SpanFramesMinDurationInMilliseconds || - Configuration.SpanFramesMinDurationInMilliseconds < 0); + (Duration >= Configuration.SpanFramesMinDurationInMilliseconds || + Configuration.SpanFramesMinDurationInMilliseconds < 0); } return Configuration.SpanStackTraceMinDurationInMilliseconds >= 0 && - Duration >= Configuration.SpanStackTraceMinDurationInMilliseconds; + Duration >= Configuration.SpanStackTraceMinDurationInMilliseconds; } return false; } @@ -594,7 +594,8 @@ private bool TryToCompress(Span sibling) private bool TryToCompressRegular(Span sibling) { - if (!IsSameKind(sibling)) return false; + if (!IsSameKind(sibling)) + return false; if (Name == sibling.Name) { @@ -943,7 +944,8 @@ internal class ChildDurationTimer /// public void OnChildStart(long startTimestamp) { - if (++_activeChildren == 1) _start = startTimestamp; + if (++_activeChildren == 1) + _start = startTimestamp; } /// @@ -952,7 +954,8 @@ public void OnChildStart(long startTimestamp) /// public void OnChildEnd(long endTimestamp) { - if (--_activeChildren == 0) IncrementDuration(endTimestamp); + if (--_activeChildren == 0) + IncrementDuration(endTimestamp); } /// diff --git a/src/Elastic.Apm/Model/Transaction.cs b/src/Elastic.Apm/Model/Transaction.cs index 4214ded4e..0093a70f2 100644 --- a/src/Elastic.Apm/Model/Transaction.cs +++ b/src/Elastic.Apm/Model/Transaction.cs @@ -68,7 +68,8 @@ internal class Transaction : ITransaction // This constructor is used only by tests that don't care about sampling and distributed tracing internal Transaction(ApmAgent agent, string name, string type, long? timestamp = null) : this(agent.Logger, name, type, new Sampler(1.0), null, agent.PayloadSender, agent.ConfigurationStore.CurrentSnapshot, - agent.TracerInternal.CurrentExecutionSegmentsContainer, null, null, timestamp: timestamp) { } + agent.TracerInternal.CurrentExecutionSegmentsContainer, null, null, timestamp: timestamp) + { } /// /// Creates a new transaction diff --git a/src/Elastic.Apm/Reflection/ExpressionBuilder.cs b/src/Elastic.Apm/Reflection/ExpressionBuilder.cs index e0837335c..94a98cced 100644 --- a/src/Elastic.Apm/Reflection/ExpressionBuilder.cs +++ b/src/Elastic.Apm/Reflection/ExpressionBuilder.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Linq.Expressions; using System.Reflection; @@ -10,7 +10,7 @@ namespace Elastic.Apm.Reflection { internal class ExpressionBuilder - { + { /// /// Builds a delegate to get a property of type from an object /// of type @@ -20,8 +20,8 @@ internal class ExpressionBuilder var parameterExpression = Expression.Parameter(typeof(TObject), "value"); var memberExpression = Expression.Property(parameterExpression, propertyName); return Expression.Lambda>(memberExpression, parameterExpression).Compile(); - } - + } + /// /// Builds a delegate to get a property from an object. is cast to , /// with the returned property cast to . @@ -33,8 +33,8 @@ internal class ExpressionBuilder var memberExpression = Expression.Property(parameterCastExpression, propertyInfo); var returnCastExpression = Expression.Convert(memberExpression, typeof(object)); return Expression.Lambda>(returnCastExpression, parameterExpression).Compile(); - } - + } + /// /// Builds a delegate to get a property from an object. is cast to , /// with the returned property cast to . @@ -46,8 +46,8 @@ internal class ExpressionBuilder var memberExpression = Expression.Field(parameterCastExpression, fieldInfo); var returnCastExpression = Expression.Convert(memberExpression, typeof(object)); return Expression.Lambda>(returnCastExpression, parameterExpression).Compile(); - } - + } + /// /// Builds a delegate to get a property from an object. is cast to , /// with the returned property cast to . diff --git a/src/Elastic.Apm/Reflection/PropertyFetcher.cs b/src/Elastic.Apm/Reflection/PropertyFetcher.cs index 36d4c432b..43b2e2892 100644 --- a/src/Elastic.Apm/Reflection/PropertyFetcher.cs +++ b/src/Elastic.Apm/Reflection/PropertyFetcher.cs @@ -27,7 +27,8 @@ public virtual object Fetch(object obj) { var type = obj.GetType().GetTypeInfo(); var property = type.DeclaredProperties.FirstOrDefault(p => string.Equals(p.Name, PropertyName, StringComparison.OrdinalIgnoreCase)); - if (property == null) property = type.GetProperty(PropertyName); + if (property == null) + property = type.GetProperty(PropertyName); _innerFetcher = PropertyFetch.FetcherForProperty(property); } diff --git a/src/Elastic.Apm/Reflection/PropertyFetcherCollection.cs b/src/Elastic.Apm/Reflection/PropertyFetcherCollection.cs index ab2a78f81..a61bc5913 100644 --- a/src/Elastic.Apm/Reflection/PropertyFetcherCollection.cs +++ b/src/Elastic.Apm/Reflection/PropertyFetcherCollection.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections; using System.Collections.Generic; namespace Elastic.Apm.Reflection -{ +{ /// /// A collection of property fetchers, used to retrieve property values /// from objects at runtime. diff --git a/src/Elastic.Apm/Report/IPayloadSender.cs b/src/Elastic.Apm/Report/IPayloadSender.cs index d91c38117..fe97a8fc7 100644 --- a/src/Elastic.Apm/Report/IPayloadSender.cs +++ b/src/Elastic.Apm/Report/IPayloadSender.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/Elastic.Apm/Report/Serialization/LabelsJsonConverter.cs b/src/Elastic.Apm/Report/Serialization/LabelsJsonConverter.cs index 2bac8640b..7ad7e93ba 100644 --- a/src/Elastic.Apm/Report/Serialization/LabelsJsonConverter.cs +++ b/src/Elastic.Apm/Report/Serialization/LabelsJsonConverter.cs @@ -4,8 +4,8 @@ using System; using Elastic.Apm.Helpers; -using Elastic.Apm.Model; using Elastic.Apm.Libraries.Newtonsoft.Json; +using Elastic.Apm.Model; namespace Elastic.Apm.Report.Serialization { diff --git a/src/Elastic.Apm/Report/Serialization/MetricSetConverter.cs b/src/Elastic.Apm/Report/Serialization/MetricSetConverter.cs index d05f246d8..6c22599ef 100644 --- a/src/Elastic.Apm/Report/Serialization/MetricSetConverter.cs +++ b/src/Elastic.Apm/Report/Serialization/MetricSetConverter.cs @@ -5,8 +5,8 @@ using System; using System.Collections.Generic; using Elastic.Apm.Api; -using Elastic.Apm.Metrics; using Elastic.Apm.Libraries.Newtonsoft.Json; +using Elastic.Apm.Metrics; namespace Elastic.Apm.Report.Serialization { @@ -17,7 +17,7 @@ public override void WriteJson(JsonWriter writer, MetricSet value, JsonSerialize writer.WriteStartObject(); if (value.Transaction != null) { - + writer.WritePropertyName("transaction"); writer.WriteStartObject(); diff --git a/src/Elastic.Apm/Report/Serialization/OutcomeConverter.cs b/src/Elastic.Apm/Report/Serialization/OutcomeConverter.cs index 86c6bb688..b6b62c2c9 100644 --- a/src/Elastic.Apm/Report/Serialization/OutcomeConverter.cs +++ b/src/Elastic.Apm/Report/Serialization/OutcomeConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; using Elastic.Apm.Api; using Elastic.Apm.Libraries.Newtonsoft.Json; @@ -20,7 +20,8 @@ public override Outcome ReadJson(JsonReader reader, Type objectType, Outcome exi { var property = (string)reader.Value; - if (Enum.TryParse(property, out var enumVal)) return enumVal; + if (Enum.TryParse(property, out var enumVal)) + return enumVal; } } diff --git a/src/Elastic.Apm/ServerInfo/ApmServerInfoProvider.cs b/src/Elastic.Apm/ServerInfo/ApmServerInfoProvider.cs index d0bed69b8..820ac8fe8 100644 --- a/src/Elastic.Apm/ServerInfo/ApmServerInfoProvider.cs +++ b/src/Elastic.Apm/ServerInfo/ApmServerInfoProvider.cs @@ -10,9 +10,9 @@ using System.Text; using System.Threading.Tasks; using Elastic.Apm.Config; -using Elastic.Apm.Logging; using Elastic.Apm.Libraries.Newtonsoft.Json; using Elastic.Apm.Libraries.Newtonsoft.Json.Linq; +using Elastic.Apm.Logging; namespace Elastic.Apm.ServerInfo { diff --git a/src/Elastic.Apm/ServerInfo/ElasticVersion.cs b/src/Elastic.Apm/ServerInfo/ElasticVersion.cs index d83a8683c..ce3979269 100644 --- a/src/Elastic.Apm/ServerInfo/ElasticVersion.cs +++ b/src/Elastic.Apm/ServerInfo/ElasticVersion.cs @@ -143,13 +143,16 @@ public int CompareByPrecedence(ElasticVersion other) return 1; var r = Major.CompareTo(other.Major); - if (r != 0) return r; + if (r != 0) + return r; r = Minor.CompareTo(other.Minor); - if (r != 0) return r; + if (r != 0) + return r; r = Patch.CompareTo(other.Patch); - if (r != 0) return r; + if (r != 0) + return r; r = CompareComponent(Prerelease, other.Prerelease, true); return r; @@ -182,7 +185,8 @@ private static int CompareComponent(string a, string b, bool lower = false) if (isanum && isbnum) { r = anum.CompareTo(bnum); - if (r != 0) return anum.CompareTo(bnum); + if (r != 0) + return anum.CompareTo(bnum); } else { diff --git a/src/azure/Elastic.Apm.Azure.CosmosDb/AzureCosmosDbDiagnosticsSubscriber.cs b/src/azure/Elastic.Apm.Azure.CosmosDb/AzureCosmosDbDiagnosticsSubscriber.cs index 7b8a9144b..d4033df21 100644 --- a/src/azure/Elastic.Apm.Azure.CosmosDb/AzureCosmosDbDiagnosticsSubscriber.cs +++ b/src/azure/Elastic.Apm.Azure.CosmosDb/AzureCosmosDbDiagnosticsSubscriber.cs @@ -1,18 +1,18 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using Elastic.Apm.DiagnosticSource; namespace Elastic.Apm.Azure.CosmosDb -{ +{ /// /// Subscribes to HTTP requests from Microsoft.Azure.Cosmos, Microsoft.Azure.DocumentDb, and Microsoft.Azure.DocumentDb.Core. /// public class AzureCosmosDbDiagnosticsSubscriber : IDiagnosticsSubscriber - { + { /// /// Subscribes to HTTP requests /// diff --git a/src/azure/Elastic.Apm.Azure.CosmosDb/AzureCosmosDbTracer.cs b/src/azure/Elastic.Apm.Azure.CosmosDb/AzureCosmosDbTracer.cs index f260df179..7386054b3 100644 --- a/src/azure/Elastic.Apm.Azure.CosmosDb/AzureCosmosDbTracer.cs +++ b/src/azure/Elastic.Apm.Azure.CosmosDb/AzureCosmosDbTracer.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/azure/Elastic.Apm.Azure.ServiceBus/AzureMessagingServiceBusDiagnosticListener.cs b/src/azure/Elastic.Apm.Azure.ServiceBus/AzureMessagingServiceBusDiagnosticListener.cs index f5aeaf880..d224bba37 100644 --- a/src/azure/Elastic.Apm.Azure.ServiceBus/AzureMessagingServiceBusDiagnosticListener.cs +++ b/src/azure/Elastic.Apm.Azure.ServiceBus/AzureMessagingServiceBusDiagnosticListener.cs @@ -405,7 +405,8 @@ private void PopulateLinks() current = current.Parent; } - if (current == null) return; + if (current == null) + return; // The type of Activity.Links got change across versions. @@ -439,7 +440,8 @@ void CollectSpanLinks(object links) var spanLinks = new List(); var iEnumerable = links as IEnumerable; - if (iEnumerable == null) return; + if (iEnumerable == null) + return; foreach (var link in iEnumerable) { diff --git a/src/azure/Elastic.Apm.Azure.ServiceBus/AzureMessagingServiceBusDiagnosticsSubscriber.cs b/src/azure/Elastic.Apm.Azure.ServiceBus/AzureMessagingServiceBusDiagnosticsSubscriber.cs index 6b3549ef1..e6c17f11f 100644 --- a/src/azure/Elastic.Apm.Azure.ServiceBus/AzureMessagingServiceBusDiagnosticsSubscriber.cs +++ b/src/azure/Elastic.Apm.Azure.ServiceBus/AzureMessagingServiceBusDiagnosticsSubscriber.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Diagnostics; using Elastic.Apm.DiagnosticSource; namespace Elastic.Apm.Azure.ServiceBus -{ +{ /// /// Subscribes to diagnostic source events from Azure.Messaging.ServiceBus /// public class AzureMessagingServiceBusDiagnosticsSubscriber : IDiagnosticsSubscriber - { + { /// /// Subscribes diagnostic source events. /// diff --git a/src/azure/Elastic.Apm.Azure.ServiceBus/MicrosoftAzureServiceBusDiagnosticListener.cs b/src/azure/Elastic.Apm.Azure.ServiceBus/MicrosoftAzureServiceBusDiagnosticListener.cs index 8dbd30236..cd266598a 100644 --- a/src/azure/Elastic.Apm.Azure.ServiceBus/MicrosoftAzureServiceBusDiagnosticListener.cs +++ b/src/azure/Elastic.Apm.Azure.ServiceBus/MicrosoftAzureServiceBusDiagnosticListener.cs @@ -37,7 +37,7 @@ internal class MicrosoftAzureServiceBusDiagnosticListener : DiagnosticListenerBa private readonly PropertyFetcherCollection _exceptionProperty = new PropertyFetcherCollection { "Exception", "Messages" }; - private readonly Framework _framework; + private readonly Framework _framework; public override string Name { get; } = "Microsoft.Azure.ServiceBus"; @@ -337,7 +337,7 @@ private void FillSpanLinks(PropertyFetcherCollection cachedProperties, IExecutio if (property.Key.Equals("Diagnostic-Id", StringComparison.InvariantCultureIgnoreCase)) { var parsedTraceParent = DistributedTracingData.TryDeserializeFromString(property.Value.ToString()); - if(parsedTraceParent != null) + if (parsedTraceParent != null) spanLinks.Add(new SpanLink(parsedTraceParent.ParentId, parsedTraceParent.TraceId)); } } @@ -347,9 +347,11 @@ private void FillSpanLinks(PropertyFetcherCollection cachedProperties, IExecutio switch (segment) { - case Model.Transaction t: t.InsertSpanLinkInternal(spanLinks); + case Model.Transaction t: + t.InsertSpanLinkInternal(spanLinks); break; - case Model.Span s: s.InsertSpanLinkInternal(spanLinks); + case Model.Span s: + s.InsertSpanLinkInternal(spanLinks); break; } } diff --git a/src/azure/Elastic.Apm.Azure.ServiceBus/MicrosoftAzureServiceBusDiagnosticsSubscriber.cs b/src/azure/Elastic.Apm.Azure.ServiceBus/MicrosoftAzureServiceBusDiagnosticsSubscriber.cs index 4615c94f6..2f5998a11 100644 --- a/src/azure/Elastic.Apm.Azure.ServiceBus/MicrosoftAzureServiceBusDiagnosticsSubscriber.cs +++ b/src/azure/Elastic.Apm.Azure.ServiceBus/MicrosoftAzureServiceBusDiagnosticsSubscriber.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Diagnostics; using Elastic.Apm.DiagnosticSource; namespace Elastic.Apm.Azure.ServiceBus -{ +{ /// /// Subscribes to diagnostic source events from Microsoft.Azure.ServiceBus /// public class MicrosoftAzureServiceBusDiagnosticsSubscriber : IDiagnosticsSubscriber - { + { /// /// Subscribes diagnostic source events. /// diff --git a/src/azure/Elastic.Apm.Azure.ServiceBus/ServiceBus.cs b/src/azure/Elastic.Apm.Azure.ServiceBus/ServiceBus.cs index 45c9a80cc..04b2e1d5f 100644 --- a/src/azure/Elastic.Apm.Azure.ServiceBus/ServiceBus.cs +++ b/src/azure/Elastic.Apm.Azure.ServiceBus/ServiceBus.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + namespace Elastic.Apm.Azure.ServiceBus { internal static class ServiceBus diff --git a/src/azure/Elastic.Apm.Azure.Storage/AzureBlobStorageDiagnosticListener.cs b/src/azure/Elastic.Apm.Azure.Storage/AzureBlobStorageDiagnosticListener.cs index 3b3f6ea93..524a365b8 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/AzureBlobStorageDiagnosticListener.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/AzureBlobStorageDiagnosticListener.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -19,8 +19,8 @@ internal static class AzureBlobStorage { internal const string SpanName = "AzureBlob"; internal const string SubType = "azureblob"; - } - + } + /// /// Creates transactions and spans for Azure Blob Storage diagnostic events from Azure.Storage.Blobs /// @@ -208,7 +208,8 @@ private void OnStart(KeyValuePair kv, string action) if (span is Span realSpan) realSpan.InstrumentationFlag = InstrumentationFlag.Azure; - if (blobUrl != null) SetDestination(span, blobUrl); + if (blobUrl != null) + SetDestination(span, blobUrl); if (!_processingSegments.TryAdd(activity.Id, span)) { diff --git a/src/azure/Elastic.Apm.Azure.Storage/AzureBlobStorageDiagnosticsSubscriber.cs b/src/azure/Elastic.Apm.Azure.Storage/AzureBlobStorageDiagnosticsSubscriber.cs index 353c97378..11465728a 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/AzureBlobStorageDiagnosticsSubscriber.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/AzureBlobStorageDiagnosticsSubscriber.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Diagnostics; using Elastic.Apm.DiagnosticSource; namespace Elastic.Apm.Azure.Storage -{ +{ /// /// Subscribes to diagnostic source events from Azure.Storage.Blobs and Microsoft.Azure.Storage.Blob /// public class AzureBlobStorageDiagnosticsSubscriber : IDiagnosticsSubscriber - { + { /// /// Subscribes diagnostic source events. /// diff --git a/src/azure/Elastic.Apm.Azure.Storage/AzureCoreDiagnosticListener.cs b/src/azure/Elastic.Apm.Azure.Storage/AzureCoreDiagnosticListener.cs index d1662c535..b6944daf2 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/AzureCoreDiagnosticListener.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/AzureCoreDiagnosticListener.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Diagnostics; @@ -11,7 +11,7 @@ using Elastic.Apm.Model; namespace Elastic.Apm.Azure.Storage -{ +{ /// /// Subscribes to Azure.Core events to set the url tag on parent activities. /// @@ -48,8 +48,8 @@ public void OnNext(KeyValuePair value) } } } - } - + } + /// /// Finds the target Azure activity to set the url tag on. /// Some Azure SDK versions and methods fire two activities with the same operation name for the same operation e.g. diff --git a/src/azure/Elastic.Apm.Azure.Storage/AzureFileShareStorageDiagnosticListener.cs b/src/azure/Elastic.Apm.Azure.Storage/AzureFileShareStorageDiagnosticListener.cs index 3ec480106..9acc861ae 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/AzureFileShareStorageDiagnosticListener.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/AzureFileShareStorageDiagnosticListener.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -19,8 +19,8 @@ internal static class AzureFileStorage { internal const string SpanName = "AzureFile"; internal const string SubType = "azurefile"; - } - + } + /// /// Creates transactions and spans for Azure File Share Storage diagnostic events from Azure.Storage.Files.Shares /// diff --git a/src/azure/Elastic.Apm.Azure.Storage/AzureFileShareStorageDiagnosticsSubscriber.cs b/src/azure/Elastic.Apm.Azure.Storage/AzureFileShareStorageDiagnosticsSubscriber.cs index dd5306af1..b364f82a2 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/AzureFileShareStorageDiagnosticsSubscriber.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/AzureFileShareStorageDiagnosticsSubscriber.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Diagnostics; using Elastic.Apm.DiagnosticSource; namespace Elastic.Apm.Azure.Storage -{ +{ /// /// Subscribes to diagnostic source events from Azure.Storage.Files.Shares /// public class AzureFileShareStorageDiagnosticsSubscriber : IDiagnosticsSubscriber - { + { /// /// Subscribes diagnostic source events. /// diff --git a/src/azure/Elastic.Apm.Azure.Storage/AzureQueueStorageDiagnosticListener.cs b/src/azure/Elastic.Apm.Azure.Storage/AzureQueueStorageDiagnosticListener.cs index 5d239a1e1..28d6a3d58 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/AzureQueueStorageDiagnosticListener.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/AzureQueueStorageDiagnosticListener.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -20,8 +20,8 @@ internal static class AzureQueueStorage { internal const string SpanName = "AzureQueue"; internal const string SubType = "azurequeue"; - } - + } + /// /// Creates transactions and spans for Azure Queue Storage diagnostic events from Azure.Storage.Queues /// @@ -144,17 +144,17 @@ private void OnReceiveStart(KeyValuePair kv) { Logger.Trace()?.Log("Value is not an activity - exiting"); return; - } - - - // if we're already processing this activity, ignore it. + } + + + // if we're already processing this activity, ignore it. if (_processingSegments.ContainsKey(activity.Id)) - return; - - // Newer versions of the Queue storage library fire two QueueClient.ReceiveMessage.Start events. - // In order to avoid creating two transactions, check if the parent activity is an APM transaction and if it is, - // check its parent activity to see if it is the same operation as this one. If it is, don't create a transaction - // for it. + return; + + // Newer versions of the Queue storage library fire two QueueClient.ReceiveMessage.Start events. + // In order to avoid creating two transactions, check if the parent activity is an APM transaction and if it is, + // check its parent activity to see if it is the same operation as this one. If it is, don't create a transaction + // for it. var parentActivity = activity.Parent; if (parentActivity != null && parentActivity.OperationName == Transaction.ApmTransactionActivityName) @@ -177,9 +177,9 @@ private void OnReceiveStart(KeyValuePair kv) : $"{AzureQueueStorage.SpanName} RECEIVE from {queueName}"; var transaction = ApmAgent.Tracer.StartTransaction(transactionName, ApiConstants.TypeMessaging); - transaction.Context.Service = new Service(null, null) { Framework = _framework }; - - // transaction creation will create an activity, so use this as the key. + transaction.Context.Service = new Service(null, null) { Framework = _framework }; + + // transaction creation will create an activity, so use this as the key. var activityId = Activity.Current.Id; if (!_processingSegments.TryAdd(activityId, transaction)) @@ -234,9 +234,9 @@ private void OnStop() { var urlTag = activity.Tags.FirstOrDefault(t => t.Key == "url").Value; if (QueueUrl.TryCreate(urlTag, out var queueUrl) && !string.IsNullOrEmpty(queueUrl.QueueName)) - { - // if destination wasn't set in the Start, we didn't get a chance to see if this - // is a queue that should be ignored, so check now. + { + // if destination wasn't set in the Start, we didn't get a chance to see if this + // is a queue that should be ignored, so check now. if (MatchesIgnoreMessageQueues(queueUrl.QueueName)) return; @@ -249,9 +249,9 @@ private void OnStop() { var urlTag = activity.Parent?.Tags.FirstOrDefault(t => t.Key == "url").Value; if (QueueUrl.TryCreate(urlTag, out var queueUrl) && !string.IsNullOrEmpty(queueUrl.QueueName)) - { - // if destination wasn't set in the Start, we didn't get a chance to see if this - // is a queue that should be ignored, so check now. + { + // if destination wasn't set in the Start, we didn't get a chance to see if this + // is a queue that should be ignored, so check now. if (MatchesIgnoreMessageQueues(queueUrl.QueueName)) return; @@ -288,10 +288,10 @@ private void OnException(KeyValuePair kv) { if (!string.IsNullOrEmpty(queueUrl.QueueName)) { - span.Name += $" to {queueUrl.QueueName}"; - - // if destination wasn't set in the Start, we didn't get a chance to see if this - // is a queue that should be ignored, so check now. + span.Name += $" to {queueUrl.QueueName}"; + + // if destination wasn't set in the Start, we didn't get a chance to see if this + // is a queue that should be ignored, so check now. if (MatchesIgnoreMessageQueues(queueUrl.QueueName)) return; } @@ -304,9 +304,9 @@ private void OnException(KeyValuePair kv) { var urlTag = activity.Parent?.Tags.FirstOrDefault(t => t.Key == "url").Value; if (QueueUrl.TryCreate(urlTag, out var queueUrl) && !string.IsNullOrEmpty(queueUrl.QueueName)) - { - // if destination wasn't set in the Start, we didn't get a chance to see if this - // is a queue that should be ignored, so check now. + { + // if destination wasn't set in the Start, we didn't get a chance to see if this + // is a queue that should be ignored, so check now. if (MatchesIgnoreMessageQueues(queueUrl.QueueName)) return; @@ -319,8 +319,8 @@ private void OnException(KeyValuePair kv) segment.Outcome = Outcome.Failure; segment.End(); - } - + } + /// /// Working with a queue url to extract the queue name and address. /// diff --git a/src/azure/Elastic.Apm.Azure.Storage/AzureQueueStorageDiagnosticsSubscriber.cs b/src/azure/Elastic.Apm.Azure.Storage/AzureQueueStorageDiagnosticsSubscriber.cs index 01bb9320b..556632894 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/AzureQueueStorageDiagnosticsSubscriber.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/AzureQueueStorageDiagnosticsSubscriber.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Diagnostics; using Elastic.Apm.DiagnosticSource; namespace Elastic.Apm.Azure.Storage -{ +{ /// /// Subscribes to diagnostic source events from Azure.Storage.Queues /// public class AzureQueueStorageDiagnosticsSubscriber : IDiagnosticsSubscriber - { + { /// /// Subscribes diagnostic source events. /// diff --git a/src/azure/Elastic.Apm.Azure.Storage/BlobUrl.cs b/src/azure/Elastic.Apm.Azure.Storage/BlobUrl.cs index 8a6c86f55..69b410615 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/BlobUrl.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/BlobUrl.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; namespace Elastic.Apm.Azure.Storage diff --git a/src/azure/Elastic.Apm.Azure.Storage/FileShareUrl.cs b/src/azure/Elastic.Apm.Azure.Storage/FileShareUrl.cs index 61ba164c0..c5323c59e 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/FileShareUrl.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/FileShareUrl.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; namespace Elastic.Apm.Azure.Storage diff --git a/src/azure/Elastic.Apm.Azure.Storage/MicrosoftAzureBlobStorageTracer.cs b/src/azure/Elastic.Apm.Azure.Storage/MicrosoftAzureBlobStorageTracer.cs index 1c5b5a5b0..7c1c5d132 100644 --- a/src/azure/Elastic.Apm.Azure.Storage/MicrosoftAzureBlobStorageTracer.cs +++ b/src/azure/Elastic.Apm.Azure.Storage/MicrosoftAzureBlobStorageTracer.cs @@ -1,15 +1,15 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using Elastic.Apm.Api; using Elastic.Apm.DiagnosticListeners; using Elastic.Apm.Model; namespace Elastic.Apm.Azure.Storage -{ +{ /// /// Creates HTTP spans wth Azure Blob storage details from Microsoft.Azure.Storage.Blob /// diff --git a/src/instrumentations/Elastic.Apm.Elasticsearch/ElasticsearchDiagnosticsListenerBase.cs b/src/instrumentations/Elastic.Apm.Elasticsearch/ElasticsearchDiagnosticsListenerBase.cs index 1d22bd5d2..34aab1312 100644 --- a/src/instrumentations/Elastic.Apm.Elasticsearch/ElasticsearchDiagnosticsListenerBase.cs +++ b/src/instrumentations/Elastic.Apm.Elasticsearch/ElasticsearchDiagnosticsListenerBase.cs @@ -62,7 +62,8 @@ internal bool TryStartElasticsearchSpan(string name, out Span span, Uri instance SetDestination(span, instanceUri); var id = Activity.Current.Id; - if (Spans.TryAdd(id, span)) return true; + if (Spans.TryAdd(id, span)) + return true; Logger.Error()?.Log("Failed to register start of span in ConcurrentDictionary {SpanDetails}", span.ToString()); span = null; @@ -95,7 +96,8 @@ internal bool TryGetCurrentElasticsearchSpan(out Span span, Uri instance = null) private static void SetDbContext(ISpan span, Uri instance) { var instanceUriString = instance?.ToString(); - if (span.Context.Db?.Instance != null || instanceUriString == null) return; + if (span.Context.Db?.Instance != null || instanceUriString == null) + return; span.Context.Db = new Database { Instance = instanceUriString, Type = Database.TypeElasticsearch }; } diff --git a/src/instrumentations/Elastic.Apm.Elasticsearch/ElasticsearchDiagnosticsSubscriber.cs b/src/instrumentations/Elastic.Apm.Elasticsearch/ElasticsearchDiagnosticsSubscriber.cs index 160e02bc1..aff7ae949 100644 --- a/src/instrumentations/Elastic.Apm.Elasticsearch/ElasticsearchDiagnosticsSubscriber.cs +++ b/src/instrumentations/Elastic.Apm.Elasticsearch/ElasticsearchDiagnosticsSubscriber.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/instrumentations/Elastic.Apm.Elasticsearch/HttpConnectionDiagnosticsListener.cs b/src/instrumentations/Elastic.Apm.Elasticsearch/HttpConnectionDiagnosticsListener.cs index 056b316d2..907c546c6 100644 --- a/src/instrumentations/Elastic.Apm.Elasticsearch/HttpConnectionDiagnosticsListener.cs +++ b/src/instrumentations/Elastic.Apm.Elasticsearch/HttpConnectionDiagnosticsListener.cs @@ -21,7 +21,8 @@ public class HttpConnectionDiagnosticsListener : ElasticsearchDiagnosticsListene private void OnResult(string @event, int? statusCode) { - if (!TryGetCurrentElasticsearchSpan(out var span)) return; + if (!TryGetCurrentElasticsearchSpan(out var span)) + return; span.Name += $" ({statusCode})"; Logger.Info()?.Log("Received an {Event} event from elasticsearch", @event); @@ -33,7 +34,8 @@ private void OnResult(string @event, int? statusCode) private void OnRequestData(string @event, RequestData requestData) { var name = ToName(@event); - if (requestData == null) return; + if (requestData == null) + return; var instanceUri = requestData.Node?.Uri; if (TryStartElasticsearchSpan(name, out var span, instanceUri)) diff --git a/src/instrumentations/Elastic.Apm.Elasticsearch/RequestPipelineDiagnosticsListener.cs b/src/instrumentations/Elastic.Apm.Elasticsearch/RequestPipelineDiagnosticsListener.cs index 9d6363754..1b5f47a7b 100644 --- a/src/instrumentations/Elastic.Apm.Elasticsearch/RequestPipelineDiagnosticsListener.cs +++ b/src/instrumentations/Elastic.Apm.Elasticsearch/RequestPipelineDiagnosticsListener.cs @@ -34,7 +34,8 @@ public class RequestPipelineDiagnosticsListener : ElasticsearchDiagnosticsListen private void OnResult(string @event, IApiCallDetails response) { - if (!TryGetCurrentElasticsearchSpan(out var span)) return; + if (!TryGetCurrentElasticsearchSpan(out var span)) + return; if (response != null) { @@ -64,7 +65,8 @@ private static void RegisterStatement(ISpan span, IApiCallDetails response) //make sure db exists var db = span.Context.Db ?? (span.Context.Db = new Database { - Instance = response.Uri?.GetLeftPart(UriPartial.Authority), Type = Database.TypeElasticsearch + Instance = response.Uri?.GetLeftPart(UriPartial.Authority), + Type = Database.TypeElasticsearch }); db.Statement = response.DebugInformation; @@ -72,7 +74,8 @@ private static void RegisterStatement(ISpan span, IApiCallDetails response) private static void RegisterError(ISpan span, IApiCallDetails response) { - if (response.Success) return; + if (response.Success) + return; var exception = response.OriginalException ?? response.AuditTrail.FirstOrDefault(a => a.Exception != null)?.Exception; var f = PipelineFailure.Unexpected; @@ -112,12 +115,15 @@ private static void RegisterError(ISpan span, IApiCallDetails response) } } - if (exception == null && !causeOnServer) return; - if (causeOnServer && string.IsNullOrEmpty(message)) return; + if (exception == null && !causeOnServer) + return; + if (causeOnServer && string.IsNullOrEmpty(message)) + return; if (causeOnServer) span.CaptureError(message, culprit, stackFrames); - else span.CaptureException(exception); + else + span.CaptureException(exception); } private void OnRequestData(string @event, RequestData requestData) diff --git a/src/instrumentations/Elastic.Apm.Elasticsearch/SerializerDiagnosticsListener .cs b/src/instrumentations/Elastic.Apm.Elasticsearch/SerializerDiagnosticsListener .cs index 6a13c302b..778541a76 100644 --- a/src/instrumentations/Elastic.Apm.Elasticsearch/SerializerDiagnosticsListener .cs +++ b/src/instrumentations/Elastic.Apm.Elasticsearch/SerializerDiagnosticsListener .cs @@ -22,7 +22,8 @@ private void OnSerializer(string @event, SerializerRegistrationInformation seria // - script parameters // - script values // This is too granular of information for tracing and is more there to aid profiling. - if (serializerInfo.Purpose != "request/response") return; + if (serializerInfo.Purpose != "request/response") + return; var name = ToName(@event); diff --git a/src/instrumentations/Elastic.Apm.EntityFramework6/Ef6Interceptor.cs b/src/instrumentations/Elastic.Apm.EntityFramework6/Ef6Interceptor.cs index 3f453cb14..066520a10 100644 --- a/src/instrumentations/Elastic.Apm.EntityFramework6/Ef6Interceptor.cs +++ b/src/instrumentations/Elastic.Apm.EntityFramework6/Ef6Interceptor.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -62,7 +62,8 @@ private Impl CreateImplIfReadyAndNoConflict() return null; // Make sure DB spans were not already captured - if (!(Agent.Tracer.CurrentSpan is Span span)) return impl; + if (!(Agent.Tracer.CurrentSpan is Span span)) + return impl; return span.InstrumentationFlag == InstrumentationFlag.SqlClient ? null : impl; } diff --git a/src/instrumentations/Elastic.Apm.EntityFrameworkCore/EfCoreDiagnosticListener.cs b/src/instrumentations/Elastic.Apm.EntityFrameworkCore/EfCoreDiagnosticListener.cs index 9c6c8b058..dc7dd1310 100644 --- a/src/instrumentations/Elastic.Apm.EntityFrameworkCore/EfCoreDiagnosticListener.cs +++ b/src/instrumentations/Elastic.Apm.EntityFrameworkCore/EfCoreDiagnosticListener.cs @@ -1,7 +1,7 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -24,8 +24,8 @@ internal class EfCoreDiagnosticListener : DiagnosticListenerBase public override string Name => "Microsoft.EntityFrameworkCore"; protected override void HandleOnNext(KeyValuePair kv) - { - // check for competing instrumentation + { + // check for competing instrumentation if (_agent?.TracerInternal.CurrentSpan is Span { InstrumentationFlag: InstrumentationFlag.SqlClient }) return; diff --git a/src/instrumentations/Elastic.Apm.EntityFrameworkCore/EfCoreDiagnosticsSubscriber.cs b/src/instrumentations/Elastic.Apm.EntityFrameworkCore/EfCoreDiagnosticsSubscriber.cs index bae517de8..ba6004eee 100644 --- a/src/instrumentations/Elastic.Apm.EntityFrameworkCore/EfCoreDiagnosticsSubscriber.cs +++ b/src/instrumentations/Elastic.Apm.EntityFrameworkCore/EfCoreDiagnosticsSubscriber.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/instrumentations/Elastic.Apm.GrpcClient/GrpcClientDiagnosticListener.cs b/src/instrumentations/Elastic.Apm.GrpcClient/GrpcClientDiagnosticListener.cs index 93879dade..3d2c44049 100644 --- a/src/instrumentations/Elastic.Apm.GrpcClient/GrpcClientDiagnosticListener.cs +++ b/src/instrumentations/Elastic.Apm.GrpcClient/GrpcClientDiagnosticListener.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/instrumentations/Elastic.Apm.GrpcClient/GrpcClientDiagnosticSubscriber.cs b/src/instrumentations/Elastic.Apm.GrpcClient/GrpcClientDiagnosticSubscriber.cs index 2bb40cc1f..39afc01eb 100644 --- a/src/instrumentations/Elastic.Apm.GrpcClient/GrpcClientDiagnosticSubscriber.cs +++ b/src/instrumentations/Elastic.Apm.GrpcClient/GrpcClientDiagnosticSubscriber.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/instrumentations/Elastic.Apm.MongoDb/MongoDbDiagnosticsSubscriber.cs b/src/instrumentations/Elastic.Apm.MongoDb/MongoDbDiagnosticsSubscriber.cs index d4d5dc0e6..3b6a401f4 100644 --- a/src/instrumentations/Elastic.Apm.MongoDb/MongoDbDiagnosticsSubscriber.cs +++ b/src/instrumentations/Elastic.Apm.MongoDb/MongoDbDiagnosticsSubscriber.cs @@ -1,4 +1,4 @@ -// Based on the elastic-apm-mongo project by Vadim Hatsura (@vhatsura) +// Based on the elastic-apm-mongo project by Vadim Hatsura (@vhatsura) // https://github.com/vhatsura/elastic-apm-mongo // Licensed to Elasticsearch B.V under the Apache 2.0 License. // Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. diff --git a/src/instrumentations/Elastic.Apm.SqlClient/SqlClientDiagnosticListener.cs b/src/instrumentations/Elastic.Apm.SqlClient/SqlClientDiagnosticListener.cs index b538500f9..526c52ec5 100644 --- a/src/instrumentations/Elastic.Apm.SqlClient/SqlClientDiagnosticListener.cs +++ b/src/instrumentations/Elastic.Apm.SqlClient/SqlClientDiagnosticListener.cs @@ -40,7 +40,8 @@ protected override void HandleOnNext(KeyValuePair value) return; } - if (!value.Key.StartsWith("Microsoft.Data.SqlClient.") && !value.Key.StartsWith("System.Data.SqlClient.")) return; + if (!value.Key.StartsWith("Microsoft.Data.SqlClient.") && !value.Key.StartsWith("System.Data.SqlClient.")) + return; switch (value.Key) { @@ -82,7 +83,8 @@ private void HandleStopCommand(object payloadData, PropertyFetcherSet propertyFe if (propertyFetcherSet.StopCorrelationId.Fetch(payloadData) is Guid operationId && propertyFetcherSet.StopCommand.Fetch(payloadData) is IDbCommand dbCommand) { - if (!_spans.TryRemove(operationId, out var span)) return; + if (!_spans.TryRemove(operationId, out var span)) + return; _agent?.TracerInternal.DbSpanCommon.EndSpan(span, dbCommand, Outcome.Success); } @@ -100,9 +102,11 @@ private void HandleErrorCommand(object payloadData, PropertyFetcherSet propertyF { if (propertyFetcherSet.ErrorCorrelationId.Fetch(payloadData) is Guid operationId) { - if (!_spans.TryRemove(operationId, out var span)) return; + if (!_spans.TryRemove(operationId, out var span)) + return; - if (propertyFetcherSet.Exception.Fetch(payloadData) is Exception exception) span.CaptureException(exception); + if (propertyFetcherSet.Exception.Fetch(payloadData) is Exception exception) + span.CaptureException(exception); if (propertyFetcherSet.ErrorCommand.Fetch(payloadData) is IDbCommand dbCommand) _agent?.TracerInternal.DbSpanCommon.EndSpan(span, dbCommand, Outcome.Failure); diff --git a/src/instrumentations/Elastic.Apm.SqlClient/SqlClientDiagnosticSubscriber.cs b/src/instrumentations/Elastic.Apm.SqlClient/SqlClientDiagnosticSubscriber.cs index 8be88972f..c5c38d631 100644 --- a/src/instrumentations/Elastic.Apm.SqlClient/SqlClientDiagnosticSubscriber.cs +++ b/src/instrumentations/Elastic.Apm.SqlClient/SqlClientDiagnosticSubscriber.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/instrumentations/Elastic.Apm.SqlClient/SqlEventListener.cs b/src/instrumentations/Elastic.Apm.SqlClient/SqlEventListener.cs index a0bcce278..269cc6971 100644 --- a/src/instrumentations/Elastic.Apm.SqlClient/SqlEventListener.cs +++ b/src/instrumentations/Elastic.Apm.SqlClient/SqlEventListener.cs @@ -47,7 +47,8 @@ protected override void OnEventSourceCreated(EventSource eventSource) protected override void OnEventWritten(EventWrittenEventArgs eventData) { - if (eventData?.Payload == null) return; + if (eventData?.Payload == null) + return; // Check for competing instrumentation if (_apmAgent.TracerInternal.CurrentSpan is Span span) @@ -103,7 +104,8 @@ private void ProcessBeginExecute(IReadOnlyList payload) var span = ExecutionSegmentCommon.StartSpanOnCurrentExecutionSegment(_apmAgent, spanName, ApiConstants.TypeDb, ApiConstants.SubtypeMssql, InstrumentationFlag.SqlClient, isExitSpan: true); - if (span == null) return; + if (span == null) + return; if (_processingSpans.TryAdd(id, (span, start))) { diff --git a/src/instrumentations/Elastic.Apm.StackExchange.Redis/ConnectionMultiplexerExtensions.cs b/src/instrumentations/Elastic.Apm.StackExchange.Redis/ConnectionMultiplexerExtensions.cs index 410989013..b96e2ca22 100644 --- a/src/instrumentations/Elastic.Apm.StackExchange.Redis/ConnectionMultiplexerExtensions.cs +++ b/src/instrumentations/Elastic.Apm.StackExchange.Redis/ConnectionMultiplexerExtensions.cs @@ -1,12 +1,12 @@ -using StackExchange.Redis; +using StackExchange.Redis; namespace Elastic.Apm.StackExchange.Redis -{ +{ /// /// Extension methods for /// public static class ConnectionMultiplexerExtensions - { + { /// /// Register Elastic APM .NET Agent to capture profiled commands sent to redis /// @@ -16,8 +16,8 @@ public static void UseElasticApm(this IConnectionMultiplexer connection, IApmAge { var profiler = new ElasticApmProfiler(() => agent); connection.RegisterProfiler(profiler.GetProfilingSession); - } - + } + /// /// Register Elastic APM .NET Agent to capture profiled commands sent to redis /// diff --git a/src/instrumentations/Elastic.Apm.StackExchange.Redis/ElasticApmProfiler.cs b/src/instrumentations/Elastic.Apm.StackExchange.Redis/ElasticApmProfiler.cs index 70b5ff937..8db88cfe0 100644 --- a/src/instrumentations/Elastic.Apm.StackExchange.Redis/ElasticApmProfiler.cs +++ b/src/instrumentations/Elastic.Apm.StackExchange.Redis/ElasticApmProfiler.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Concurrent; using System.Globalization; @@ -16,7 +16,7 @@ using StackExchange.Redis.Profiling; namespace Elastic.Apm.StackExchange.Redis -{ +{ /// /// Captures redis commands sent with StackExchange.Redis client /// @@ -27,8 +27,8 @@ public class ElasticApmProfiler private readonly Lazy _logger; private readonly Lazy _agent; - private static readonly Func MessageFetcher; - private static readonly Func CommandAndKeyFetcher; + private static readonly Func MessageFetcher; + private static readonly Func CommandAndKeyFetcher; private static readonly Type _profiledCommandType; static ElasticApmProfiler() @@ -51,8 +51,8 @@ public ElasticApmProfiler(Func agentGetter) { _agent = new Lazy(agentGetter); _logger = new Lazy(() => _agent.Value.Logger.Scoped(nameof(ElasticApmProfiler))); - } - + } + /// /// Gets a profiling session for StackExchange.Redis to add redis commands to. /// Creates a profiling session per span or transaction @@ -68,9 +68,9 @@ public ProfilingSession GetProfilingSession() var executionSegment = _agent.Value.GetCurrentExecutionSegment(); var realSpan = executionSegment as Span; - Transaction realTransaction = null; - - // don't profile when there's no real span or transaction + Transaction realTransaction = null; + + // don't profile when there's no real span or transaction if (realSpan is null) { realTransaction = executionSegment as Transaction; @@ -119,9 +119,9 @@ private void EndProfilingSession(object sender, ProfilingSession session) segmentType = "span"; try - { - // Remove the session. Use session passed to EndProfilingSession rather than the removed session in the event - // there was an issue in adding or removing the session + { + // Remove the session. Use session passed to EndProfilingSession rather than the removed session in the event + // there was an issue in adding or removing the session if (!_executionSegmentSessions.TryRemove(executionSegment.Id, out _)) { _logger.Value.Debug()?.Log( @@ -134,7 +134,8 @@ private void EndProfilingSession(object sender, ProfilingSession session) "Finished profiling session for {ExecutionSegment}. Collected {ProfiledCommandCount} commands", executionSegment, profiledCommands.Count()); - foreach (var profiledCommand in profiledCommands) ProcessCommand(profiledCommand, executionSegment); + foreach (var profiledCommand in profiledCommands) + ProcessCommand(profiledCommand, executionSegment); _logger.Value.Trace()?.Log( "End profiling session for {ExecutionSegment} {Id}", @@ -180,19 +181,19 @@ private static void ProcessCommand(IProfiledCommand profiledCommand, IExecutionS } if (address != null) - span.Context.Destination = new Destination { Address = address, Port = port }; - - // update the timestamp to reflect the point at which the command was created + span.Context.Destination = new Destination { Address = address, Port = port }; + + // update the timestamp to reflect the point at which the command was created if (span is Span realSpan) realSpan.Timestamp = TimeUtils.ToTimestamp(profiledCommand.CommandCreated); - span.Duration = profiledCommand.ElapsedTime.TotalMilliseconds; - - // profiled commands are always successful - span.Outcome = Outcome.Success; - - // TODO: clear the raw stacktrace as it won't be representative of the call stack at - // the point at which the call to redis happens, and therefore misleading to include + span.Duration = profiledCommand.ElapsedTime.TotalMilliseconds; + + // profiled commands are always successful + span.Outcome = Outcome.Success; + + // TODO: clear the raw stacktrace as it won't be representative of the call stack at + // the point at which the call to redis happens, and therefore misleading to include }, ApiConstants.SubTypeRedis, "query", true); } diff --git a/src/integrations/Elastic.Apm.AspNetCore/ApmMiddleware.cs b/src/integrations/Elastic.Apm.AspNetCore/ApmMiddleware.cs index 308ea4c33..11e629246 100644 --- a/src/integrations/Elastic.Apm.AspNetCore/ApmMiddleware.cs +++ b/src/integrations/Elastic.Apm.AspNetCore/ApmMiddleware.cs @@ -1,7 +1,7 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Threading.Tasks; using Elastic.Apm.Api; @@ -11,8 +11,8 @@ using Microsoft.AspNetCore.Http; namespace Elastic.Apm.AspNetCore -{ - // ReSharper disable once ClassNeverInstantiated.Global +{ + // ReSharper disable once ClassNeverInstantiated.Global internal class ApmMiddleware { private readonly IApmLogger _logger; @@ -46,15 +46,15 @@ public async Task InvokeAsync(HttpContext context) } catch (Exception e) when (CaptureExceptionAndRequestBody(e, context, transaction)) { } finally - { - // In case an error handler middleware is registered, the catch block above won't be executed, because the - // error handler handles all the exceptions - in this case, based on the response code and the config, we may capture the body here + { + // In case an error handler middleware is registered, the catch block above won't be executed, because the + // error handler handles all the exceptions - in this case, based on the response code and the config, we may capture the body here if (transaction != null && transaction.IsContextCreated && context?.Response.StatusCode >= 400 && transaction.Context?.Request?.Body is string body && (string.IsNullOrEmpty(body) || body == Apm.Consts.Redacted)) transaction.CollectRequestBody(true, new AspNetCoreHttpRequest(context.Request), _logger); - if(transaction != null) + if (transaction != null) WebRequestTransactionCreator.StopTransaction(transaction, context, _logger); else createdTransaction?.End(); diff --git a/src/integrations/Elastic.Apm.AspNetCore/ApmMiddlewareExtension.cs b/src/integrations/Elastic.Apm.AspNetCore/ApmMiddlewareExtension.cs index 9b37d666d..717124e8e 100644 --- a/src/integrations/Elastic.Apm.AspNetCore/ApmMiddlewareExtension.cs +++ b/src/integrations/Elastic.Apm.AspNetCore/ApmMiddlewareExtension.cs @@ -1,7 +1,7 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; @@ -19,7 +19,7 @@ namespace Elastic.Apm.AspNetCore { public static class ApmMiddlewareExtension - { + { /// /// Adds the Elastic APM Middleware to the ASP.NET Core pipeline. /// You can customize the agent by passing additional IDiagnosticsSubscriber components to this method. @@ -54,9 +54,9 @@ public static class ApmMiddlewareExtension : new ApmConfiguration(configuration, logger, builder.ApplicationServices.GetEnvironmentName()) as IConfigurationReader; var config = new AgentComponents(configurationReader: configReader, logger: logger); - HostBuilderExtensions.UpdateServiceInformation(config.Service); - - // Agent.Setup must be called, even if agent is disabled. This way static public API usage won't implicitly initialize an agent with default values, instead, this will be reused. + HostBuilderExtensions.UpdateServiceInformation(config.Service); + + // Agent.Setup must be called, even if agent is disabled. This way static public API usage won't implicitly initialize an agent with default values, instead, this will be reused. Agent.Setup(config); return UseElasticApm(builder, Agent.Instance, logger, subscribers); @@ -87,15 +87,15 @@ public static class ApmMiddlewareExtension return builder.UseMiddleware(agent.Tracer, agent); } - private static string GetEnvironmentName(this IServiceProvider serviceProvider) => + private static string GetEnvironmentName(this IServiceProvider serviceProvider) => #if NET6_0_OR_GREATER (serviceProvider.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment)?.EnvironmentName; #else #pragma warning disable CS0246 - (serviceProvider.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment)?.EnvironmentName; + (serviceProvider.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment)?.EnvironmentName; #pragma warning restore CS0246 #endif - + internal static IApmLogger GetApmLogger(this IServiceProvider serviceProvider) => serviceProvider.GetService(typeof(ILoggerFactory)) is ILoggerFactory loggerFactory ? new NetCoreLogger(loggerFactory) diff --git a/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreDiagnosticListener.cs b/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreDiagnosticListener.cs index 7b1d769ba..a5972a094 100644 --- a/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreDiagnosticListener.cs +++ b/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreDiagnosticListener.cs @@ -76,9 +76,12 @@ protected override void HandleOnNext(KeyValuePair kv) { case "Microsoft.AspNetCore.Diagnostics.UnhandledException": //Called when exception handler is registered case "Microsoft.AspNetCore.Diagnostics.HandledException": - if (!(_defaultHttpContextFetcher.Fetch(kv.Value) is DefaultHttpContext httpContextDiagnosticsUnhandledException)) return; - if (!(_exceptionContextPropertyFetcher.Fetch(kv.Value) is Exception diagnosticsException)) return; - if (!ProcessingRequests.TryGetValue(httpContextDiagnosticsUnhandledException, out var iDiagnosticsTransaction)) return; + if (!(_defaultHttpContextFetcher.Fetch(kv.Value) is DefaultHttpContext httpContextDiagnosticsUnhandledException)) + return; + if (!(_exceptionContextPropertyFetcher.Fetch(kv.Value) is Exception diagnosticsException)) + return; + if (!ProcessingRequests.TryGetValue(httpContextDiagnosticsUnhandledException, out var iDiagnosticsTransaction)) + return; if (iDiagnosticsTransaction is Transaction diagnosticsTransaction) { @@ -88,9 +91,12 @@ protected override void HandleOnNext(KeyValuePair kv) break; case "Microsoft.AspNetCore.Hosting.UnhandledException": // Not called when exception handler registered - if (!(_hostDefaultHttpContextFetcher.Fetch(kv.Value) is DefaultHttpContext httpContextUnhandledException)) return; - if (!(_hostExceptionContextPropertyFetcher.Fetch(kv.Value) is Exception exception)) return; - if (!ProcessingRequests.TryGetValue(httpContextUnhandledException, out var iCurrentTransaction)) return; + if (!(_hostDefaultHttpContextFetcher.Fetch(kv.Value) is DefaultHttpContext httpContextUnhandledException)) + return; + if (!(_hostExceptionContextPropertyFetcher.Fetch(kv.Value) is Exception exception)) + return; + if (!ProcessingRequests.TryGetValue(httpContextUnhandledException, out var iCurrentTransaction)) + return; if (iCurrentTransaction is Transaction currentTransaction) { diff --git a/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreErrorDiagnosticListener.cs b/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreErrorDiagnosticListener.cs index 61f4ce768..b60ab3472 100644 --- a/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreErrorDiagnosticListener.cs +++ b/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreErrorDiagnosticListener.cs @@ -22,7 +22,8 @@ internal class AspNetCoreErrorDiagnosticListener : DiagnosticListenerBase protected override void HandleOnNext(KeyValuePair kv) { if (kv.Key != "Microsoft.AspNetCore.Diagnostics.UnhandledException" - && kv.Key != "Microsoft.AspNetCore.Diagnostics.HandledException") return; + && kv.Key != "Microsoft.AspNetCore.Diagnostics.HandledException") + return; var exception = kv.Value.GetType().GetTypeInfo().GetDeclaredProperty("exception")?.GetValue(kv.Value) as Exception; var httpContextUnhandledException = diff --git a/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreErrorDiagnosticsSubscriber.cs b/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreErrorDiagnosticsSubscriber.cs index 81e0a9209..be54f88bb 100644 --- a/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreErrorDiagnosticsSubscriber.cs +++ b/src/integrations/Elastic.Apm.AspNetCore/DiagnosticListener/AspNetCoreErrorDiagnosticsSubscriber.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/integrations/Elastic.Apm.AspNetCore/WebRequestTransactionCreator.cs b/src/integrations/Elastic.Apm.AspNetCore/WebRequestTransactionCreator.cs index ea469d646..462f38aa9 100644 --- a/src/integrations/Elastic.Apm.AspNetCore/WebRequestTransactionCreator.cs +++ b/src/integrations/Elastic.Apm.AspNetCore/WebRequestTransactionCreator.cs @@ -86,14 +86,16 @@ internal static ITransaction StartTransactionAsync(HttpContext context, IApmLogg internal static void FillSampledTransactionContextRequest(Transaction transaction, HttpContext context, IApmLogger logger) { - if (transaction.IsSampled) FillSampledTransactionContextRequest(context, transaction, logger); + if (transaction.IsSampled) + FillSampledTransactionContextRequest(context, transaction, logger); } private static void FillSampledTransactionContextRequest(HttpContext context, Transaction transaction, IApmLogger logger) { try { - if (context?.Request == null) return; + if (context?.Request == null) + return; var url = new Url { @@ -164,7 +166,8 @@ private static string GetHttpVersion(string protocolString) internal static void StopTransaction(Transaction transaction, HttpContext context, IApmLogger logger) { - if (transaction == null) return; + if (transaction == null) + return; var grpcCallInfo = CollectGrpcInfo(); @@ -180,7 +183,8 @@ internal static void StopTransaction(Transaction transaction, HttpContext contex logger?.Trace()?.Log("Calculating transaction name based on route data"); var name = Transaction.GetNameFromRouteContext(routeData); - if (!string.IsNullOrWhiteSpace(name)) transaction.Name = $"{context.Request.Method} {name}"; + if (!string.IsNullOrWhiteSpace(name)) + transaction.Name = $"{context.Request.Method} {name}"; } else if (context.Response.StatusCode == StatusCodes.Status404NotFound) { diff --git a/src/integrations/Elastic.Apm.AspNetFullFramework/AspNetHttpRequest.cs b/src/integrations/Elastic.Apm.AspNetFullFramework/AspNetHttpRequest.cs index b5a93f733..66e2e0b43 100644 --- a/src/integrations/Elastic.Apm.AspNetFullFramework/AspNetHttpRequest.cs +++ b/src/integrations/Elastic.Apm.AspNetFullFramework/AspNetHttpRequest.cs @@ -3,9 +3,9 @@ // See the LICENSE file in the project root for more information using System.Web; +using Elastic.Apm.AspNetFullFramework.Extensions; using Elastic.Apm.Config; using Elastic.Apm.Helpers; -using Elastic.Apm.AspNetFullFramework.Extensions; using Elastic.Apm.Logging; namespace Elastic.Apm.AspNetFullFramework diff --git a/src/integrations/Elastic.Apm.AspNetFullFramework/AspNetVersion.cs b/src/integrations/Elastic.Apm.AspNetFullFramework/AspNetVersion.cs index b10839e4d..3fd86e66d 100644 --- a/src/integrations/Elastic.Apm.AspNetFullFramework/AspNetVersion.cs +++ b/src/integrations/Elastic.Apm.AspNetFullFramework/AspNetVersion.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Reflection; using System.Web; @@ -11,7 +11,7 @@ namespace Elastic.Apm.AspNetFullFramework { internal static class AspNetVersion - { + { /// /// Gets the ASP.NET engine version /// @@ -21,12 +21,12 @@ public static string GetEngineVersion(IApmLogger logger) { var aspNetVersion = "N/A"; try - { - // We would like to report the same ASP.NET version as the one printed at the bottom of the error page - // (see https://github.com/microsoft/referencesource/blob/master/System.Web/ErrorFormatter.cs#L431) - // It is stored in VersionInfo.EngineVersion - // (see https://github.com/microsoft/referencesource/blob/3b1eaf5203992df69de44c783a3eda37d3d4cd10/System.Web/Util/versioninfo.cs#L91) - // which is unfortunately an internal property of an internal class in System.Web assembly so we use reflection to get it + { + // We would like to report the same ASP.NET version as the one printed at the bottom of the error page + // (see https://github.com/microsoft/referencesource/blob/master/System.Web/ErrorFormatter.cs#L431) + // It is stored in VersionInfo.EngineVersion + // (see https://github.com/microsoft/referencesource/blob/3b1eaf5203992df69de44c783a3eda37d3d4cd10/System.Web/Util/versioninfo.cs#L91) + // which is unfortunately an internal property of an internal class in System.Web assembly so we use reflection to get it const string versionInfoTypeName = "System.Web.Util.VersionInfo"; var versionInfoType = typeof(HttpRuntime).Assembly.GetType(versionInfoTypeName); if (versionInfoType == null) diff --git a/src/integrations/Elastic.Apm.AspNetFullFramework/ElasticApmModule.cs b/src/integrations/Elastic.Apm.AspNetFullFramework/ElasticApmModule.cs index 01c44d2fb..e4f3ef78e 100644 --- a/src/integrations/Elastic.Apm.AspNetFullFramework/ElasticApmModule.cs +++ b/src/integrations/Elastic.Apm.AspNetFullFramework/ElasticApmModule.cs @@ -13,13 +13,13 @@ using Elastic.Apm.AspNetFullFramework.Extensions; using Elastic.Apm.Config.Net4FullFramework; using Elastic.Apm.DiagnosticSource; +using Elastic.Apm.Extensions; using Elastic.Apm.Helpers; using Elastic.Apm.Logging; using Elastic.Apm.Model; -using TraceContext = Elastic.Apm.DistributedTracing.TraceContext; using Elastic.Apm.Reflection; -using Elastic.Apm.Extensions; using Environment = System.Environment; +using TraceContext = Elastic.Apm.DistributedTracing.TraceContext; namespace Elastic.Apm.AspNetFullFramework { @@ -84,7 +84,8 @@ internal static AgentComponents CreateAgentComponents(string debugName) var scopedLogger = logger.Scoped(debugName); var aspNetVersion = AspNetVersion.GetEngineVersion(scopedLogger); - if (aspNetVersion != null) agentComponents.Service.Framework = new Framework { Name = "ASP.NET", Version = aspNetVersion}; + if (aspNetVersion != null) + agentComponents.Service.Framework = new Framework { Name = "ASP.NET", Version = aspNetVersion }; return agentComponents; } @@ -188,7 +189,8 @@ private void ProcessBeginRequest(object sender) transaction = Agent.Instance.Tracer.StartTransaction(transactionName, ApiConstants.TypeRequest, ignoreActivity: true); } - if (transaction.IsSampled) FillSampledTransactionContextRequest(request, transaction, _logger); + if (transaction.IsSampled) + FillSampledTransactionContextRequest(request, transaction, _logger); } /// @@ -283,7 +285,8 @@ private static string GetHttpVersion(string protocol) private void ProcessError(object sender) { var transaction = Agent.Instance.Tracer.CurrentTransaction; - if (transaction is null) return; + if (transaction is null) + return; var application = (HttpApplication)sender; var exception = application.Server.GetLastError(); @@ -344,7 +347,8 @@ private void ProcessEndRequest(object sender) if (area != null) { routeData = new Dictionary(values.Count + 1); - foreach (var value in values) routeData.Add(value.Key, value.Value); + foreach (var value in values) + routeData.Add(value.Key, value.Value); routeData.Add("area", area); } else @@ -383,7 +387,8 @@ private void ProcessEndRequest(object sender) name = Transaction.GetNameFromRouteContext(routeData); } - if (!string.IsNullOrWhiteSpace(name)) transaction.Name = $"{context.Request.HttpMethod} {name}"; + if (!string.IsNullOrWhiteSpace(name)) + transaction.Name = $"{context.Request.HttpMethod} {name}"; } else { @@ -425,15 +430,19 @@ private void ProcessEndRequest(object sender) private static void FillSampledTransactionContextResponse(HttpResponse response, ITransaction transaction) => transaction.Context.Response = new Response { - Finished = true, StatusCode = response.StatusCode, Headers = _isCaptureHeadersEnabled ? ConvertHeaders(response.Headers) : null + Finished = true, + StatusCode = response.StatusCode, + Headers = _isCaptureHeadersEnabled ? ConvertHeaders(response.Headers) : null }; private void FillSampledTransactionContextUser(HttpContext context, ITransaction transaction) { - if (transaction.Context.User != null) return; + if (transaction.Context.User != null) + return; var userIdentity = context.User?.Identity; - if (userIdentity == null || !userIdentity.IsAuthenticated) return; + if (userIdentity == null || !userIdentity.IsAuthenticated) + return; var user = new User { UserName = userIdentity.Name }; diff --git a/src/integrations/Elastic.Apm.AspNetFullFramework/ElasticApmModuleConfiguration.cs b/src/integrations/Elastic.Apm.AspNetFullFramework/ElasticApmModuleConfiguration.cs index d42bf9705..0d5f6a6e8 100644 --- a/src/integrations/Elastic.Apm.AspNetFullFramework/ElasticApmModuleConfiguration.cs +++ b/src/integrations/Elastic.Apm.AspNetFullFramework/ElasticApmModuleConfiguration.cs @@ -17,8 +17,8 @@ public ElasticApmModuleConfiguration(IApmLogger logger = null) : base(logger, new ConfigurationDefaults { - DebugName = nameof(ElasticApmModuleConfiguration), - ServiceName = DiscoverFullFrameworkServiceName(logger?.Scoped(nameof(ElasticApmModuleConfiguration))) + DebugName = nameof(ElasticApmModuleConfiguration), + ServiceName = DiscoverFullFrameworkServiceName(logger?.Scoped(nameof(ElasticApmModuleConfiguration))) } ) { } diff --git a/src/integrations/Elastic.Apm.AspNetFullFramework/Extensions/SoapRequest.cs b/src/integrations/Elastic.Apm.AspNetFullFramework/Extensions/SoapRequest.cs index 291804243..2193fab88 100644 --- a/src/integrations/Elastic.Apm.AspNetFullFramework/Extensions/SoapRequest.cs +++ b/src/integrations/Elastic.Apm.AspNetFullFramework/Extensions/SoapRequest.cs @@ -62,7 +62,8 @@ private static string GetSoap11Action(NameValueCollection headers) if (!string.IsNullOrWhiteSpace(soapActionWithNamespace)) { var indexPosition = soapActionWithNamespace.LastIndexOf(@"/", StringComparison.InvariantCulture); - if (indexPosition != -1) return soapActionWithNamespace.Substring(indexPosition + 1).TrimEnd('\"'); + if (indexPosition != -1) + return soapActionWithNamespace.Substring(indexPosition + 1).TrimEnd('\"'); } return null; } diff --git a/src/integrations/Elastic.Apm.AspNetFullFramework/HttpContextCurrentExecutionSegmentsContainer.cs b/src/integrations/Elastic.Apm.AspNetFullFramework/HttpContextCurrentExecutionSegmentsContainer.cs index 39914d9a2..82d33c0c0 100644 --- a/src/integrations/Elastic.Apm.AspNetFullFramework/HttpContextCurrentExecutionSegmentsContainer.cs +++ b/src/integrations/Elastic.Apm.AspNetFullFramework/HttpContextCurrentExecutionSegmentsContainer.cs @@ -1,14 +1,14 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading; using System.Web; using Elastic.Apm.Api; namespace Elastic.Apm.AspNetFullFramework -{ +{ /// /// An that stores the current transaction /// and current span in both async local storage and the current diff --git a/src/integrations/Elastic.Apm.AspNetFullFramework/OpenIdClaimTypes.cs b/src/integrations/Elastic.Apm.AspNetFullFramework/OpenIdClaimTypes.cs index 05bf77ba4..8b56577d0 100644 --- a/src/integrations/Elastic.Apm.AspNetFullFramework/OpenIdClaimTypes.cs +++ b/src/integrations/Elastic.Apm.AspNetFullFramework/OpenIdClaimTypes.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + namespace Elastic.Apm.AspNetFullFramework { internal static class OpenIdClaimTypes diff --git a/src/integrations/Elastic.Apm.Extensions.Hosting/Config/ApmConfiguration.cs b/src/integrations/Elastic.Apm.Extensions.Hosting/Config/ApmConfiguration.cs index 9221d6c57..b07095571 100644 --- a/src/integrations/Elastic.Apm.Extensions.Hosting/Config/ApmConfiguration.cs +++ b/src/integrations/Elastic.Apm.Extensions.Hosting/Config/ApmConfiguration.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -44,10 +44,12 @@ public ApmConfiguration(IConfiguration configuration, IApmLogger logger, string private void ChangeCallback(object obj) { - if (obj is not IConfigurationSection) return; + if (obj is not IConfigurationSection) + return; var newLogLevel = ParseLogLevel(Lookup(ConfigurationOption.LogLevel)); - if (LogLevel == newLogLevel) return; + if (LogLevel == newLogLevel) + return; LogLevel = newLogLevel; } } diff --git a/src/integrations/Elastic.Apm.Extensions.Hosting/HostBuilderExtensions.cs b/src/integrations/Elastic.Apm.Extensions.Hosting/HostBuilderExtensions.cs index b4dfce34c..6553abfae 100644 --- a/src/integrations/Elastic.Apm.Extensions.Hosting/HostBuilderExtensions.cs +++ b/src/integrations/Elastic.Apm.Extensions.Hosting/HostBuilderExtensions.cs @@ -60,7 +60,8 @@ public static IHostBuilder UseElasticApm(this IHostBuilder builder, params IDiag services.AddSingleton(sp => { - if (Agent.IsConfigured) return Agent.Components; + if (Agent.IsConfigured) + return Agent.Components; var logger = sp.GetService(); var configReader = sp.GetService(); @@ -74,7 +75,8 @@ public static IHostBuilder UseElasticApm(this IHostBuilder builder, params IDiag services.AddSingleton(sp => { - if (Agent.IsConfigured) return Agent.Instance; + if (Agent.IsConfigured) + return Agent.Instance; Agent.Setup(sp.GetService()); return Agent.Instance; @@ -86,9 +88,11 @@ public static IHostBuilder UseElasticApm(this IHostBuilder builder, params IDiag var serviceProvider = services.BuildServiceProvider(); var agent = serviceProvider.GetService(); - if (!(agent is ApmAgent apmAgent)) return; + if (!(agent is ApmAgent apmAgent)) + return; - if (!Agent.IsConfigured || !apmAgent.ConfigurationReader.Enabled) return; + if (!Agent.IsConfigured || !apmAgent.ConfigurationReader.Enabled) + return; // Only add ElasticApmErrorLoggingProvider after the agent is created, because it depends on the agent services.AddSingleton(sp => diff --git a/src/integrations/Elastic.Apm.Extensions.Hosting/NetCoreLogger.cs b/src/integrations/Elastic.Apm.Extensions.Hosting/NetCoreLogger.cs index 0230f4f8f..ea9dc55ed 100644 --- a/src/integrations/Elastic.Apm.Extensions.Hosting/NetCoreLogger.cs +++ b/src/integrations/Elastic.Apm.Extensions.Hosting/NetCoreLogger.cs @@ -21,15 +21,22 @@ private static Microsoft.Extensions.Logging.LogLevel Convert(LogLevel logLevel) { switch (logLevel) { - case LogLevel.Trace: return Microsoft.Extensions.Logging.LogLevel.Trace; - case LogLevel.Debug: return Microsoft.Extensions.Logging.LogLevel.Debug; - case LogLevel.Information: return Microsoft.Extensions.Logging.LogLevel.Information; - case LogLevel.Warning: return Microsoft.Extensions.Logging.LogLevel.Warning; - case LogLevel.Error: return Microsoft.Extensions.Logging.LogLevel.Error; - case LogLevel.Critical: return Microsoft.Extensions.Logging.LogLevel.Critical; + case LogLevel.Trace: + return Microsoft.Extensions.Logging.LogLevel.Trace; + case LogLevel.Debug: + return Microsoft.Extensions.Logging.LogLevel.Debug; + case LogLevel.Information: + return Microsoft.Extensions.Logging.LogLevel.Information; + case LogLevel.Warning: + return Microsoft.Extensions.Logging.LogLevel.Warning; + case LogLevel.Error: + return Microsoft.Extensions.Logging.LogLevel.Error; + case LogLevel.Critical: + return Microsoft.Extensions.Logging.LogLevel.Critical; // ReSharper disable once RedundantCaseLabel case LogLevel.None: - default: return Microsoft.Extensions.Logging.LogLevel.None; + default: + return Microsoft.Extensions.Logging.LogLevel.None; } } } diff --git a/src/integrations/Elastic.Apm.Extensions.Logging/ApmErrorLogger.cs b/src/integrations/Elastic.Apm.Extensions.Logging/ApmErrorLogger.cs index 6a234967f..ca9951a51 100644 --- a/src/integrations/Elastic.Apm.Extensions.Logging/ApmErrorLogger.cs +++ b/src/integrations/Elastic.Apm.Extensions.Logging/ApmErrorLogger.cs @@ -7,9 +7,8 @@ using System.Collections.Generic; using Elastic.Apm.Api; using Elastic.Apm.Helpers; -using Microsoft.Extensions.Logging; using Elastic.Apm.Logging; - +using Microsoft.Extensions.Logging; using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace Elastic.Apm.Extensions.Logging @@ -33,9 +32,12 @@ public bool IsEnabled(LogLevel logLevel) public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { - if (!Agent.IsConfigured) return; - if (!IsEnabled(logLevel)) return; - if (!_agent.ConfigurationReader.Enabled || !_agent.ConfigurationReader.Recording) return; + if (!Agent.IsConfigured) + return; + if (!IsEnabled(logLevel)) + return; + if (!_agent.ConfigurationReader.Enabled || !_agent.ConfigurationReader.Recording) + return; var logLine = formatter(state, exception); var errorLog = new ErrorLog(logLine); @@ -66,7 +68,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except else _agent.Tracer.CaptureErrorLog(errorLog); } - catch(Exception e) + catch (Exception e) { _agent.Logger.Warning()?.LogException(e, "Failed capturing APM Error based on log"); } diff --git a/src/integrations/Elastic.Apm.NetCoreAll/ApmMiddlewareExtension.cs b/src/integrations/Elastic.Apm.NetCoreAll/ApmMiddlewareExtension.cs index 665ae6d28..075d6c0a8 100644 --- a/src/integrations/Elastic.Apm.NetCoreAll/ApmMiddlewareExtension.cs +++ b/src/integrations/Elastic.Apm.NetCoreAll/ApmMiddlewareExtension.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/CommandLineOptions.cs b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/CommandLineOptions.cs index 7ef79db25..959b89481 100644 --- a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/CommandLineOptions.cs +++ b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/CommandLineOptions.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using CommandLine; namespace Elastic.Apm.Profiler.IntegrationsGenerator diff --git a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Integration.cs b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Integration.cs index 1472bbd00..9c1aaa819 100644 --- a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Integration.cs +++ b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Integration.cs @@ -1,16 +1,16 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections.Generic; namespace Elastic.Apm.Profiler.IntegrationsGenerator { public class Integration { - public string Name { get; set; } - + public string Name { get; set; } + public IEnumerable MethodReplacements { get; set; } } } diff --git a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/MethodReplacement.cs b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/MethodReplacement.cs index 172a96458..93b1254fb 100644 --- a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/MethodReplacement.cs +++ b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/MethodReplacement.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + namespace Elastic.Apm.Profiler.IntegrationsGenerator { public class MethodReplacement diff --git a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Program.cs b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Program.cs index 057f19dc6..160abadd3 100644 --- a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Program.cs +++ b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Program.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.IO; @@ -28,8 +28,8 @@ internal class Program private static int Run(CommandLineOptions opts) { try - { - // assumes the assembly is compatible to load for the TFM of this executable + { + // assumes the assembly is compatible to load for the TFM of this executable var targetAssembly = Assembly.LoadFrom(opts.Input); var classesInstrumentMethodAttributes = @@ -45,39 +45,39 @@ private static int Run(CommandLineOptions opts) from attribute in attributes select attribute; - var callTargetIntegrations = from attribute in classesInstrumentMethodAttributes - let integrationName = attribute.Group - let assembly = attribute.CallTargetType.Assembly - let wrapperType = attribute.CallTargetType - orderby integrationName - group new { assembly, wrapperType, attribute } by integrationName - into g - select new Integration - { - Name = g.Key, - MethodReplacements = from item in g - select new MethodReplacement - { - Target = new Target - { - Nuget = item.attribute.Nuget, - Assembly = item.attribute.Assembly, - Type = item.attribute.Type, - Method = item.attribute.Method, - SignatureTypes = new[] { item.attribute.ReturnType } - .Concat(item.attribute.ParameterTypes ?? Enumerable.Empty()) - .ToArray(), - MinimumVersion = item.attribute.MinimumVersion, - MaximumVersion = item.attribute.MaximumVersion - }, - Wrapper = new Wrapper - { - Assembly = item.assembly.FullName, - Type = item.wrapperType.FullName, - Action = "CallTargetModification" - } - } - }; + var callTargetIntegrations = from attribute in classesInstrumentMethodAttributes + let integrationName = attribute.Group + let assembly = attribute.CallTargetType.Assembly + let wrapperType = attribute.CallTargetType + orderby integrationName + group new { assembly, wrapperType, attribute } by integrationName + into g + select new Integration + { + Name = g.Key, + MethodReplacements = from item in g + select new MethodReplacement + { + Target = new Target + { + Nuget = item.attribute.Nuget, + Assembly = item.attribute.Assembly, + Type = item.attribute.Type, + Method = item.attribute.Method, + SignatureTypes = new[] { item.attribute.ReturnType } + .Concat(item.attribute.ParameterTypes ?? Enumerable.Empty()) + .ToArray(), + MinimumVersion = item.attribute.MinimumVersion, + MaximumVersion = item.attribute.MaximumVersion + }, + Wrapper = new Wrapper + { + Assembly = item.assembly.FullName, + Type = item.wrapperType.FullName, + Action = "CallTargetModification" + } + } + }; string output; switch (opts.Format) @@ -91,7 +91,8 @@ into g case CommandLineOptions.OutputFormat.Asciidoc: output = GenerateAsciidoc(callTargetIntegrations); break; - default: throw new ArgumentOutOfRangeException(nameof(opts.Format),"Unknown format"); + default: + throw new ArgumentOutOfRangeException(nameof(opts.Format), "Unknown format"); } var filename = Path.Combine(opts.Output, "integrations." + opts.Format.ToString().ToLowerInvariant()); @@ -128,13 +129,13 @@ private static string GenerateAsciidoc(IEnumerable integrations) foreach (var integrationMethod in integrationMethods) { var versionRange = $"{integrationMethod.Key.MinimumVersion.Replace("*", "{star}")} - " - + $"{integrationMethod.Key.MaximumVersion.Replace("*", "{star}")}"; - - // Nuget property can be: - // - null: take the assembly name and combine with version constraints - // - start with "part of": take verbatim - // - package name: take package name and combine with version constraints - // - package name and version: take verbatim + + $"{integrationMethod.Key.MaximumVersion.Replace("*", "{star}")}"; + + // Nuget property can be: + // - null: take the assembly name and combine with version constraints + // - start with "part of": take verbatim + // - package name: take package name and combine with version constraints + // - package name and version: take verbatim string nuget; if (integrationMethod.Key.Nuget is not null) { diff --git a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Target.cs b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Target.cs index 7a43875fd..ab06e95f9 100644 --- a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Target.cs +++ b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Target.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using YamlDotNet.Serialization; namespace Elastic.Apm.Profiler.IntegrationsGenerator diff --git a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Wrapper.cs b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Wrapper.cs index bb38b087b..52cf77862 100644 --- a/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Wrapper.cs +++ b/src/profiler/Elastic.Apm.Profiler.IntegrationsGenerator/Wrapper.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + namespace Elastic.Apm.Profiler.IntegrationsGenerator { public class Wrapper diff --git a/src/profiler/Elastic.Apm.Profiler.Managed.Core/ClrTypeNames.cs b/src/profiler/Elastic.Apm.Profiler.Managed.Core/ClrTypeNames.cs index b343f3806..ee854e9de 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed.Core/ClrTypeNames.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed.Core/ClrTypeNames.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Core { public static class ClrTypeNames @@ -33,9 +33,9 @@ public static class ClrTypeNames public const string Stream = "System.IO.Stream"; public const string Task = "System.Threading.Tasks.Task"; - public const string CancellationToken = "System.Threading.CancellationToken"; - - // ReSharper disable once InconsistentNaming + public const string CancellationToken = "System.Threading.CancellationToken"; + + // ReSharper disable once InconsistentNaming public const string IAsyncResult = "System.IAsyncResult"; public const string AsyncCallback = "System.AsyncCallback"; diff --git a/src/profiler/Elastic.Apm.Profiler.Managed.Core/InstrumentAttribute.cs b/src/profiler/Elastic.Apm.Profiler.Managed.Core/InstrumentAttribute.cs index ecaecf33a..42c4b779b 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed.Core/InstrumentAttribute.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed.Core/InstrumentAttribute.cs @@ -1,64 +1,64 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + using System; namespace Elastic.Apm.Profiler.Managed.Core -{ +{ /// /// Decorated class instruments a method /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class InstrumentAttribute : Attribute - { + { /// /// The name of the group to which this instrumentation belongs /// - public string Group { get; set; } - + public string Group { get; set; } + /// /// The name of the assembly containing the target method to instrument /// - public string Assembly { get; set; } - + public string Assembly { get; set; } + /// /// The name of the nuget package containing the assembly to instrument. /// Used for documentation. If unspecified, will use value. /// Values starting with "part of" are specially treated. /// - public string Nuget { get; set; } - + public string Nuget { get; set; } + /// /// The fully qualified name of the type containing the target method to instrument /// - public string Type { get; set; } - + public string Type { get; set; } + /// /// The name of the method to instrument /// - public string Method { get; set; } - + public string Method { get; set; } + /// /// The fully qualified name of the return type of the method to instrument /// - public string ReturnType { get; set; } - + public string ReturnType { get; set; } + /// /// The fully qualified names of the parameter types of the method to instrument /// - public string[] ParameterTypes { get; set; } - + public string[] ParameterTypes { get; set; } + /// /// The minimum assembly version that can be instrumented /// - public string MinimumVersion { get; set; } - + public string MinimumVersion { get; set; } + /// /// The maximum assembly version that can be instrumented /// - public string MaximumVersion { get; set; } - + public string MaximumVersion { get; set; } + /// /// The type to which this instrumentation applies. If null, the type will /// be determined from the type to which the attribute is applied. diff --git a/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Logger.cs b/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Logger.cs index 6deab4db8..4fa72b544 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Logger.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Logger.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Diagnostics; @@ -10,8 +10,8 @@ using System.Text; namespace Elastic.Apm.Profiler.Managed.Loader -{ - // match the log levels of the profiler logger +{ + // match the log levels of the profiler logger internal enum LogLevel { Trace = 0, @@ -42,7 +42,7 @@ static Logger() private static readonly LogLevel Level; private static readonly string LogFile; - private static readonly Dictionary Levels; + private static readonly Dictionary Levels; public static void Log(LogLevel level, Exception exception, string message, params object[] args) { @@ -75,16 +75,16 @@ public static void Log(LogLevel level, string message, params object[] args) return; } catch - { - // ignore + { + // ignore } } Console.Error.WriteLine($"[{DateTimeOffset.Now:O}] [{Levels[level]}] {message}", args); } catch - { - // ignore + { + // ignore } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.NetCore.cs b/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.NetCore.cs index 31b4cb724..753bf9144 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.NetCore.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.NetCore.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + + #if !NETFRAMEWORK using System; using System.IO; diff --git a/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.NetFramework.cs b/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.NetFramework.cs index 182ab2718..18023e7e3 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.NetFramework.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.NetFramework.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + #if NETFRAMEWORK using System; using System.IO; @@ -25,12 +25,12 @@ private static string ResolveDirectory() private static Assembly ResolveDependencies(object sender, ResolveEventArgs args) { - var assemblyName = new AssemblyName(args.Name).Name; - - // On .NET Framework, having a non-US locale can cause mscorlib - // to enter the AssemblyResolve event when searching for resources - // in its satellite assemblies. Exit early so we don't cause - // infinite recursion. + var assemblyName = new AssemblyName(args.Name).Name; + + // On .NET Framework, having a non-US locale can cause mscorlib + // to enter the AssemblyResolve event when searching for resources + // in its satellite assemblies. Exit early so we don't cause + // infinite recursion. if (string.Equals(assemblyName, "mscorlib.resources", StringComparison.OrdinalIgnoreCase) || string.Equals(assemblyName, "System.Net.Http", StringComparison.OrdinalIgnoreCase)) return null; @@ -49,5 +49,5 @@ private static Assembly ResolveDependencies(object sender, ResolveEventArgs args return null; } } -} +} #endif diff --git a/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.cs b/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.cs index 097f061d1..6d8aa6883 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed.Loader/Startup.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Reflection; @@ -37,7 +37,8 @@ private static void TryLoadManagedAssembly() { var version = Assembly.GetExecutingAssembly().GetName().Version; var assembly = Assembly.Load($"Elastic.Apm.Profiler.Managed, Version={version}, Culture=neutral, PublicKeyToken=ae7400d2c189cf22"); - if (assembly == null) return; + if (assembly == null) + return; var type = assembly.GetType("Elastic.Apm.Profiler.Managed.AutoInstrumentation", throwOnError: false); var method = type?.GetRuntimeMethod("Initialize", parameters: Type.EmptyTypes); diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/AutoInstrumentation.cs b/src/profiler/Elastic.Apm.Profiler.Managed/AutoInstrumentation.cs index 27a586bc9..1f6a165d9 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/AutoInstrumentation.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/AutoInstrumentation.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Threading; @@ -18,40 +18,40 @@ public static class AutoInstrumentation private static int FirstInitialization = 1; public static void Initialize() - { - // check if already called + { + // check if already called if (Interlocked.Exchange(ref FirstInitialization, 0) != 1) return; Logger.Log(LogLevel.Debug, $"{nameof(AutoInstrumentation)}.{nameof(Initialize)} called"); try - { - // ReSharper disable once ReplaceWithSingleAssignment.False - var skipInstantiation = false; - + { + // ReSharper disable once ReplaceWithSingleAssignment.False + var skipInstantiation = false; + #if NETFRAMEWORK - // if this is a .NET Framework application running in IIS, don't instantiate the agent here, but let the - // ElasticApmModule do so in its Init(). This assumes that the application: - // either - // 1. references Elastic.Apm.AspNetFullFramework and has configured ElasticApmModule in web.config - // or - // 2. is relying on profiler auto instrumentation to register ElasticApmModule - // - // We allow instantiation to happen in ElasticApmModule because in the case point 1, a user may have - // configured a logging adaptor for the agent running in ASP.NET, which would be ignored if the agent - // was instantiated here. - // ReSharper disable once ConvertIfToOrExpression + // if this is a .NET Framework application running in IIS, don't instantiate the agent here, but let the + // ElasticApmModule do so in its Init(). This assumes that the application: + // either + // 1. references Elastic.Apm.AspNetFullFramework and has configured ElasticApmModule in web.config + // or + // 2. is relying on profiler auto instrumentation to register ElasticApmModule + // + // We allow instantiation to happen in ElasticApmModule because in the case point 1, a user may have + // configured a logging adaptor for the agent running in ASP.NET, which would be ignored if the agent + // was instantiated here. + // ReSharper disable once ConvertIfToOrExpression if (System.Web.Hosting.HostingEnvironment.IsHosted) - skipInstantiation = true; + skipInstantiation = true; #endif Logger.Log(LogLevel.Debug, - "{methodName}: value of {skipInstantiation}", $"{nameof(AutoInstrumentation)}.{nameof(Initialize)}", skipInstantiation); - - // ensure global instance is created if it's not already + "{methodName}: value of {skipInstantiation}", $"{nameof(AutoInstrumentation)}.{nameof(Initialize)}", skipInstantiation); + + // ensure global instance is created if it's not already if (!skipInstantiation) { - _ = Agent.Instance; + _ = Agent.Instance; #if !NETFRAMEWORK Logger.Log(LogLevel.Debug, "Activate Elastic.Apm.AspNetCore.DiagnosticListener.AspNetCoreDiagnosticSubscriber"); Agent.Subscribe(new Elastic.Apm.AspNetCore.DiagnosticListener.AspNetCoreDiagnosticSubscriber()); diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetInvoker.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetInvoker.cs index 42ec2b716..ac414296c 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetInvoker.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetInvoker.cs @@ -1,23 +1,23 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.CompilerServices; using Elastic.Apm.Profiler.Managed.CallTarget.Handlers; namespace Elastic.Apm.Profiler.Managed.CallTarget -{ +{ /// /// CallTarget Invoker /// public static class CallTargetInvoker - { + { /// /// Begin Method Invoker /// @@ -32,8 +32,8 @@ public static class CallTargetInvoker return BeginMethodHandler.Invoke(instance); return CallTargetState.GetDefault(); - } - + } + /// /// Begin Method Invoker /// @@ -50,8 +50,8 @@ public static class CallTargetInvoker return BeginMethodHandler.Invoke(instance, arg1); return CallTargetState.GetDefault(); - } - + } + /// /// Begin Method Invoker /// @@ -70,8 +70,8 @@ public static class CallTargetInvoker return BeginMethodHandler.Invoke(instance, arg1, arg2); return CallTargetState.GetDefault(); - } - + } + /// /// Begin Method Invoker /// @@ -92,8 +92,8 @@ public static class CallTargetInvoker return BeginMethodHandler.Invoke(instance, arg1, arg2, arg3); return CallTargetState.GetDefault(); - } - + } + /// /// Begin Method Invoker /// @@ -118,8 +118,8 @@ public static class CallTargetInvoker return BeginMethodHandler.Invoke(instance, arg1, arg2, arg3, arg4); return CallTargetState.GetDefault(); - } - + } + /// /// Begin Method Invoker /// @@ -146,8 +146,8 @@ public static class CallTargetInvoker return BeginMethodHandler.Invoke(instance, arg1, arg2, arg3, arg4, arg5); return CallTargetState.GetDefault(); - } - + } + /// /// Begin Method Invoker /// @@ -179,8 +179,8 @@ public static class CallTargetInvoker } return CallTargetState.GetDefault(); - } - + } + /// /// Begin Method Invoker /// @@ -214,8 +214,8 @@ public static class CallTargetInvoker } return CallTargetState.GetDefault(); - } - + } + /// /// Begin Method Invoker /// @@ -251,8 +251,8 @@ public static class CallTargetInvoker } return CallTargetState.GetDefault(); - } - + } + /// /// Begin Method Invoker Slow Path /// @@ -268,8 +268,8 @@ public static class CallTargetInvoker return BeginMethodSlowHandler.Invoke(instance, arguments); return CallTargetState.GetDefault(); - } - + } + /// /// End Method with Void return value invoker /// @@ -286,8 +286,8 @@ public static class CallTargetInvoker return EndMethodHandler.Invoke(instance, exception, state); return CallTargetReturn.GetDefault(); - } - + } + /// /// End Method with Return value invoker /// @@ -308,8 +308,8 @@ CallTargetState state return EndMethodHandler.Invoke(instance, returnValue, exception, state); return new CallTargetReturn(returnValue); - } - + } + /// /// Log integration exception /// @@ -318,8 +318,8 @@ CallTargetState state /// Integration exception instance [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void LogException(Exception exception) => - IntegrationOptions.LogException(exception); - + IntegrationOptions.LogException(exception); + /// /// Gets the default value of a type /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetInvokerException.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetInvokerException.cs index 4ec3bc7c9..227ef17ff 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetInvokerException.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetInvokerException.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.CallTarget diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetReturn.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetReturn.cs index 6fb85c8a8..3f7e67371 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetReturn.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetReturn.cs @@ -1,56 +1,56 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Runtime.CompilerServices; namespace Elastic.Apm.Profiler.Managed.CallTarget -{ +{ /// /// Call target return value /// /// Type of the return value public readonly struct CallTargetReturn { - private readonly T _returnValue; - + private readonly T _returnValue; + /// /// Initializes a new instance of the struct. /// /// Return value - public CallTargetReturn(T returnValue) => _returnValue = returnValue; - + public CallTargetReturn(T returnValue) => _returnValue = returnValue; + /// /// Gets the default call target return value (used by the native side to initialize the locals) /// /// Default call target return value [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static CallTargetReturn GetDefault() => default; - + public static CallTargetReturn GetDefault() => default; + /// /// Gets the return value /// /// Return value [MethodImpl(MethodImplOptions.AggressiveInlining)] - public T GetReturnValue() => _returnValue; - + public T GetReturnValue() => _returnValue; + /// /// ToString override /// /// String value public override string ToString() => $"{typeof(CallTargetReturn).FullName}({_returnValue})"; - } - + } + /// /// Call target return value /// public readonly struct CallTargetReturn - { + { /// /// Gets the default call target return value (used by the native side to initialize the locals) /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetState.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetState.cs index 675cc52e6..fc52ab3a4 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetState.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/CallTargetState.cs @@ -1,18 +1,18 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.CompilerServices; using Elastic.Apm.Api; namespace Elastic.Apm.Profiler.Managed.CallTarget -{ +{ /// /// Call target execution state /// @@ -21,8 +21,8 @@ namespace Elastic.Apm.Profiler.Managed.CallTarget private readonly IExecutionSegment _previousSegment; private readonly IExecutionSegment _segment; private readonly object _state; - private readonly DateTimeOffset? _startTime; - + private readonly DateTimeOffset? _startTime; + /// /// Initializes a new instance of the struct. /// @@ -33,8 +33,8 @@ public CallTargetState(IExecutionSegment segment) _segment = segment; _state = null; _startTime = null; - } - + } + /// /// Initializes a new instance of the struct. /// @@ -46,8 +46,8 @@ public CallTargetState(IExecutionSegment segment, object state) _segment = segment; _state = state; _startTime = null; - } - + } + /// /// Initializes a new instance of the struct. /// @@ -68,32 +68,32 @@ internal CallTargetState(IExecutionSegment previousSegment, CallTargetState stat _segment = state._segment; _state = state._state; _startTime = state._startTime; - } - + } + /// /// Gets the CallTarget BeginMethod segment /// - public IExecutionSegment Segment => _segment; - + public IExecutionSegment Segment => _segment; + /// /// Gets the CallTarget BeginMethod state /// - public object State => _state; - + public object State => _state; + /// /// Gets the CallTarget state StartTime /// public DateTimeOffset? StartTime => _startTime; - internal IExecutionSegment PreviousSegment => _previousSegment; - + internal IExecutionSegment PreviousSegment => _previousSegment; + /// /// Gets the default call target state (used by the native side to initialize the locals) /// /// Default call target state [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static CallTargetState GetDefault() => default; - + public static CallTargetState GetDefault() => default; + /// /// ToString override /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler.cs index 921fd5fda..6d22f4b1b 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class BeginMethodHandler diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`1.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`1.cs index dc707fee7..983bf3534 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`1.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`1.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class BeginMethodHandler @@ -23,7 +23,8 @@ static BeginMethodHandler() try { var dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1) }); - if (dynMethod != null) _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); + if (dynMethod != null) + _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); } catch (Exception ex) { @@ -31,7 +32,8 @@ static BeginMethodHandler() } finally { - if (_invokeDelegate is null) _invokeDelegate = (_, _) => CallTargetState.GetDefault(); + if (_invokeDelegate is null) + _invokeDelegate = (_, _) => CallTargetState.GetDefault(); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`2.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`2.cs index 689c9fbb7..168f233d2 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`2.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`2.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class BeginMethodHandler @@ -24,7 +24,8 @@ static BeginMethodHandler() { var dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2) }); - if (dynMethod != null) _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); + if (dynMethod != null) + _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); } catch (Exception ex) { @@ -32,7 +33,8 @@ static BeginMethodHandler() } finally { - if (_invokeDelegate is null) _invokeDelegate = (_, _, _) => CallTargetState.GetDefault(); + if (_invokeDelegate is null) + _invokeDelegate = (_, _, _) => CallTargetState.GetDefault(); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`3.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`3.cs index ca0aa5069..27207ff8f 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`3.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`3.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class BeginMethodHandler @@ -24,7 +24,8 @@ static BeginMethodHandler() { var dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3) }); - if (dynMethod != null) _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); + if (dynMethod != null) + _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); } catch (Exception ex) { @@ -32,7 +33,8 @@ static BeginMethodHandler() } finally { - if (_invokeDelegate is null) _invokeDelegate = (_, _, _, _) => CallTargetState.GetDefault(); + if (_invokeDelegate is null) + _invokeDelegate = (_, _, _, _) => CallTargetState.GetDefault(); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`4.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`4.cs index 8f01f74a4..aa50037b0 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`4.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`4.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class BeginMethodHandler @@ -24,7 +24,8 @@ static BeginMethodHandler() { var dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4) }); - if (dynMethod != null) _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); + if (dynMethod != null) + _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); } catch (Exception ex) { @@ -32,7 +33,8 @@ static BeginMethodHandler() } finally { - if (_invokeDelegate is null) _invokeDelegate = (_, _, _, _, _) => CallTargetState.GetDefault(); + if (_invokeDelegate is null) + _invokeDelegate = (_, _, _, _, _) => CallTargetState.GetDefault(); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`5.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`5.cs index 41347bb4b..f055c5acf 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`5.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`5.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class BeginMethodHandler @@ -24,7 +24,8 @@ static BeginMethodHandler() { var dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5) }); - if (dynMethod != null) _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); + if (dynMethod != null) + _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); } catch (Exception ex) { @@ -32,7 +33,8 @@ static BeginMethodHandler() } finally { - if (_invokeDelegate is null) _invokeDelegate = (_, _, _, _, _, _) => CallTargetState.GetDefault(); + if (_invokeDelegate is null) + _invokeDelegate = (_, _, _, _, _, _) => CallTargetState.GetDefault(); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`6.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`6.cs index 9735576a2..c4660527f 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`6.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`6.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class BeginMethodHandler @@ -24,7 +24,8 @@ static BeginMethodHandler() { var dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5), typeof(TArg6) }); - if (dynMethod != null) _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); + if (dynMethod != null) + _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); } catch (Exception ex) { @@ -32,7 +33,8 @@ static BeginMethodHandler() } finally { - if (_invokeDelegate is null) _invokeDelegate = (_, _, _, _, _, _, _) => CallTargetState.GetDefault(); + if (_invokeDelegate is null) + _invokeDelegate = (_, _, _, _, _, _, _) => CallTargetState.GetDefault(); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`7.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`7.cs index 09bebdc4b..0f2160de5 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`7.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`7.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class BeginMethodHandler @@ -24,7 +24,8 @@ static BeginMethodHandler() { var dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5), typeof(TArg6), typeof(TArg7) }); - if (dynMethod != null) _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); + if (dynMethod != null) + _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); } catch (Exception ex) { @@ -32,7 +33,8 @@ static BeginMethodHandler() } finally { - if (_invokeDelegate is null) _invokeDelegate = (_, _, _, _, _, _, _, _) => CallTargetState.GetDefault(); + if (_invokeDelegate is null) + _invokeDelegate = (_, _, _, _, _, _, _, _) => CallTargetState.GetDefault(); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`8.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`8.cs index 1b91a72cf..4375aa7e3 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`8.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodHandler`8.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Runtime.CompilerServices; - +using System.Runtime.CompilerServices; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class BeginMethodHandler @@ -24,7 +24,8 @@ static BeginMethodHandler() { var dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5), typeof(TArg6), typeof(TArg7), typeof(TArg8) }); - if (dynMethod != null) _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); + if (dynMethod != null) + _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); } catch (Exception ex) { @@ -32,7 +33,8 @@ static BeginMethodHandler() } finally { - if (_invokeDelegate is null) _invokeDelegate = (_, _, _, _, _, _, _, _, _) => CallTargetState.GetDefault(); + if (_invokeDelegate is null) + _invokeDelegate = (_, _, _, _, _, _, _, _, _) => CallTargetState.GetDefault(); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodSlowHandler.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodSlowHandler.cs index 111f98095..3e376ca9b 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodSlowHandler.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/BeginMethodSlowHandler.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.CompilerServices; @@ -21,7 +21,8 @@ static BeginMethodSlowHandler() try { var dynMethod = IntegrationMapper.CreateSlowBeginMethodDelegate(typeof(TIntegration), typeof(TTarget)); - if (dynMethod != null) _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); + if (dynMethod != null) + _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); } catch (Exception ex) { @@ -29,7 +30,8 @@ static BeginMethodSlowHandler() } finally { - if (_invokeDelegate is null) _invokeDelegate = (_, _) => CallTargetState.GetDefault(); + if (_invokeDelegate is null) + _invokeDelegate = (_, _) => CallTargetState.GetDefault(); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ContinuationGenerator.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ContinuationGenerator.cs index 693462dd1..3c13114f7 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ContinuationGenerator.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ContinuationGenerator.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.CompilerServices; @@ -18,21 +18,21 @@ internal class ContinuationGenerator [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static TReturn ToTReturn(TFrom returnValue) - { + { #if NETSTANDARD2_1_OR_GREATER return Unsafe.As(ref returnValue); #else - return ContinuationsHelper.Convert(returnValue); + return ContinuationsHelper.Convert(returnValue); #endif } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static TTo FromTReturn(TReturn returnValue) - { + { #if NETSTANDARD2_1_OR_GREATER return Unsafe.As(ref returnValue); #else - return ContinuationsHelper.Convert(returnValue); + return ContinuationsHelper.Convert(returnValue); #endif } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ContinuationsHelper.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ContinuationsHelper.cs index 1d039ac85..c2bad10b1 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ContinuationsHelper.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ContinuationsHelper.cs @@ -1,15 +1,15 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - -using System; +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; #if NETSTANDARD2_0 || NETFRAMEWORK -using System.Reflection.Emit; +using System.Reflection.Emit; #endif using System.Runtime.CompilerServices; @@ -37,30 +37,30 @@ internal static Type GetResultType(Type parentType) } return typeof(object); - } - + } + #if NETSTANDARD2_1_OR_GREATER #else - internal static TTo Convert(TFrom value) => Converter.Convert(value); - - private static class Converter - { - private static readonly ConvertDelegate _converter; - - static Converter() - { - var dMethod = - new DynamicMethod($"Converter<{typeof(TFrom).Name},{typeof(TTo).Name}>", typeof(TTo), new[] { typeof(TFrom) }, typeof(ConvertDelegate).Module, true); - var il = dMethod.GetILGenerator(); - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ret); - _converter = (ConvertDelegate)dMethod.CreateDelegate(typeof(ConvertDelegate)); - } - - private delegate TTo ConvertDelegate(TFrom value); + internal static TTo Convert(TFrom value) => Converter.Convert(value); - public static TTo Convert(TFrom value) => _converter(value); - } + private static class Converter + { + private static readonly ConvertDelegate _converter; + + static Converter() + { + var dMethod = + new DynamicMethod($"Converter<{typeof(TFrom).Name},{typeof(TTo).Name}>", typeof(TTo), new[] { typeof(TFrom) }, typeof(ConvertDelegate).Module, true); + var il = dMethod.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ret); + _converter = (ConvertDelegate)dMethod.CreateDelegate(typeof(ConvertDelegate)); + } + + private delegate TTo ConvertDelegate(TFrom value); + + public static TTo Convert(TFrom value) => _converter(value); + } #endif } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/NoThrowAwaiter.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/NoThrowAwaiter.cs index 81deb5747..ee136db71 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/NoThrowAwaiter.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/NoThrowAwaiter.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/TaskContinuationGenerator.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/TaskContinuationGenerator.cs index 9c8b19129..08a73431b 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/TaskContinuationGenerator.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/TaskContinuationGenerator.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.ExceptionServices; using System.Threading.Tasks; @@ -32,7 +32,8 @@ static TaskContinuationGenerator() public override TReturn SetContinuation(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) { - if (_continuation == null) return returnValue; + if (_continuation == null) + return returnValue; if (exception != null || returnValue == null) { @@ -52,7 +53,8 @@ public override TReturn SetContinuation(TTarget instance, TReturn returnValue, E private static async Task ContinuationAction(Task previousTask, TTarget target, CallTargetState state) { - if (!previousTask.IsCompleted) await new NoThrowAwaiter(previousTask, _preserveContext); + if (!previousTask.IsCompleted) + await new NoThrowAwaiter(previousTask, _preserveContext); Exception exception = null; @@ -61,8 +63,8 @@ private static async Task ContinuationAction(Task previousTask, TTarget target, else if (previousTask.Status == TaskStatus.Canceled) { try - { - // The only supported way to extract the cancellation exception is to await the task + { + // The only supported way to extract the cancellation exception is to await the task await previousTask.ConfigureAwait(_preserveContext); } catch (Exception ex) @@ -72,22 +74,23 @@ private static async Task ContinuationAction(Task previousTask, TTarget target, } try - { - // * - // Calls the CallTarget integration continuation, exceptions here should never bubble up to the application - // * + { + // * + // Calls the CallTarget integration continuation, exceptions here should never bubble up to the application + // * _continuation(target, null, exception, state); } catch (Exception ex) { IntegrationOptions.LogException(ex, "Exception occurred when calling the CallTarget integration continuation."); - } - - // * - // If the original task throws an exception we rethrow it here. - // * - if (exception != null) ExceptionDispatchInfo.Capture(exception).Throw(); + } + + // * + // If the original task throws an exception we rethrow it here. + // * + if (exception != null) + ExceptionDispatchInfo.Capture(exception).Throw(); } } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/TaskContinuationGenerator`1.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/TaskContinuationGenerator`1.cs index 80095a35d..684944bf9 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/TaskContinuationGenerator`1.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/TaskContinuationGenerator`1.cs @@ -1,18 +1,18 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.ExceptionServices; -using System.Threading.Tasks; - +using System.Threading.Tasks; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers.Continuations { internal class TaskContinuationGenerator : ContinuationGenerator @@ -34,7 +34,8 @@ static TaskContinuationGenerator() public override TReturn SetContinuation(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) { - if (_continuation == null) return returnValue; + if (_continuation == null) + return returnValue; if (exception != null || returnValue == null) { @@ -44,7 +45,8 @@ public override TReturn SetContinuation(TTarget instance, TReturn returnValue, E var previousTask = FromTReturn>(returnValue); - if (previousTask.Status == TaskStatus.RanToCompletion) return ToTReturn(Task.FromResult(_continuation(instance, previousTask.Result, default, state))); + if (previousTask.Status == TaskStatus.RanToCompletion) + return ToTReturn(Task.FromResult(_continuation(instance, previousTask.Result, default, state))); return ToTReturn(ContinuationAction(previousTask, instance, state)); } @@ -65,8 +67,8 @@ private static async Task ContinuationAction(Task previousTask else if (previousTask.Status == TaskStatus.Canceled) { try - { - // The only supported way to extract the cancellation exception is to await the task + { + // The only supported way to extract the cancellation exception is to await the task await previousTask.ConfigureAwait(_preserveContext); } catch (Exception ex) @@ -76,21 +78,21 @@ private static async Task ContinuationAction(Task previousTask } try - { - // * - // Calls the CallTarget integration continuation, exceptions here should never bubble up to the application - // * + { + // * + // Calls the CallTarget integration continuation, exceptions here should never bubble up to the application + // * continuationResult = _continuation(target, taskResult, exception, state); } catch (Exception ex) { IntegrationOptions.LogException(ex, "Exception occurred when calling the CallTarget integration continuation."); - } - - // * - // If the original task throws an exception we rethrow it here. - // * + } + + // * + // If the original task throws an exception we rethrow it here. + // * if (exception != null) ExceptionDispatchInfo.Capture(exception).Throw(); diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator.cs index 960003432..83e1ae81e 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Threading.Tasks; namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers.Continuations -{ +{ #if NETSTANDARD2_1_OR_GREATER internal class ValueTaskContinuationGenerator : ContinuationGenerator { diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator`1.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator`1.cs index f94646d26..853c2eee5 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator`1.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator`1.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; -using System.Threading.Tasks; - +using System.Threading.Tasks; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers.Continuations -{ +{ #if NETSTANDARD2_1_OR_GREATER internal class ValueTaskContinuationGenerator : ContinuationGenerator { diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/CreateAsyncEndMethodResult.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/CreateAsyncEndMethodResult.cs index 1bfa1a7e5..d8afe3d7b 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/CreateAsyncEndMethodResult.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/CreateAsyncEndMethodResult.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Reflection.Emit; namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/EndMethodHandler.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/EndMethodHandler.cs index 014d79d5c..6cf42cb9a 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/EndMethodHandler.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/EndMethodHandler.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.CompilerServices; diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/EndMethodHandler`1.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/EndMethodHandler`1.cs index 24270ff3a..afda93c66 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/EndMethodHandler`1.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/EndMethodHandler`1.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Elastic.Apm.Api; -using Elastic.Apm.Profiler.Managed.CallTarget.Handlers.Continuations; - +using Elastic.Apm.Profiler.Managed.CallTarget.Handlers.Continuations; + #pragma warning disable SA1649 // File name must match first type name - + namespace Elastic.Apm.Profiler.Managed.CallTarget.Handlers { internal static class EndMethodHandler @@ -40,12 +40,12 @@ static EndMethodHandler() { var genericReturnType = returnType.GetGenericTypeDefinition(); if (typeof(Task).IsAssignableFrom(returnType)) - { - // The type is a Task<> + { + // The type is a Task<> _continuationGenerator = (ContinuationGenerator)Activator.CreateInstance( typeof(TaskContinuationGenerator<,,,>).MakeGenericType(typeof(TIntegration), typeof(TTarget), returnType, ContinuationsHelper.GetResultType(returnType))); - } + } #if NETSTANDARD2_1_OR_GREATER else if (genericReturnType == typeof(ValueTask<>)) { @@ -59,10 +59,10 @@ static EndMethodHandler() else { if (returnType == typeof(Task)) - { - // The type is a Task + { + // The type is a Task _continuationGenerator = new TaskContinuationGenerator(); - } + } #if NETSTANDARD2_1_OR_GREATER else if (returnType == typeof(ValueTask)) { @@ -80,10 +80,10 @@ internal static CallTargetReturn Invoke(TTarget instance, TReturn retur { if (_continuationGenerator != null) { - returnValue = _continuationGenerator.SetContinuation(instance, returnValue, exception, state); - - // Restore previous scope if there is a continuation - // This is used to mimic the ExecutionContext copy from the StateMachine + returnValue = _continuationGenerator.SetContinuation(instance, returnValue, exception, state); + + // Restore previous scope if there is a continuation + // This is used to mimic the ExecutionContext copy from the StateMachine if (Agent.IsConfigured) { switch (state.PreviousSegment) diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/IntegrationMapper.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/IntegrationMapper.cs index 146b16ee3..46a102dd6 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/IntegrationMapper.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/IntegrationMapper.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Linq; @@ -29,7 +29,7 @@ internal class IntegrationMapper typeof(IntegrationMapper).GetMethod(nameof(IntegrationMapper.ConvertType), BindingFlags.NonPublic | BindingFlags.Static); internal static DynamicMethod CreateBeginMethodDelegate(Type integrationType, Type targetType, Type[] argumentsTypes) - { + { /* * OnMethodBegin signatures with 1 or more parameters with 1 or more generics: * - CallTargetState OnMethodBegin(TTarget instance); @@ -41,8 +41,8 @@ internal static DynamicMethod CreateBeginMethodDelegate(Type integrationType, Ty * - CallTargetState OnMethodBegin(TArg1 arg1, TArg2); * - CallTargetState OnMethodBegin(TArg1 arg1, TArg2, ...); * - */ - + */ + Logger.Debug($"Creating BeginMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}]"); var onMethodBeginMethodInfo = integrationType.GetMethod(BeginMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -104,18 +104,18 @@ internal static DynamicMethod CreateBeginMethodDelegate(Type integrationType, Ty onMethodBeginMethodInfo.Module, true); - var ilWriter = callMethod.GetILGenerator(); - - // Load the instance if is needed + var ilWriter = callMethod.GetILGenerator(); + + // Load the instance if is needed if (mustLoadInstance) { ilWriter.Emit(OpCodes.Ldarg_0); if (instanceGenericConstraint != null) WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); - } - - // Load arguments + } + + // Load arguments for (var i = mustLoadInstance ? 1 : 0; i < onMethodBeginParameters.Length; i++) { var sourceParameterType = argumentsTypes[mustLoadInstance ? i - 1 : i]; @@ -141,10 +141,11 @@ internal static DynamicMethod CreateBeginMethodDelegate(Type integrationType, Ty throw new InvalidCastException($"The target parameter {targetParameterType} can't be assigned from {sourceParameterType}"); WriteLoadArgument(ilWriter, i, mustLoadInstance); - if (parameterProxyType != null) WriteCreateNewProxyInstance(ilWriter, parameterProxyType, sourceParameterType); - } - - // Call method + if (parameterProxyType != null) + WriteCreateNewProxyInstance(ilWriter, parameterProxyType, sourceParameterType); + } + + // Call method onMethodBeginMethodInfo = onMethodBeginMethodInfo.MakeGenericMethod(callGenericTypes.ToArray()); ilWriter.EmitCall(OpCodes.Call, onMethodBeginMethodInfo, null); ilWriter.Emit(OpCodes.Ret); @@ -154,7 +155,7 @@ internal static DynamicMethod CreateBeginMethodDelegate(Type integrationType, Ty } internal static DynamicMethod CreateSlowBeginMethodDelegate(Type integrationType, Type targetType) - { + { /* * OnMethodBegin signatures with 1 or more parameters with 1 or more generics: * - CallTargetState OnMethodBegin(TTarget instance); @@ -166,8 +167,8 @@ internal static DynamicMethod CreateSlowBeginMethodDelegate(Type integrationType * - CallTargetState OnMethodBegin(TArg1 arg1, TArg2); * - CallTargetState OnMethodBegin(TArg1 arg1, TArg2, ...); * - */ - + */ + Logger.Debug($"Creating SlowBeginMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}]"); var onMethodBeginMethodInfo = integrationType.GetMethod(BeginMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -215,17 +216,18 @@ internal static DynamicMethod CreateSlowBeginMethodDelegate(Type integrationType onMethodBeginMethodInfo.Module, true); - var ilWriter = callMethod.GetILGenerator(); - - // Load the instance if is needed + var ilWriter = callMethod.GetILGenerator(); + + // Load the instance if is needed if (mustLoadInstance) { ilWriter.Emit(OpCodes.Ldarg_0); - if (instanceGenericConstraint != null) WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); - } - - // Load arguments + if (instanceGenericConstraint != null) + WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); + } + + // Load arguments for (var i = mustLoadInstance ? 1 : 0; i < onMethodBeginParameters.Length; i++) { var targetParameterType = onMethodBeginParameters[i].ParameterType; @@ -254,9 +256,9 @@ internal static DynamicMethod CreateSlowBeginMethodDelegate(Type integrationType ilWriter.EmitCall(OpCodes.Call, ConvertTypeMethodInfo.MakeGenericMethod(targetParameterTypeConstraint), null); else if (targetParameterType.IsValueType) ilWriter.Emit(OpCodes.Unbox_Any, targetParameterType); - } - - // Call method + } + + // Call method onMethodBeginMethodInfo = onMethodBeginMethodInfo.MakeGenericMethod(callGenericTypes.ToArray()); ilWriter.EmitCall(OpCodes.Call, onMethodBeginMethodInfo, null); ilWriter.Emit(OpCodes.Ret); @@ -266,14 +268,14 @@ internal static DynamicMethod CreateSlowBeginMethodDelegate(Type integrationType } internal static DynamicMethod CreateEndMethodDelegate(Type integrationType, Type targetType) - { + { /* * OnMethodEnd signatures with 2 or 3 parameters with 1 generics: * - CallTargetReturn OnMethodEnd(TTarget instance, Exception exception, CallTargetState state); * - CallTargetReturn OnMethodEnd(Exception exception, CallTargetState state); * - */ - + */ + Logger.Debug($"Creating EndMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}]"); var onMethodEndMethodInfo = integrationType.GetMethod(EndMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (onMethodEndMethodInfo is null) @@ -341,24 +343,24 @@ internal static DynamicMethod CreateEndMethodDelegate(Type integrationType, Type onMethodEndMethodInfo.Module, true); - var ilWriter = callMethod.GetILGenerator(); - - // Load the instance if is needed + var ilWriter = callMethod.GetILGenerator(); + + // Load the instance if is needed if (mustLoadInstance) { ilWriter.Emit(OpCodes.Ldarg_0); if (instanceGenericConstraint != null) WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); - } - - // Load the exception - ilWriter.Emit(OpCodes.Ldarg_1); - - // Load the state - ilWriter.Emit(OpCodes.Ldarg_2); - - // Call Method + } + + // Load the exception + ilWriter.Emit(OpCodes.Ldarg_1); + + // Load the state + ilWriter.Emit(OpCodes.Ldarg_2); + + // Call Method onMethodEndMethodInfo = onMethodEndMethodInfo.MakeGenericMethod(callGenericTypes.ToArray()); ilWriter.EmitCall(OpCodes.Call, onMethodEndMethodInfo, null); @@ -369,15 +371,15 @@ internal static DynamicMethod CreateEndMethodDelegate(Type integrationType, Type } internal static DynamicMethod CreateEndMethodDelegate(Type integrationType, Type targetType, Type returnType) - { + { /* * OnMethodEnd signatures with 3 or 4 parameters with 1 or 2 generics: * - CallTargetReturn OnMethodEnd(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state); * - CallTargetReturn OnMethodEnd(TReturn returnValue, Exception exception, CallTargetState state); * - CallTargetReturn<[Type]> OnMethodEnd([Type] returnValue, Exception exception, CallTargetState state); * - */ - + */ + Logger.Debug( $"Creating EndMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}, ReturnType={returnType.FullName}]"); var onMethodEndMethodInfo = integrationType.GetMethod(EndMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -470,31 +472,33 @@ internal static DynamicMethod CreateEndMethodDelegate(Type integrationType, Type onMethodEndMethodInfo.Module, true); - var ilWriter = callMethod.GetILGenerator(); - - // Load the instance if is needed + var ilWriter = callMethod.GetILGenerator(); + + // Load the instance if is needed if (mustLoadInstance) { ilWriter.Emit(OpCodes.Ldarg_0); - if (instanceGenericConstraint != null) WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); - } - - // Load the return value + if (instanceGenericConstraint != null) + WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); + } + + // Load the return value ilWriter.Emit(OpCodes.Ldarg_1); - if (returnValueProxyType != null) WriteCreateNewProxyInstance(ilWriter, returnValueProxyType, returnType); - - // Load the exception - ilWriter.Emit(OpCodes.Ldarg_2); - - // Load the state - ilWriter.Emit(OpCodes.Ldarg_3); - - // Call Method + if (returnValueProxyType != null) + WriteCreateNewProxyInstance(ilWriter, returnValueProxyType, returnType); + + // Load the exception + ilWriter.Emit(OpCodes.Ldarg_2); + + // Load the state + ilWriter.Emit(OpCodes.Ldarg_3); + + // Call Method onMethodEndMethodInfo = onMethodEndMethodInfo.MakeGenericMethod(callGenericTypes.ToArray()); - ilWriter.EmitCall(OpCodes.Call, onMethodEndMethodInfo, null); - - // Unwrap return value proxy + ilWriter.EmitCall(OpCodes.Call, onMethodEndMethodInfo, null); + + // Unwrap return value proxy if (returnValueProxyType != null) { var unwrapReturnValue = UnwrapReturnValueMethodInfo.MakeGenericMethod(returnValueProxyType, returnType); @@ -509,7 +513,7 @@ internal static DynamicMethod CreateEndMethodDelegate(Type integrationType, Type } internal static CreateAsyncEndMethodResult CreateAsyncEndMethodDelegate(Type integrationType, Type targetType, Type returnType) - { + { /* * OnAsyncMethodEnd signatures with 3 or 4 parameters with 1 or 2 generics: * - TReturn OnAsyncMethodEnd(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state); @@ -519,8 +523,8 @@ internal static CreateAsyncEndMethodResult CreateAsyncEndMethodDelegate(Type int * In case the continuation is for a Task/ValueTask, the returnValue type will be an object and the value null. * In case the continuation is for a Task/ValueTask, the returnValue type will be T with the instance value after the task completes. * - */ - + */ + Logger.Debug( $"Creating AsyncEndMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}, ReturnType={returnType.FullName}]"); var onAsyncMethodEndMethodInfo = @@ -616,33 +620,33 @@ internal static CreateAsyncEndMethodResult CreateAsyncEndMethodDelegate(Type int onAsyncMethodEndMethodInfo.Module, true); - var ilWriter = callMethod.GetILGenerator(); - - // Load the instance if is needed + var ilWriter = callMethod.GetILGenerator(); + + // Load the instance if is needed if (mustLoadInstance) { ilWriter.Emit(OpCodes.Ldarg_0); if (instanceGenericConstraint != null) WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); - } - - // Load the return value + } + + // Load the return value ilWriter.Emit(OpCodes.Ldarg_1); if (returnValueProxyType != null) - WriteCreateNewProxyInstance(ilWriter, returnValueProxyType, returnType); - - // Load the exception - ilWriter.Emit(OpCodes.Ldarg_2); - - // Load the state - ilWriter.Emit(OpCodes.Ldarg_3); - - // Call Method + WriteCreateNewProxyInstance(ilWriter, returnValueProxyType, returnType); + + // Load the exception + ilWriter.Emit(OpCodes.Ldarg_2); + + // Load the state + ilWriter.Emit(OpCodes.Ldarg_3); + + // Call Method onAsyncMethodEndMethodInfo = onAsyncMethodEndMethodInfo.MakeGenericMethod(callGenericTypes.ToArray()); - ilWriter.EmitCall(OpCodes.Call, onAsyncMethodEndMethodInfo, null); - - // Unwrap return value proxy + ilWriter.EmitCall(OpCodes.Call, onAsyncMethodEndMethodInfo, null); + + // Unwrap return value proxy if (returnValueProxyType != null) { var unwrapReturnValue = UnwrapReturnValueMethodInfo.MakeGenericMethod(returnValueProxyType, returnType); @@ -740,9 +744,9 @@ private static T ConvertType(object value) var valueType = value.GetType(); if (valueType == conversionType || conversionType.IsAssignableFrom(valueType)) - return (T)value; - - // Finally we try to duck type + return (T)value; + + // Finally we try to duck type return DuckType.Create(value); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/IntegrationOptions.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/IntegrationOptions.cs index 18844816c..64bc64e14 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/IntegrationOptions.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/Handlers/IntegrationOptions.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.CompilerServices; using Elastic.Apm.Profiler.Managed.DuckTyping; @@ -24,8 +24,8 @@ internal static class IntegrationOptions [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void LogException(Exception exception, string message = null) - { - // ReSharper disable twice ExplicitCallerInfoArgument + { + // ReSharper disable twice ExplicitCallerInfoArgument Logger.Log(LogLevel.Error, exception, message ?? "exception whilst instrumenting integration <{0}, {1}>", typeof(TIntegration).FullName, typeof(TTarget).FullName); diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/PreserveContextAttribute.cs b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/PreserveContextAttribute.cs index 23b662850..b6cf819c0 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/PreserveContextAttribute.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/CallTarget/PreserveContextAttribute.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.CallTarget -{ +{ /// /// Apply on a calltarget async callback to indicate that the method /// should execute under the current synchronization context/task scheduler. diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckAttribute.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckAttribute.cs index d13b3d3d2..4b5c2affb 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckAttribute.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckAttribute.cs @@ -1,71 +1,71 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Reflection; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck kind /// public enum DuckKind - { + { /// /// Property /// - Property, - + Property, + /// /// Field /// Field - } - + } + /// /// Duck attribute /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = false)] public class DuckAttribute : Attribute - { + { /// /// Default BindingFlags /// public const BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance - | BindingFlags.FlattenHierarchy; - + | BindingFlags.FlattenHierarchy; + /// /// Gets or sets the underlying type member name /// - public string Name { get; set; } - + public string Name { get; set; } + /// /// Gets or sets duck kind /// - public DuckKind Kind { get; set; } = DuckKind.Property; - + public DuckKind Kind { get; set; } = DuckKind.Property; + /// /// Gets or sets the binding flags /// - public BindingFlags BindingFlags { get; set; } = DefaultFlags; - + public BindingFlags BindingFlags { get; set; } = DefaultFlags; + /// /// Gets or sets the generic parameter type names definition for a generic method call (required when calling generic methods and instance type is non public) /// - public string[] GenericParameterTypeNames { get; set; } - + public string[] GenericParameterTypeNames { get; set; } + /// /// Gets or sets the parameter type names of the target method (optional / used to disambiguation) /// - public string[] ParameterTypeNames { get; set; } - + public string[] ParameterTypeNames { get; set; } + /// /// Gets or sets the explicit interface type name /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckCopyAttribute.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckCopyAttribute.cs index b7f7b81cc..d0e31e384 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckCopyAttribute.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckCopyAttribute.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck copy struct attribute /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckFieldAttribute.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckFieldAttribute.cs index 464466a48..fe665166a 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckFieldAttribute.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckFieldAttribute.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck attribute where the underlying member is a field /// public class DuckFieldAttribute : DuckAttribute - { + { /// /// Initializes a new instance of the class. /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckIgnoreAttribute.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckIgnoreAttribute.cs index cb82b25ec..b8cc6b715 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckIgnoreAttribute.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckIgnoreAttribute.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Ignores the member when DuckTyping /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckIncludeAttribute.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckIncludeAttribute.cs index 919ae38bc..edaa7e196 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckIncludeAttribute.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckIncludeAttribute.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Use to include a member that would normally be ignored /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckReverseMethodAttribute.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckReverseMethodAttribute.cs index 07eda5c8b..75a61ad82 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckReverseMethodAttribute.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckReverseMethodAttribute.cs @@ -1,34 +1,34 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck reverse method attribute /// [AttributeUsage(AttributeTargets.Method)] public class DuckReverseMethodAttribute : Attribute - { + { /// /// Initializes a new instance of the class. /// - public DuckReverseMethodAttribute() { } - + public DuckReverseMethodAttribute() { } + /// /// Initializes a new instance of the class. /// /// Methods arguments - public DuckReverseMethodAttribute(params string[] arguments) => Arguments = arguments; - + public DuckReverseMethodAttribute(params string[] arguments) => Arguments = arguments; + /// /// Gets the methods arguments /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Fields.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Fields.cs index 983d618d8..8a6464c7e 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Fields.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Fields.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Reflection; using System.Reflection.Emit; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck Type /// @@ -35,58 +35,60 @@ FieldInfo instanceField Type.EmptyTypes); var il = new LazyILGenerator(proxyMethod.GetILGenerator()); - var returnType = targetField.FieldType; - - // Load the instance + var returnType = targetField.FieldType; + + // Load the instance if (!targetField.IsStatic) { il.Emit(OpCodes.Ldarg_0); il.Emit(instanceField.FieldType.IsValueType ? OpCodes.Ldflda : OpCodes.Ldfld, instanceField); - } - - // Load the field value to the stack + } + + // Load the field value to the stack if (UseDirectAccessTo(proxyTypeBuilder, targetType) && targetField.IsPublic) - { - // In case is public is pretty simple + { + // In case is public is pretty simple il.Emit(targetField.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, targetField); } else - { - // If the instance or the field are non public we need to create a Dynamic method to overpass the visibility checks - // we can't access non public types so we have to cast to object type (in the instance object and the return type if is needed). + { + // If the instance or the field are non public we need to create a Dynamic method to overpass the visibility checks + // we can't access non public types so we have to cast to object type (in the instance object and the return type if is needed). var dynMethodName = $"_getNonPublicField_{targetField.DeclaringType.Name}_{targetField.Name}"; - returnType = UseDirectAccessTo(proxyTypeBuilder, targetField.FieldType) ? targetField.FieldType : typeof(object); - - // We create the dynamic method + returnType = UseDirectAccessTo(proxyTypeBuilder, targetField.FieldType) ? targetField.FieldType : typeof(object); + + // We create the dynamic method var dynParameters = targetField.IsStatic ? Type.EmptyTypes : new[] { typeof(object) }; - var dynMethod = new DynamicMethod(dynMethodName, returnType, dynParameters, proxyTypeBuilder.Module, true); - - // Emit the dynamic method body + var dynMethod = new DynamicMethod(dynMethodName, returnType, dynParameters, proxyTypeBuilder.Module, true); + + // Emit the dynamic method body var dynIL = new LazyILGenerator(dynMethod.GetILGenerator()); if (!targetField.IsStatic) - { - // Emit the instance load in the dynamic method + { + // Emit the instance load in the dynamic method dynIL.Emit(OpCodes.Ldarg_0); - if (targetField.DeclaringType != typeof(object)) dynIL.Emit(targetField.DeclaringType!.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, targetField.DeclaringType); - } - - // Emit the field and convert before returning (in case of boxing) + if (targetField.DeclaringType != typeof(object)) + dynIL.Emit(targetField.DeclaringType!.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, targetField.DeclaringType); + } + + // Emit the field and convert before returning (in case of boxing) dynIL.Emit(targetField.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, targetField); dynIL.WriteTypeConversion(targetField.FieldType, returnType); dynIL.Emit(OpCodes.Ret); - dynIL.Flush(); - - // Emit the call to the dynamic method + dynIL.Flush(); + + // Emit the call to the dynamic method il.WriteDynamicMethodCall(dynMethod, proxyTypeBuilder); - } - - // Check if the type can be converted or if we need to enable duck chaining + } + + // Check if the type can be converted or if we need to enable duck chaining if (DuckType.NeedsDuckChaining(targetField.FieldType, proxyMemberReturnType)) { - if (UseDirectAccessTo(proxyTypeBuilder, targetField.FieldType) && targetField.FieldType.IsValueType) il.Emit(OpCodes.Box, targetField.FieldType); - - // We call DuckType.CreateCache<>.Create() + if (UseDirectAccessTo(proxyTypeBuilder, targetField.FieldType) && targetField.FieldType.IsValueType) + il.Emit(OpCodes.Box, targetField.FieldType); + + // We call DuckType.CreateCache<>.Create() var getProxyMethodInfo = typeof(DuckType.CreateCache<>) .MakeGenericType(proxyMemberReturnType) .GetMethod("Create"); @@ -94,8 +96,8 @@ FieldInfo instanceField il.Emit(OpCodes.Call, getProxyMethodInfo); } else if (returnType != proxyMemberReturnType) - { - // If the type is not the expected type we try a conversion. + { + // If the type is not the expected type we try a conversion. il.WriteTypeConversion(returnType, proxyMemberReturnType); } @@ -121,56 +123,56 @@ FieldInfo instanceField new[] { proxyMemberReturnType }); var il = new LazyILGenerator(method.GetILGenerator()); - var currentValueType = proxyMemberReturnType; - - // Load instance + var currentValueType = proxyMemberReturnType; + + // Load instance if (!targetField.IsStatic) { il.Emit(OpCodes.Ldarg_0); il.Emit(instanceField.FieldType.IsValueType ? OpCodes.Ldflda : OpCodes.Ldfld, instanceField); - } - - // Check if the type can be converted of if we need to enable duck chaining + } + + // Check if the type can be converted of if we need to enable duck chaining if (DuckType.NeedsDuckChaining(targetField.FieldType, proxyMemberReturnType)) - { - // Load the argument and convert it to Duck type + { + // Load the argument and convert it to Duck type il.Emit(OpCodes.Ldarg_1); - il.WriteTypeConversion(proxyMemberReturnType, typeof(IDuckType)); - - // Call IDuckType.Instance property to get the actual value + il.WriteTypeConversion(proxyMemberReturnType, typeof(IDuckType)); + + // Call IDuckType.Instance property to get the actual value il.EmitCall(OpCodes.Callvirt, DuckTypeInstancePropertyInfo.GetMethod, null); currentValueType = typeof(object); } else - { - // Load the value into the stack + { + // Load the value into the stack il.Emit(OpCodes.Ldarg_1); - } - - // We set the field value + } + + // We set the field value if (UseDirectAccessTo(proxyTypeBuilder, targetType) && targetField.IsPublic) - { - // If the instance and the field are public then is easy to set. + { + // If the instance and the field are public then is easy to set. il.WriteTypeConversion(currentValueType, targetField.FieldType); il.Emit(targetField.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, targetField); } else - { - // If the instance or the field are non public we need to create a Dynamic method to overpass the visibility checks - - var dynMethodName = $"_setField_{targetField.DeclaringType.Name}_{targetField.Name}"; - - // Convert the field type for the dynamic method + { + // If the instance or the field are non public we need to create a Dynamic method to overpass the visibility checks + + var dynMethodName = $"_setField_{targetField.DeclaringType.Name}_{targetField.Name}"; + + // Convert the field type for the dynamic method var dynValueType = UseDirectAccessTo(proxyTypeBuilder, targetField.FieldType) ? targetField.FieldType : typeof(object); - il.WriteTypeConversion(currentValueType, dynValueType); - - // Create dynamic method + il.WriteTypeConversion(currentValueType, dynValueType); + + // Create dynamic method var dynParameters = targetField.IsStatic ? new[] { dynValueType } : new[] { typeof(object), dynValueType }; - var dynMethod = new DynamicMethod(dynMethodName, typeof(void), dynParameters, proxyTypeBuilder.Module, true); - - // Write the dynamic method body + var dynMethod = new DynamicMethod(dynMethodName, typeof(void), dynParameters, proxyTypeBuilder.Module, true); + + // Write the dynamic method body var dynIL = new LazyILGenerator(dynMethod.GetILGenerator()); dynIL.Emit(OpCodes.Ldarg_0); @@ -181,7 +183,8 @@ FieldInfo instanceField } else { - if (targetField.DeclaringType != typeof(object)) dynIL.Emit(OpCodes.Castclass, targetField.DeclaringType); + if (targetField.DeclaringType != typeof(object)) + dynIL.Emit(OpCodes.Castclass, targetField.DeclaringType); dynIL.Emit(OpCodes.Ldarg_1); dynIL.WriteTypeConversion(dynValueType, targetField.FieldType); @@ -189,9 +192,9 @@ FieldInfo instanceField } dynIL.Emit(OpCodes.Ret); - dynIL.Flush(); - - // Emit the call to the dynamic method + dynIL.Flush(); + + // Emit the call to the dynamic method il.WriteDynamicMethodCall(dynMethod, proxyTypeBuilder); } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Methods.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Methods.cs index a696760c6..965260219 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Methods.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Methods.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Linq; @@ -15,7 +15,7 @@ using System.Reflection.Emit; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck Type /// @@ -23,8 +23,8 @@ public static partial class DuckType { private static List GetMethods(Type baseType) { - var selectedMethods = new List(GetBaseMethods(baseType)); - // If the base type is an interface we must make sure we implement all methods, including from other interfaces + var selectedMethods = new List(GetBaseMethods(baseType)); + // If the base type is an interface we must make sure we implement all methods, including from other interfaces if (baseType.IsInterface) { var implementedInterfaces = baseType.GetInterfaces(); @@ -65,10 +65,10 @@ private static List GetMethods(Type baseType) static IEnumerable GetBaseMethods(Type baseType) { foreach (var method in baseType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) - { - // Avoid proxying object methods like ToString(), GetHashCode() - // or the Finalize() that creates problems by keeping alive the object to another collection. - // You can still proxy those methods if they are defined in an interface, or if you add the DuckInclude attribute. + { + // Avoid proxying object methods like ToString(), GetHashCode() + // or the Finalize() that creates problems by keeping alive the object to another collection. + // You can still proxy those methods if they are defined in an interface, or if you add the DuckInclude attribute. if (method.DeclaringType == typeof(object)) { var include = method.GetCustomAttribute(true) is not null; @@ -99,31 +99,31 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, } foreach (var proxyMethodDefinition in proxyMethodsDefinitions) - { - // Ignore the method marked with `DuckIgnore` attribute + { + // Ignore the method marked with `DuckIgnore` attribute if (proxyMethodDefinition.GetCustomAttribute(true) is not null) - continue; - - // Extract the method parameters types + continue; + + // Extract the method parameters types var proxyMethodDefinitionParameters = proxyMethodDefinition.GetParameters(); - var proxyMethodDefinitionParametersTypes = proxyMethodDefinitionParameters.Select(p => p.ParameterType).ToArray(); - - // We select the target method to call + var proxyMethodDefinitionParametersTypes = proxyMethodDefinitionParameters.Select(p => p.ParameterType).ToArray(); + + // We select the target method to call var targetMethod = SelectTargetMethod(targetType, proxyMethodDefinition, proxyMethodDefinitionParameters, - proxyMethodDefinitionParametersTypes); - - // If the target method couldn't be found and the proxy method doesn't have an implementation already (ex: abstract and virtual classes) we throw. + proxyMethodDefinitionParametersTypes); + + // If the target method couldn't be found and the proxy method doesn't have an implementation already (ex: abstract and virtual classes) we throw. if (targetMethod is null && proxyMethodDefinition.IsVirtual) - DuckTypeTargetMethodNotFoundException.Throw(proxyMethodDefinition); - - // Check if target method is a reverse method - var isReverse = targetMethod.GetCustomAttribute(true) is not null; - - // Gets the proxy method definition generic arguments + DuckTypeTargetMethodNotFoundException.Throw(proxyMethodDefinition); + + // Check if target method is a reverse method + var isReverse = targetMethod.GetCustomAttribute(true) is not null; + + // Gets the proxy method definition generic arguments var proxyMethodDefinitionGenericArguments = proxyMethodDefinition.GetGenericArguments(); - var proxyMethodDefinitionGenericArgumentsNames = proxyMethodDefinitionGenericArguments.Select(a => a.Name).ToArray(); - - // Checks if the target method is a generic method while the proxy method is non generic (checks if the Duck attribute contains the generic parameters) + var proxyMethodDefinitionGenericArgumentsNames = proxyMethodDefinitionGenericArguments.Select(a => a.Name).ToArray(); + + // Checks if the target method is a generic method while the proxy method is non generic (checks if the Duck attribute contains the generic parameters) var targetMethodGenericArguments = targetMethod.GetGenericArguments(); if (proxyMethodDefinitionGenericArguments.Length == 0 && targetMethodGenericArguments.Length > 0) { @@ -136,23 +136,23 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, targetMethod = targetMethod.MakeGenericMethod(proxyDuckAttribute.GenericParameterTypeNames.Select(name => Type.GetType(name)) .ToArray()); - } - - // Gets target method parameters + } + + // Gets target method parameters var targetMethodParameters = targetMethod.GetParameters(); - var targetMethodParametersTypes = targetMethodParameters.Select(p => p.ParameterType).ToArray(); - - // Make sure we have the right methods attributes. - var proxyMethodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig; - - // Create the proxy method implementation + var targetMethodParametersTypes = targetMethodParameters.Select(p => p.ParameterType).ToArray(); + + // Make sure we have the right methods attributes. + var proxyMethodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig; + + // Create the proxy method implementation var proxyMethodParametersBuilders = new ParameterBuilder[proxyMethodDefinitionParameters.Length]; var proxyMethod = proxyTypeBuilder.DefineMethod(proxyMethodDefinition.Name, proxyMethodAttributes, proxyMethodDefinition.ReturnType, proxyMethodDefinitionParametersTypes); if (proxyMethodDefinitionGenericArgumentsNames.Length > 0) - _ = proxyMethod.DefineGenericParameters(proxyMethodDefinitionGenericArgumentsNames); - - // Define the proxy method implementation parameters for optional parameters with default values + _ = proxyMethod.DefineGenericParameters(proxyMethodDefinitionGenericArgumentsNames); + + // Define the proxy method implementation parameters for optional parameters with default values for (var j = 0; j < proxyMethodDefinitionParameters.Length; j++) { var pmDefParameter = proxyMethodDefinitionParameters[j]; @@ -165,16 +165,16 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, var il = new LazyILGenerator(proxyMethod.GetILGenerator()); var returnType = targetMethod.ReturnType; - List outputAndRefParameters = null; - - // Load the instance if needed + List outputAndRefParameters = null; + + // Load the instance if needed if (!targetMethod.IsStatic) { il.Emit(OpCodes.Ldarg_0); il.Emit(instanceField.FieldType.IsValueType ? OpCodes.Ldflda : OpCodes.Ldfld, instanceField); - } - - // Load all the arguments / parameters + } + + // Load all the arguments / parameters var maxParamLength = Math.Max(proxyMethodDefinitionParameters.Length, targetMethodParameters.Length); for (var idx = 0; idx < maxParamLength; idx++) { @@ -182,19 +182,19 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, var targetParamInfo = targetMethodParameters[idx]; if (proxyParamInfo is null) - { - // The proxy method is missing parameters, we check if the target parameter is optional + { + // The proxy method is missing parameters, we check if the target parameter is optional if (!targetParamInfo.IsOptional) - { - // The target method parameter is not optional. + { + // The target method parameter is not optional. DuckTypeProxyMethodParameterIsMissingException.Throw(proxyMethodDefinition, targetParamInfo); } } else { if (proxyParamInfo.IsOut != targetParamInfo.IsOut || proxyParamInfo.IsIn != targetParamInfo.IsIn) - { - // the proxy and target parameters doesn't have the same signature + { + // the proxy and target parameters doesn't have the same signature DuckTypeProxyAndTargetMethodParameterSignatureMismatchException.Throw(proxyMethodDefinition, targetMethod); } @@ -202,40 +202,40 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, var targetParamType = targetParamInfo.ParameterType; if (proxyParamType.IsByRef != targetParamType.IsByRef) - { - // the proxy and target parameters doesn't have the same signature + { + // the proxy and target parameters doesn't have the same signature DuckTypeProxyAndTargetMethodParameterSignatureMismatchException.Throw(proxyMethodDefinition, targetMethod); - } - - // We check if we have to handle an output parameter, by ref parameter or a normal parameter + } + + // We check if we have to handle an output parameter, by ref parameter or a normal parameter if (proxyParamInfo.IsOut) - { - // If is an output parameter with diferent types we need to handle differently - // by creating a local var first to store the target parameter out value - // and then try to set the output parameter of the proxy method by converting the value (a base class or a duck typing) + { + // If is an output parameter with diferent types we need to handle differently + // by creating a local var first to store the target parameter out value + // and then try to set the output parameter of the proxy method by converting the value (a base class or a duck typing) if (proxyParamType != targetParamType) { - var localTargetArg = il.DeclareLocal(targetParamType.GetElementType()); - - // We need to store the output parameter data to set the proxy parameter value after we call the target method + var localTargetArg = il.DeclareLocal(targetParamType.GetElementType()); + + // We need to store the output parameter data to set the proxy parameter value after we call the target method if (outputAndRefParameters is null) outputAndRefParameters = new List(); outputAndRefParameters.Add(new OutputAndRefParameterData(localTargetArg.LocalIndex, targetParamType, idx, - proxyParamType)); - - // Load the local var ref (to be used in the target method param as output) + proxyParamType)); + + // Load the local var ref (to be used in the target method param as output) il.Emit(OpCodes.Ldloca_S, localTargetArg.LocalIndex); } else il.WriteLoadArgument(idx, false); } else if (proxyParamType.IsByRef) - { - // If is a ref parameter with diferent types we need to handle differently - // by creating a local var first to store the initial proxy parameter ref value casted to the target parameter type ( this cast may fail at runtime ) - // later pass this local var ref to the target method, and then, modify the proxy parameter ref with the new reference from the target method - // by converting the value (a base class or a duck typing) + { + // If is a ref parameter with diferent types we need to handle differently + // by creating a local var first to store the initial proxy parameter ref value casted to the target parameter type ( this cast may fail at runtime ) + // later pass this local var ref to the target method, and then, modify the proxy parameter ref with the new reference from the target method + // by converting the value (a base class or a duck typing) if (proxyParamType != targetParamType) { var proxyParamTypeElementType = proxyParamType.GetElementType(); @@ -247,25 +247,25 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, targetParamTypeElementType = typeof(object); } - var localTargetArg = il.DeclareLocal(targetParamTypeElementType); - - // We need to store the ref parameter data to set the proxy parameter value after we call the target method + var localTargetArg = il.DeclareLocal(targetParamTypeElementType); + + // We need to store the ref parameter data to set the proxy parameter value after we call the target method if (outputAndRefParameters is null) outputAndRefParameters = new List(); outputAndRefParameters.Add(new OutputAndRefParameterData(localTargetArg.LocalIndex, targetParamType, idx, - proxyParamType)); - - // Load the argument (ref) - il.WriteLoadArgument(idx, false); - - // Load the value inside the ref - il.Emit(OpCodes.Ldind_Ref); - - // Check if the type can be converted of if we need to enable duck chaining + proxyParamType)); + + // Load the argument (ref) + il.WriteLoadArgument(idx, false); + + // Load the value inside the ref + il.Emit(OpCodes.Ldind_Ref); + + // Check if the type can be converted of if we need to enable duck chaining if (NeedsDuckChaining(targetParamTypeElementType, proxyParamTypeElementType)) - { - // First we check if the value is null before trying to get the instance value + { + // First we check if the value is null before trying to get the instance value var lblCallGetInstance = il.DefineLabel(); var lblAfterGetInstance = il.DefineLabel(); @@ -274,43 +274,43 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, il.Emit(OpCodes.Pop); il.Emit(OpCodes.Ldnull); - il.Emit(OpCodes.Br_S, lblAfterGetInstance); - - // Call IDuckType.Instance property to get the actual value + il.Emit(OpCodes.Br_S, lblAfterGetInstance); + + // Call IDuckType.Instance property to get the actual value il.MarkLabel(lblCallGetInstance); il.Emit(OpCodes.Castclass, typeof(IDuckType)); il.EmitCall(OpCodes.Callvirt, DuckTypeInstancePropertyInfo.GetMethod, null); il.MarkLabel(lblAfterGetInstance); - } - - // Cast the value to the target type - il.WriteSafeTypeConversion(proxyParamTypeElementType, targetParamTypeElementType); - - // Store the casted value to the local var - il.WriteStoreLocal(localTargetArg.LocalIndex); - - // Load the local var ref (to be used in the target method param) + } + + // Cast the value to the target type + il.WriteSafeTypeConversion(proxyParamTypeElementType, targetParamTypeElementType); + + // Store the casted value to the local var + il.WriteStoreLocal(localTargetArg.LocalIndex); + + // Load the local var ref (to be used in the target method param) il.Emit(OpCodes.Ldloca_S, localTargetArg.LocalIndex); } else il.WriteLoadArgument(idx, false); } else if (!isReverse) - { - // Check if the type can be converted of if we need to enable duck chaining + { + // Check if the type can be converted of if we need to enable duck chaining if (NeedsDuckChaining(targetParamType, proxyParamType)) - { - // Load the argument and cast it as Duck type + { + // Load the argument and cast it as Duck type il.WriteLoadArgument(idx, false); - il.Emit(OpCodes.Castclass, typeof(IDuckType)); - - // Call IDuckType.Instance property to get the actual value + il.Emit(OpCodes.Castclass, typeof(IDuckType)); + + // Call IDuckType.Instance property to get the actual value il.EmitCall(OpCodes.Callvirt, DuckTypeInstancePropertyInfo.GetMethod, null); } else - il.WriteLoadArgument(idx, false); - - // If the target parameter type is public or if it's by ref we have to actually use the original target type. + il.WriteLoadArgument(idx, false); + + // If the target parameter type is public or if it's by ref we have to actually use the original target type. targetParamType = UseDirectAccessTo(proxyTypeBuilder, targetParamType) ? targetParamType : typeof(object); il.WriteSafeTypeConversion(proxyParamType, targetParamType); @@ -319,13 +319,13 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, else { if (NeedsDuckChaining(proxyParamType, targetParamType)) - { - // Load the argument (our proxy type) and cast it as Duck type (the original type) + { + // Load the argument (our proxy type) and cast it as Duck type (the original type) il.WriteLoadArgument(idx, false); if (UseDirectAccessTo(proxyTypeBuilder, proxyParamType) && proxyParamType.IsValueType) - il.Emit(OpCodes.Box, proxyParamType); - - // We call DuckType.CreateCache<>.Create(object instance) + il.Emit(OpCodes.Box, proxyParamType); + + // We call DuckType.CreateCache<>.Create(object instance) var getProxyMethodInfo = typeof(CreateCache<>) .MakeGenericType(targetParamType) .GetMethod("Create"); @@ -333,53 +333,55 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, il.Emit(OpCodes.Call, getProxyMethodInfo); } else - il.WriteLoadArgument(idx, false); - - // If the target parameter type is public or if it's by ref we have to actually use the original target type. + il.WriteLoadArgument(idx, false); + + // If the target parameter type is public or if it's by ref we have to actually use the original target type. targetParamType = UseDirectAccessTo(proxyTypeBuilder, targetParamType) ? targetParamType : typeof(object); il.WriteSafeTypeConversion(proxyParamType, targetParamType); targetMethodParametersTypes[idx] = targetParamType; } } - } - - // Call the target method + } + + // Call the target method if (UseDirectAccessTo(proxyTypeBuilder, targetType)) - { - // If the instance is public we can emit directly without any dynamic method - - // Create generic method call - if (proxyMethodDefinitionGenericArguments.Length > 0) targetMethod = targetMethod.MakeGenericMethod(proxyMethodDefinitionGenericArguments); - - // Method call - // A generic method cannot be called using calli (throws System.InvalidOperationException) + { + // If the instance is public we can emit directly without any dynamic method + + // Create generic method call + if (proxyMethodDefinitionGenericArguments.Length > 0) + targetMethod = targetMethod.MakeGenericMethod(proxyMethodDefinitionGenericArguments); + + // Method call + // A generic method cannot be called using calli (throws System.InvalidOperationException) if (targetMethod.IsPublic || targetMethod.IsGenericMethod) - { - // We can emit a normal call if we have a public instance with a public target method. + { + // We can emit a normal call if we have a public instance with a public target method. il.EmitCall(targetMethod.IsStatic || targetMethod.DeclaringType.IsValueType ? OpCodes.Call : OpCodes.Callvirt, targetMethod, null); } else - { - // In case we have a public instance and a non public target method we can use [Calli] with the function pointer + { + // In case we have a public instance and a non public target method we can use [Calli] with the function pointer il.WriteMethodCalli(targetMethod); } } else - { - // A generic method call can't be made from a DynamicMethod - if (proxyMethodDefinitionGenericArguments.Length > 0) DuckTypeProxyMethodsWithGenericParametersNotSupportedInNonPublicInstancesException.Throw(proxyMethod); - - // If the instance is not public we need to create a Dynamic method to overpass the visibility checks - // we can't access non public types so we have to cast to object type (in the instance object and the return type). - + { + // A generic method call can't be made from a DynamicMethod + if (proxyMethodDefinitionGenericArguments.Length > 0) + DuckTypeProxyMethodsWithGenericParametersNotSupportedInNonPublicInstancesException.Throw(proxyMethod); + + // If the instance is not public we need to create a Dynamic method to overpass the visibility checks + // we can't access non public types so we have to cast to object type (in the instance object and the return type). + var dynMethodName = $"_callMethod_{targetMethod.DeclaringType.Name}_{targetMethod.Name}"; returnType = UseDirectAccessTo(proxyTypeBuilder, targetMethod.ReturnType) && !targetMethod.ReturnType.IsGenericParameter ? targetMethod.ReturnType - : typeof(object); - - // We create the dynamic method + : typeof(object); + + // We create the dynamic method var originalTargetParameters = targetMethod.GetParameters().Select(p => p.ParameterType).ToArray(); var targetParameters = targetMethod.IsStatic ? originalTargetParameters @@ -387,9 +389,9 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, var dynParameters = targetMethod.IsStatic ? targetMethodParametersTypes : (new[] { typeof(object) }).Concat(targetMethodParametersTypes).ToArray(); - var dynMethod = new DynamicMethod(dynMethodName, returnType, dynParameters, proxyTypeBuilder.Module, true); - - // Emit the dynamic method body + var dynMethod = new DynamicMethod(dynMethodName, returnType, dynParameters, proxyTypeBuilder.Module, true); + + // Emit the dynamic method body var dynIL = new LazyILGenerator(dynMethod.GetILGenerator()); if (!targetMethod.IsStatic) @@ -399,50 +401,50 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, { dynIL.WriteLoadArgument(idx, true); dynIL.WriteSafeTypeConversion(dynParameters[idx], targetParameters[idx]); - } - - // Check if we can emit a normal Call/CallVirt to the target method + } + + // Check if we can emit a normal Call/CallVirt to the target method if (!targetMethod.ContainsGenericParameters) { dynIL.EmitCall(targetMethod.IsStatic || targetMethod.DeclaringType.IsValueType ? OpCodes.Call : OpCodes.Callvirt, targetMethod, null); } else - { - // We can't emit a call to a method with generics from a DynamicMethod - // Instead we emit a Calli with the function pointer. + { + // We can't emit a call to a method with generics from a DynamicMethod + // Instead we emit a Calli with the function pointer. dynIL.WriteMethodCalli(targetMethod); } dynIL.WriteSafeTypeConversion(targetMethod.ReturnType, returnType); dynIL.Emit(OpCodes.Ret); - dynIL.Flush(); - - // Emit the call to the dynamic method + dynIL.Flush(); + + // Emit the call to the dynamic method il.WriteDynamicMethodCall(dynMethod, proxyTypeBuilder); - } - - // We check if we have output or ref parameters to set in the proxy method + } + + // We check if we have output or ref parameters to set in the proxy method if (outputAndRefParameters != null) { foreach (var outOrRefParameter in outputAndRefParameters) { var proxyArgumentType = outOrRefParameter.ProxyArgumentType.GetElementType(); - var localType = outOrRefParameter.LocalType.GetElementType(); - - // We load the argument to be set - il.WriteLoadArgument(outOrRefParameter.ProxyArgumentIndex, false); - - // We load the value from the local - il.WriteLoadLocal(outOrRefParameter.LocalIndex); - - // If we detect duck chaining we create a new proxy instance with the output of the original target method + var localType = outOrRefParameter.LocalType.GetElementType(); + + // We load the argument to be set + il.WriteLoadArgument(outOrRefParameter.ProxyArgumentIndex, false); + + // We load the value from the local + il.WriteLoadLocal(outOrRefParameter.LocalIndex); + + // If we detect duck chaining we create a new proxy instance with the output of the original target method if (NeedsDuckChaining(localType, proxyArgumentType)) { if (localType.IsValueType) - il.Emit(OpCodes.Box, localType); - - // We call DuckType.CreateCache<>.Create() + il.Emit(OpCodes.Box, localType); + + // We call DuckType.CreateCache<>.Create() var getProxyMethodInfo = typeof(CreateCache<>) .MakeGenericType(proxyArgumentType) .GetMethod("Create"); @@ -450,24 +452,24 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, il.Emit(OpCodes.Call, getProxyMethodInfo); } else - il.WriteSafeTypeConversion(localType, proxyArgumentType); - - // We store the value + il.WriteSafeTypeConversion(localType, proxyArgumentType); + + // We store the value il.Emit(OpCodes.Stind_Ref); } - } - - // Check if the target method returns something + } + + // Check if the target method returns something if (targetMethod.ReturnType != typeof(void)) - { - // Handle the return value - // Check if the type can be converted or if we need to enable duck chaining + { + // Handle the return value + // Check if the type can be converted or if we need to enable duck chaining if (NeedsDuckChaining(targetMethod.ReturnType, proxyMethodDefinition.ReturnType)) { if (UseDirectAccessTo(proxyTypeBuilder, targetMethod.ReturnType) && targetMethod.ReturnType.IsValueType) - il.Emit(OpCodes.Box, targetMethod.ReturnType); - - // We call DuckType.CreateCache<>.Create() + il.Emit(OpCodes.Box, targetMethod.ReturnType); + + // We call DuckType.CreateCache<>.Create() var getProxyMethodInfo = typeof(CreateCache<>) .MakeGenericType(proxyMethodDefinition.ReturnType) .GetMethod("Create"); @@ -475,8 +477,8 @@ private static void CreateMethods(TypeBuilder proxyTypeBuilder, Type proxyType, il.Emit(OpCodes.Call, getProxyMethodInfo); } else if (returnType != proxyMethodDefinition.ReturnType) - { - // If the type is not the expected type we try a conversion. + { + // If the type is not the expected type we try a conversion. il.WriteSafeTypeConversion(returnType, proxyMethodDefinition.ReturnType); } } @@ -494,9 +496,9 @@ Type[] proxyMethodParametersTypes var proxyMethodDuckAttribute = proxyMethod.GetCustomAttribute(true) ?? new DuckAttribute(); proxyMethodDuckAttribute.Name ??= proxyMethod.Name; - MethodInfo targetMethod = null; - - // Check if the duck attribute has the parameter type names to use for selecting the target method, in case of not found an exception is thrown. + MethodInfo targetMethod = null; + + // Check if the duck attribute has the parameter type names to use for selecting the target method, in case of not found an exception is thrown. if (proxyMethodDuckAttribute.ParameterTypeNames != null) { var parameterTypes = proxyMethodDuckAttribute.ParameterTypeNames.Select(pName => Type.GetType(pName, true)).ToArray(); @@ -505,53 +507,53 @@ Type[] proxyMethodParametersTypes DuckTypeTargetMethodNotFoundException.Throw(proxyMethod); return targetMethod; - } - - // If the duck attribute doesn't specify the parameters to use, we do the best effor to find a target method without any ambiguity. - - // First we try with the current proxy parameter types + } + + // If the duck attribute doesn't specify the parameters to use, we do the best effor to find a target method without any ambiguity. + + // First we try with the current proxy parameter types targetMethod = targetType.GetMethod(proxyMethodDuckAttribute.Name, proxyMethodDuckAttribute.BindingFlags, null, proxyMethodParametersTypes, null); if (targetMethod != null) - return targetMethod; - - // If the method wasn't found could be because a DuckType interface is being use in the parameters or in the return value. - // Also this can happen if the proxy parameters type uses a base object (ex: System.Object) instead the type. - // In this case we try to find a method that we can match, in case of ambiguity (> 1 method found) we throw an exception. - + return targetMethod; + + // If the method wasn't found could be because a DuckType interface is being use in the parameters or in the return value. + // Also this can happen if the proxy parameters type uses a base object (ex: System.Object) instead the type. + // In this case we try to find a method that we can match, in case of ambiguity (> 1 method found) we throw an exception. + var allTargetMethods = targetType.GetMethods(DuckAttribute.DefaultFlags); foreach (var candidateMethod in allTargetMethods) { var name = proxyMethodDuckAttribute.Name; - var useRelaxedNameComparison = false; - - // If there is an explicit interface type name we add it to the name + var useRelaxedNameComparison = false; + + // If there is an explicit interface type name we add it to the name if (!string.IsNullOrEmpty(proxyMethodDuckAttribute.ExplicitInterfaceTypeName)) { var interfaceTypeName = proxyMethodDuckAttribute.ExplicitInterfaceTypeName; if (interfaceTypeName == "*") - { - // If a wildcard is use, then we relax the name comparison so it can be an implicit or explicity implementation + { + // If a wildcard is use, then we relax the name comparison so it can be an implicit or explicity implementation useRelaxedNameComparison = true; } else - { - // Nested types are separated with a "." on explicit implementation. + { + // Nested types are separated with a "." on explicit implementation. interfaceTypeName = interfaceTypeName.Replace("+", "."); name = interfaceTypeName + "." + name; } - } - - // We omit target methods with different names. + } + + // We omit target methods with different names. if (candidateMethod.Name != name) { if (!useRelaxedNameComparison || !candidateMethod.Name.EndsWith("." + name)) continue; - } - - // Check if the candidate method is a reverse mapped method + } + + // Check if the candidate method is a reverse mapped method var reverseMethodAttribute = candidateMethod.GetCustomAttribute(true); if (reverseMethodAttribute?.Arguments is not null) { @@ -573,12 +575,13 @@ Type[] proxyMethodParametersTypes return candidateMethod; } - var candidateParameters = candidateMethod.GetParameters(); - - // The proxy must have the same or less parameters than the candidate ( less is due to possible optional parameters in the candidate ). - if (proxyMethodParameters.Length > candidateParameters.Length) continue; - - // We compare the target method candidate parameter by parameter. + var candidateParameters = candidateMethod.GetParameters(); + + // The proxy must have the same or less parameters than the candidate ( less is due to possible optional parameters in the candidate ). + if (proxyMethodParameters.Length > candidateParameters.Length) + continue; + + // We compare the target method candidate parameter by parameter. var skip = false; for (var i = 0; i < proxyMethodParametersTypes.Length; i++) { @@ -586,51 +589,51 @@ Type[] proxyMethodParametersTypes var candidateParam = candidateParameters[i]; var proxyParamType = proxyParam.ParameterType; - var candidateParamType = candidateParam.ParameterType; - - // both needs to have the same parameter direction + var candidateParamType = candidateParam.ParameterType; + + // both needs to have the same parameter direction if (proxyParam.IsOut != candidateParam.IsOut) { skip = true; break; - } - - // Both need to have the same element type or byref type signature. + } + + // Both need to have the same element type or byref type signature. if (proxyParamType.IsByRef != candidateParamType.IsByRef) { skip = true; break; - } - - // If the parameters are by ref we unwrap them to have the actual type + } + + // If the parameters are by ref we unwrap them to have the actual type proxyParamType = proxyParamType.IsByRef ? proxyParamType.GetElementType() : proxyParamType; - candidateParamType = candidateParamType.IsByRef ? candidateParamType.GetElementType() : candidateParamType; - - // We can't compare generic parameters + candidateParamType = candidateParamType.IsByRef ? candidateParamType.GetElementType() : candidateParamType; + + // We can't compare generic parameters if (candidateParamType.IsGenericParameter) - continue; - - // If the proxy parameter type is a value type (no ducktyping neither a base class) both types must match + continue; + + // If the proxy parameter type is a value type (no ducktyping neither a base class) both types must match if (proxyParamType.IsValueType && !proxyParamType.IsEnum && proxyParamType != candidateParamType) { skip = true; break; - } - - // If the proxy parameter is a class and not is an abstract class (only interface and abstract class can be used as ducktype base type) + } + + // If the proxy parameter is a class and not is an abstract class (only interface and abstract class can be used as ducktype base type) if (proxyParamType.IsClass && !proxyParamType.IsAbstract && proxyParamType != typeof(object)) { if (!candidateParamType.IsAssignableFrom(proxyParamType)) - { - // Check if the parameter type contains generic types before skipping + { + // Check if the parameter type contains generic types before skipping if (!candidateParamType.IsGenericType || !proxyParamType.IsGenericType) { skip = true; break; - } - - // if the string representation of the generic parameter types is not the same we need to analyze the - // GenericTypeArguments array before skipping it + } + + // if the string representation of the generic parameter types is not the same we need to analyze the + // GenericTypeArguments array before skipping it if (candidateParamType.ToString() != proxyParamType.ToString()) { if (candidateParamType.GenericTypeArguments.Length != proxyParamType.GenericTypeArguments.Length) @@ -642,38 +645,38 @@ Type[] proxyMethodParametersTypes for (var paramIndex = 0; paramIndex < candidateParamType.GenericTypeArguments.Length; paramIndex++) { var candidateParamTypeGenericType = candidateParamType.GenericTypeArguments[paramIndex]; - var proxyParamTypeGenericType = proxyParamType.GenericTypeArguments[paramIndex]; - - // Both need to have the same element type or byref type signature. + var proxyParamTypeGenericType = proxyParamType.GenericTypeArguments[paramIndex]; + + // Both need to have the same element type or byref type signature. if (proxyParamTypeGenericType.IsByRef != candidateParamTypeGenericType.IsByRef) { skip = true; break; - } - - // If the parameters are by ref we unwrap them to have the actual type + } + + // If the parameters are by ref we unwrap them to have the actual type proxyParamTypeGenericType = proxyParamTypeGenericType.IsByRef ? proxyParamTypeGenericType.GetElementType() : proxyParamTypeGenericType; candidateParamTypeGenericType = candidateParamTypeGenericType.IsByRef ? candidateParamTypeGenericType.GetElementType() - : candidateParamTypeGenericType; - - // We can't compare generic parameters + : candidateParamTypeGenericType; + + // We can't compare generic parameters if (candidateParamTypeGenericType.IsGenericParameter) - continue; - - // If the proxy parameter type is a value type (no ducktyping neither a base class) both types must match - if (proxyParamTypeGenericType.IsValueType && !proxyParamTypeGenericType.IsEnum - && proxyParamTypeGenericType != candidateParamTypeGenericType) + continue; + + // If the proxy parameter type is a value type (no ducktyping neither a base class) both types must match + if (proxyParamTypeGenericType.IsValueType && !proxyParamTypeGenericType.IsEnum + && proxyParamTypeGenericType != candidateParamTypeGenericType) { skip = true; break; - } - - // If the proxy parameter is a class and not is an abstract class (only interface and abstract class can be used as ducktype base type) - if (proxyParamTypeGenericType.IsClass && !proxyParamTypeGenericType.IsAbstract - && proxyParamTypeGenericType != typeof(object)) + } + + // If the proxy parameter is a class and not is an abstract class (only interface and abstract class can be used as ducktype base type) + if (proxyParamTypeGenericType.IsClass && !proxyParamTypeGenericType.IsAbstract + && proxyParamTypeGenericType != typeof(object)) { if (!candidateParamTypeGenericType.IsAssignableFrom(proxyParamTypeGenericType)) { @@ -683,16 +686,17 @@ Type[] proxyMethodParametersTypes } } - if (skip) break; + if (skip) + break; } } } } if (skip) - continue; - - // The target method may have optional parameters with default values so we have to skip those + continue; + + // The target method may have optional parameters with default values so we have to skip those for (var i = proxyMethodParametersTypes.Length; i < candidateParameters.Length; i++) { if (!candidateParameters[i].IsOptional) @@ -715,8 +719,8 @@ Type[] proxyMethodParametersTypes } private static void WriteSafeTypeConversion(this LazyILGenerator il, Type actualType, Type expectedType) - { - // If both types are generics, we expect that the generic parameter are the same type (passthrough) + { + // If both types are generics, we expect that the generic parameter are the same type (passthrough) if (actualType.IsGenericParameter && expectedType.IsGenericParameter) return; diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Properties.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Properties.cs index ab92224a9..4bf074fe3 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Properties.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Properties.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Linq; @@ -15,7 +15,7 @@ using System.Reflection.Emit; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck Type /// @@ -34,13 +34,15 @@ public static partial class DuckType { proxyMemberReturnType = proxyProperty.PropertyType; proxyParameterTypes = GetPropertyGetParametersTypes(proxyTypeBuilder, proxyProperty, true).ToArray(); - if (proxyParameterTypes.Length != targetParametersTypes.Length) DuckTypePropertyArgumentsLengthException.Throw(proxyProperty); + if (proxyParameterTypes.Length != targetParametersTypes.Length) + DuckTypePropertyArgumentsLengthException.Throw(proxyProperty); } else if (proxyMember is FieldInfo proxyField) { proxyMemberReturnType = proxyField.FieldType; proxyParameterTypes = Type.EmptyTypes; - if (proxyParameterTypes.Length != targetParametersTypes.Length) DuckTypePropertyArgumentsLengthException.Throw(targetProperty); + if (proxyParameterTypes.Length != targetParametersTypes.Length) + DuckTypePropertyArgumentsLengthException.Throw(targetProperty); } var proxyMethod = proxyTypeBuilder.DefineMethod( @@ -52,78 +54,79 @@ public static partial class DuckType var il = new LazyILGenerator(proxyMethod.GetILGenerator()); var targetMethod = targetProperty.GetMethod; - var returnType = targetProperty.PropertyType; - - // Load the instance if needed + var returnType = targetProperty.PropertyType; + + // Load the instance if needed if (!targetMethod.IsStatic) { il.Emit(OpCodes.Ldarg_0); il.Emit(instanceField.FieldType.IsValueType ? OpCodes.Ldflda : OpCodes.Ldfld, instanceField); - } - - // Load the indexer keys to the stack + } + + // Load the indexer keys to the stack for (var pIndex = 0; pIndex < proxyParameterTypes.Length; pIndex++) { var proxyParamType = proxyParameterTypes[pIndex]; - var targetParamType = targetParametersTypes[pIndex]; - - // Check if the type can be converted of if we need to enable duck chaining + var targetParamType = targetParametersTypes[pIndex]; + + // Check if the type can be converted of if we need to enable duck chaining if (NeedsDuckChaining(targetParamType, proxyParamType)) - { - // Load the argument and cast it as Duck type + { + // Load the argument and cast it as Duck type il.WriteLoadArgument(pIndex, false); - il.Emit(OpCodes.Castclass, typeof(IDuckType)); - - // Call IDuckType.Instance property to get the actual value + il.Emit(OpCodes.Castclass, typeof(IDuckType)); + + // Call IDuckType.Instance property to get the actual value il.EmitCall(OpCodes.Callvirt, DuckTypeInstancePropertyInfo.GetMethod, null); targetParamType = typeof(object); } else - il.WriteLoadArgument(pIndex, false); - - // If the target parameter type is public or if it's by ref we have to actually use the original target type. + il.WriteLoadArgument(pIndex, false); + + // If the target parameter type is public or if it's by ref we have to actually use the original target type. targetParamType = UseDirectAccessTo(proxyTypeBuilder, targetParamType) || targetParamType.IsByRef ? targetParamType : typeof(object); il.WriteTypeConversion(proxyParamType, targetParamType); targetParametersTypes[pIndex] = targetParamType; - } - - // Call the getter method + } + + // Call the getter method if (UseDirectAccessTo(proxyTypeBuilder, targetType)) - { - // If the instance is public we can emit directly without any dynamic method - - // Method call + { + // If the instance is public we can emit directly without any dynamic method + + // Method call if (targetMethod.IsPublic) - { - // We can emit a normal call if we have a public instance with a public property method. + { + // We can emit a normal call if we have a public instance with a public property method. il.EmitCall(targetMethod.IsStatic || instanceField.FieldType.IsValueType ? OpCodes.Call : OpCodes.Callvirt, targetMethod, null); } else - { - // In case we have a public instance and a non public property method we can use [Calli] with the function pointer + { + // In case we have a public instance and a non public property method we can use [Calli] with the function pointer il.WriteMethodCalli(targetMethod); } } else - { - // If the instance is not public we need to create a Dynamic method to overpass the visibility checks - // we can't access non public types so we have to cast to object type (in the instance object and the return type). - + { + // If the instance is not public we need to create a Dynamic method to overpass the visibility checks + // we can't access non public types so we have to cast to object type (in the instance object and the return type). + var dynMethodName = $"_getNonPublicProperty_{targetProperty.DeclaringType.Name}_{targetProperty.Name}"; - returnType = UseDirectAccessTo(proxyTypeBuilder, targetProperty.PropertyType) ? targetProperty.PropertyType : typeof(object); - - // We create the dynamic method + returnType = UseDirectAccessTo(proxyTypeBuilder, targetProperty.PropertyType) ? targetProperty.PropertyType : typeof(object); + + // We create the dynamic method var targetParameters = GetPropertyGetParametersTypes(proxyTypeBuilder, targetProperty, false, !targetMethod.IsStatic).ToArray(); var dynParameters = targetMethod.IsStatic ? targetParametersTypes : (new[] { typeof(object) }).Concat(targetParametersTypes).ToArray(); - var dynMethod = new DynamicMethod(dynMethodName, returnType, dynParameters, proxyTypeBuilder.Module, true); - - // Emit the dynamic method body + var dynMethod = new DynamicMethod(dynMethodName, returnType, dynParameters, proxyTypeBuilder.Module, true); + + // Emit the dynamic method body var dynIL = new LazyILGenerator(dynMethod.GetILGenerator()); - if (!targetMethod.IsStatic) dynIL.LoadInstanceArgument(typeof(object), targetProperty.DeclaringType); + if (!targetMethod.IsStatic) + dynIL.LoadInstanceArgument(typeof(object), targetProperty.DeclaringType); for (var idx = targetMethod.IsStatic ? 0 : 1; idx < dynParameters.Length; idx++) { @@ -134,19 +137,20 @@ public static partial class DuckType dynIL.EmitCall(targetMethod.IsStatic || instanceField.FieldType.IsValueType ? OpCodes.Call : OpCodes.Callvirt, targetMethod, null); dynIL.WriteTypeConversion(targetProperty.PropertyType, returnType); dynIL.Emit(OpCodes.Ret); - dynIL.Flush(); - - // Emit the call to the dynamic method + dynIL.Flush(); + + // Emit the call to the dynamic method il.WriteDynamicMethodCall(dynMethod, proxyTypeBuilder); - } - - // Handle the return value - // Check if the type can be converted or if we need to enable duck chaining + } + + // Handle the return value + // Check if the type can be converted or if we need to enable duck chaining if (NeedsDuckChaining(targetProperty.PropertyType, proxyMemberReturnType)) { - if (UseDirectAccessTo(proxyTypeBuilder, targetProperty.PropertyType) && targetProperty.PropertyType.IsValueType) il.Emit(OpCodes.Box, targetProperty.PropertyType); - - // We call DuckType.CreateCache<>.Create() + if (UseDirectAccessTo(proxyTypeBuilder, targetProperty.PropertyType) && targetProperty.PropertyType.IsValueType) + il.Emit(OpCodes.Box, targetProperty.PropertyType); + + // We call DuckType.CreateCache<>.Create() var getProxyMethodInfo = typeof(CreateCache<>) .MakeGenericType(proxyMemberReturnType) .GetMethod("Create"); @@ -154,8 +158,8 @@ public static partial class DuckType il.Emit(OpCodes.Call, getProxyMethodInfo); } else if (returnType != proxyMemberReturnType) - { - // If the type is not the expected type we try a conversion. + { + // If the type is not the expected type we try a conversion. il.WriteTypeConversion(returnType, proxyMemberReturnType); } @@ -177,13 +181,15 @@ public static partial class DuckType { proxyMemberName = proxyProperty.Name; proxyParameterTypes = GetPropertySetParametersTypes(proxyTypeBuilder, proxyProperty, true).ToArray(); - if (proxyParameterTypes.Length != targetParametersTypes.Length) DuckTypePropertyArgumentsLengthException.Throw(proxyProperty); + if (proxyParameterTypes.Length != targetParametersTypes.Length) + DuckTypePropertyArgumentsLengthException.Throw(proxyProperty); } else if (proxyMember is FieldInfo proxyField) { proxyMemberName = proxyField.Name; proxyParameterTypes = new Type[] { proxyField.FieldType }; - if (proxyParameterTypes.Length != targetParametersTypes.Length) DuckTypePropertyArgumentsLengthException.Throw(targetProperty); + if (proxyParameterTypes.Length != targetParametersTypes.Length) + DuckTypePropertyArgumentsLengthException.Throw(targetProperty); } var proxyMethod = proxyTypeBuilder.DefineMethod( @@ -194,77 +200,78 @@ public static partial class DuckType proxyParameterTypes); var il = new LazyILGenerator(proxyMethod.GetILGenerator()); - var targetMethod = targetProperty.SetMethod; - - // Load the instance if needed + var targetMethod = targetProperty.SetMethod; + + // Load the instance if needed if (!targetMethod.IsStatic) { il.Emit(OpCodes.Ldarg_0); il.Emit(instanceField.FieldType.IsValueType ? OpCodes.Ldflda : OpCodes.Ldfld, instanceField); - } - - // Load the indexer keys and set value to the stack + } + + // Load the indexer keys and set value to the stack for (var pIndex = 0; pIndex < proxyParameterTypes.Length; pIndex++) { var proxyParamType = proxyParameterTypes[pIndex]; - var targetParamType = targetParametersTypes[pIndex]; - - // Check if the type can be converted of if we need to enable duck chaining + var targetParamType = targetParametersTypes[pIndex]; + + // Check if the type can be converted of if we need to enable duck chaining if (NeedsDuckChaining(targetParamType, proxyParamType)) - { - // Load the argument and cast it as Duck type + { + // Load the argument and cast it as Duck type il.WriteLoadArgument(pIndex, false); - il.Emit(OpCodes.Castclass, typeof(IDuckType)); - - // Call IDuckType.Instance property to get the actual value + il.Emit(OpCodes.Castclass, typeof(IDuckType)); + + // Call IDuckType.Instance property to get the actual value il.EmitCall(OpCodes.Callvirt, DuckTypeInstancePropertyInfo.GetMethod, null); targetParamType = typeof(object); } else - il.WriteLoadArgument(pIndex, false); - - // If the target parameter type is public or if it's by ref we have to actually use the original target type. + il.WriteLoadArgument(pIndex, false); + + // If the target parameter type is public or if it's by ref we have to actually use the original target type. targetParamType = UseDirectAccessTo(proxyTypeBuilder, targetParamType) || targetParamType.IsByRef ? targetParamType : typeof(object); il.WriteTypeConversion(proxyParamType, targetParamType); targetParametersTypes[pIndex] = targetParamType; - } - - // Call the setter method + } + + // Call the setter method if (UseDirectAccessTo(proxyTypeBuilder, targetType)) - { - // If the instance is public we can emit directly without any dynamic method - + { + // If the instance is public we can emit directly without any dynamic method + if (targetMethod.IsPublic) - { - // We can emit a normal call if we have a public instance with a public property method. + { + // We can emit a normal call if we have a public instance with a public property method. il.EmitCall(targetMethod.IsStatic ? OpCodes.Call : OpCodes.Callvirt, targetMethod, null); } else - { - // In case we have a public instance and a non public property method we can use [Calli] with the function pointer + { + // In case we have a public instance and a non public property method we can use [Calli] with the function pointer il.WriteMethodCalli(targetMethod); } } else - { - // If the instance is not public we need to create a Dynamic method to overpass the visibility checks - // we can't access non public types so we have to cast to object type (in the instance object and the return type). - - var dynMethodName = $"_setNonPublicProperty+{targetProperty.DeclaringType.Name}.{targetProperty.Name}"; - - // We create the dynamic method + { + // If the instance is not public we need to create a Dynamic method to overpass the visibility checks + // we can't access non public types so we have to cast to object type (in the instance object and the return type). + + var dynMethodName = $"_setNonPublicProperty+{targetProperty.DeclaringType.Name}.{targetProperty.Name}"; + + // We create the dynamic method var targetParameters = GetPropertySetParametersTypes(proxyTypeBuilder, targetProperty, false, !targetMethod.IsStatic).ToArray(); var dynParameters = targetMethod.IsStatic ? targetParametersTypes : (new[] { typeof(object) }).Concat(targetParametersTypes).ToArray(); - var dynMethod = new DynamicMethod(dynMethodName, typeof(void), dynParameters, proxyTypeBuilder.Module, true); - - // Emit the dynamic method body + var dynMethod = new DynamicMethod(dynMethodName, typeof(void), dynParameters, proxyTypeBuilder.Module, true); + + // Emit the dynamic method body var dynIL = new LazyILGenerator(dynMethod.GetILGenerator()); - if (!targetMethod.IsStatic) dynIL.LoadInstanceArgument(typeof(object), targetProperty.DeclaringType); + if (!targetMethod.IsStatic) + dynIL.LoadInstanceArgument(typeof(object), targetProperty.DeclaringType); for (var idx = targetMethod.IsStatic ? 0 : 1; idx < dynParameters.Length; idx++) { @@ -274,9 +281,9 @@ public static partial class DuckType dynIL.EmitCall(targetMethod.IsStatic ? OpCodes.Call : OpCodes.Callvirt, targetMethod, null); dynIL.Emit(OpCodes.Ret); - dynIL.Flush(); - - // Create and load delegate for the DynamicMethod + dynIL.Flush(); + + // Create and load delegate for the DynamicMethod il.WriteDynamicMethodCall(dynMethod, proxyTypeBuilder); } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Statics.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Statics.cs index 7b09bcf9a..107ef2549 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Statics.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Statics.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -17,17 +17,17 @@ using System.Runtime.CompilerServices; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck Type /// public static partial class DuckType - { + { /// /// Gets the Type.GetTypeFromHandle method info /// - public static readonly MethodInfo GetTypeFromHandleMethodInfo = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)); - + public static readonly MethodInfo GetTypeFromHandleMethodInfo = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)); + /// /// Gets the Enum.ToObject method info /// @@ -67,8 +67,8 @@ public static partial class DuckType internal static long AssemblyCount => _assemblyCount; - internal static long TypeCount => _typeCount; - + internal static long TypeCount => _typeCount; + /// /// Gets the ModuleBuilder instance from a target type. (.NET Framework / Non AssemblyLoadContext version) /// @@ -80,17 +80,18 @@ private static ModuleBuilder GetModuleBuilder(Type targetType, bool isVisible) var targetAssembly = targetType.Assembly ?? typeof(DuckType).Assembly; if (!isVisible) - { - // If the target type is not visible then we create a new module builder. - // This is the only way to IgnoresAccessChecksToAttribute to work. - // We can't reuse the module builder if the attributes collection changes. + { + // If the target type is not visible then we create a new module builder. + // This is the only way to IgnoresAccessChecksToAttribute to work. + // We can't reuse the module builder if the attributes collection changes. return CreateModuleBuilder($"DuckTypeNotVisibleAssembly.{targetType.Name}", targetAssembly); } if (targetType.IsGenericType) { foreach (var type in targetType.GetGenericArguments()) - if (type.Assembly != targetAssembly) return CreateModuleBuilder($"DuckTypeGenericTypeAssembly.{targetType.Name}", targetAssembly); + if (type.Assembly != targetAssembly) + return CreateModuleBuilder($"DuckTypeGenericTypeAssembly.{targetType.Name}", targetAssembly); } if (!ActiveBuilders.TryGetValue(targetAssembly, out var moduleBuilder)) @@ -108,8 +109,8 @@ static ModuleBuilder CreateModuleBuilder(string name, Assembly targetAssembly) var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); return assemblyBuilder.DefineDynamicModule("MainModule"); } - } - + } + /// /// DynamicMethods delegates cache /// @@ -117,14 +118,14 @@ static ModuleBuilder CreateModuleBuilder(string name, Assembly targetAssembly) public static class DelegateCache where TProxyDelegate : Delegate { - private static TProxyDelegate _delegate; - + private static TProxyDelegate _delegate; + /// /// Get cached delegate from the DynamicMethod /// /// TProxyDelegate instance - public static TProxyDelegate GetDelegate() => _delegate; - + public static TProxyDelegate GetDelegate() => _delegate; + /// /// Create delegate from a DynamicMethod index /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Utilities.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Utilities.cs index 60399bab6..6a8802143 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Utilities.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.Utilities.cs @@ -1,25 +1,25 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck Type /// public static partial class DuckType - { + { /// /// Checks and ensures the arguments for the Create methods /// @@ -28,18 +28,20 @@ public static partial class DuckType /// If the duck type or the instance value is null private static void EnsureArguments(Type proxyType, object instance) { - if (proxyType is null) DuckTypeProxyTypeDefinitionIsNull.Throw(); - - if (instance is null) DuckTypeTargetObjectInstanceIsNull.Throw(); + if (proxyType is null) + DuckTypeProxyTypeDefinitionIsNull.Throw(); + if (instance is null) + DuckTypeTargetObjectInstanceIsNull.Throw(); + #if NET45 if (!proxyType.IsPublic && !proxyType.IsNestedPublic) { DuckTypeTypeIsNotPublicException.Throw(proxyType, nameof(proxyType)); } #endif - } - + } + /// /// Ensures the visibility access to the type /// @@ -61,9 +63,9 @@ private static void EnsureTypeVisibility(ModuleBuilder builder, Type type) while (type.IsNested) { if (!type.IsNestedPublic) - EnsureAssemblyNameVisibility(builder, type.Assembly.GetName().Name); - - // this should be null for non-nested types. + EnsureAssemblyNameVisibility(builder, type.Assembly.GetName().Name); + + // this should be null for non-nested types. type = type.DeclaringType; } @@ -86,21 +88,21 @@ static void EnsureAssemblyNameVisibility(ModuleBuilder builder, string assemblyN } } - private static bool NeedsDuckChaining(Type targetType, Type proxyType) => - // The condition to apply duck chaining is: - // 1. Is a struct with the DuckCopy attribute - // 2. Both types must be differents. - // 3. The proxy type (duck chaining proxy definition type) can't be a struct - // 4. The proxy type can't be a generic parameter (should be a well known type) - // 5. Can't be a base type or an iterface implemented by the targetType type. - // 6. The proxy type can't be a CLR type + private static bool NeedsDuckChaining(Type targetType, Type proxyType) => + // The condition to apply duck chaining is: + // 1. Is a struct with the DuckCopy attribute + // 2. Both types must be differents. + // 3. The proxy type (duck chaining proxy definition type) can't be a struct + // 4. The proxy type can't be a generic parameter (should be a well known type) + // 5. Can't be a base type or an iterface implemented by the targetType type. + // 6. The proxy type can't be a CLR type proxyType.GetCustomAttribute() != null || (proxyType != targetType && !proxyType.IsValueType && !proxyType.IsGenericParameter && !proxyType.IsAssignableFrom(targetType) && - proxyType.Module != typeof(string).Module); - + proxyType.Module != typeof(string).Module); + /// /// Gets if the direct access method should be used or the inderect method (dynamic method) /// @@ -114,16 +116,16 @@ private static bool UseDirectAccessTo(ModuleBuilder builder, Type targetType) EnsureTypeVisibility(builder, targetType); return true; - } - + } + /// /// Gets if the direct access method should be used or the inderect method (dynamic method) /// /// Type builder /// Target type /// true for direct method; otherwise, false. - private static bool UseDirectAccessTo(TypeBuilder builder, Type targetType) => UseDirectAccessTo((ModuleBuilder)builder?.Module, targetType); - + private static bool UseDirectAccessTo(TypeBuilder builder, Type targetType) => UseDirectAccessTo((ModuleBuilder)builder?.Module, targetType); + /// /// Gets if the direct access method should be used or the inderect method (dynamic method) /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.cs index 1a83f900d..2b01740bc 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Linq; @@ -17,20 +17,20 @@ using System.Runtime.ExceptionServices; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Create struct proxy instance delegate /// /// Type of struct /// Object instance /// Proxy instance - public delegate T CreateProxyInstance(object instance); - + public delegate T CreateProxyInstance(object instance); + /// /// Duck Type /// public static partial class DuckType - { + { /// /// Create duck type proxy using a base type /// @@ -38,8 +38,8 @@ public static partial class DuckType /// Duck type /// Duck type proxy [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static T Create(object instance) => CreateCache.Create(instance); - + public static T Create(object instance) => CreateCache.Create(instance); + /// /// Create duck type proxy using a base type /// @@ -48,17 +48,17 @@ public static partial class DuckType /// Duck Type proxy [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IDuckType Create(Type proxyType, object instance) - { - // Validate arguments - EnsureArguments(proxyType, instance); - - // Create Type - var result = GetOrCreateProxyType(proxyType, instance.GetType()); - - // Create instance + { + // Validate arguments + EnsureArguments(proxyType, instance); + + // Create Type + var result = GetOrCreateProxyType(proxyType, instance.GetType()); + + // Create instance return result.CreateInstance(instance); - } - + } + /// /// Gets if a proxy can be created /// @@ -66,8 +66,8 @@ public static IDuckType Create(Type proxyType, object instance) /// Duck type /// true if the proxy can be created; otherwise, false [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool CanCreate(object instance) => CreateCache.CanCreate(instance); - + public static bool CanCreate(object instance) => CreateCache.CanCreate(instance); + /// /// Gets if a proxy can be created /// @@ -76,17 +76,17 @@ public static IDuckType Create(Type proxyType, object instance) /// true if the proxy can be created; otherwise, false [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool CanCreate(Type proxyType, object instance) - { - // Validate arguments - EnsureArguments(proxyType, instance); - - // Create Type - var result = GetOrCreateProxyType(proxyType, instance.GetType()); - - // Create instance + { + // Validate arguments + EnsureArguments(proxyType, instance); + + // Create Type + var result = GetOrCreateProxyType(proxyType, instance.GetType()); + + // Create instance return result.CanCreate(); - } - + } + /// /// Gets or create a new proxy type for ducktyping /// @@ -104,15 +104,15 @@ private static CreateTypeResult CreateProxyType(Type proxyDefinitionType, Type t lock (_locker) { try - { - // Define parent type, interface types + { + // Define parent type, interface types Type parentType; TypeAttributes typeAttributes; Type[] interfaceTypes; if (proxyDefinitionType.IsInterface || proxyDefinitionType.IsValueType) - { - // If the proxy type definition is an interface we create an struct proxy - // If the proxy type definition is an struct then we use that struct to copy the values from the target type + { + // If the proxy type definition is an interface we create an struct proxy + // If the proxy type definition is an struct then we use that struct to copy the values from the target type parentType = typeof(ValueType); typeAttributes = TypeAttributes.Public | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.SequentialLayout | TypeAttributes.Sealed | TypeAttributes.Serializable; @@ -122,48 +122,48 @@ private static CreateTypeResult CreateProxyType(Type proxyDefinitionType, Type t interfaceTypes = new[] { typeof(IDuckType) }; } else - { - // If the proxy type definition is a class then we create a class proxy + { + // If the proxy type definition is a class then we create a class proxy parentType = proxyDefinitionType; typeAttributes = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout | TypeAttributes.Sealed; interfaceTypes = new[] { typeof(IDuckType) }; - } - - // Gets the module builder + } + + // Gets the module builder var moduleBuilder = GetModuleBuilder(targetType, - (targetType.IsPublic || targetType.IsNestedPublic) && (proxyDefinitionType.IsPublic || proxyDefinitionType.IsNestedPublic)); - - // Ensure visibility + (targetType.IsPublic || targetType.IsNestedPublic) && (proxyDefinitionType.IsPublic || proxyDefinitionType.IsNestedPublic)); + + // Ensure visibility EnsureTypeVisibility(moduleBuilder, targetType); EnsureTypeVisibility(moduleBuilder, proxyDefinitionType); var assembly = string.Empty; if (targetType.Assembly != null) - { - // Include target assembly name and public token. + { + // Include target assembly name and public token. var asmName = targetType.Assembly.GetName(); assembly = asmName.Name; var pbToken = asmName.GetPublicKeyToken(); assembly += "__" + BitConverter.ToString(pbToken).Replace("-", string.Empty); assembly = assembly.Replace(".", "_").Replace("+", "__"); - } - - // Create a valid type name that can be used as a member of a class. (BenchmarkDotNet fails if is an invalid name) + } + + // Create a valid type name that can be used as a member of a class. (BenchmarkDotNet fails if is an invalid name) var proxyTypeName = - $"{assembly}.{targetType.FullName.Replace(".", "_").Replace("+", "__")}.{proxyDefinitionType.FullName.Replace(".", "_").Replace("+", "__")}_{++_typeCount}"; - - // Create Type + $"{assembly}.{targetType.FullName.Replace(".", "_").Replace("+", "__")}.{proxyDefinitionType.FullName.Replace(".", "_").Replace("+", "__")}_{++_typeCount}"; + + // Create Type var proxyTypeBuilder = moduleBuilder.DefineType( proxyTypeName, typeAttributes, parentType, - interfaceTypes); - - // Create IDuckType and IDuckTypeSetter implementations - var instanceField = CreateIDuckTypeImplementation(proxyTypeBuilder, targetType); - - // Define .ctor to store the instance field + interfaceTypes); + + // Create IDuckType and IDuckTypeSetter implementations + var instanceField = CreateIDuckTypeImplementation(proxyTypeBuilder, targetType); + + // Define .ctor to store the instance field var ctorBuilder = proxyTypeBuilder.DefineConstructor( MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, @@ -175,24 +175,24 @@ private static CreateTypeResult CreateProxyType(Type proxyDefinitionType, Type t ctorIL.Emit(OpCodes.Ret); if (proxyDefinitionType.IsValueType) - { - // Create Fields and Properties from the struct information - CreatePropertiesFromStruct(proxyTypeBuilder, proxyDefinitionType, targetType, instanceField); - - // Create Type + { + // Create Fields and Properties from the struct information + CreatePropertiesFromStruct(proxyTypeBuilder, proxyDefinitionType, targetType, instanceField); + + // Create Type var proxyType = proxyTypeBuilder.CreateTypeInfo().AsType(); return new CreateTypeResult(proxyDefinitionType, proxyType, targetType, CreateStructCopyMethod(moduleBuilder, proxyDefinitionType, proxyType, targetType), null); } else - { - // Create Fields and Properties - CreateProperties(proxyTypeBuilder, proxyDefinitionType, targetType, instanceField); - - // Create Methods - CreateMethods(proxyTypeBuilder, proxyDefinitionType, targetType, instanceField); - - // Create Type + { + // Create Fields and Properties + CreateProperties(proxyTypeBuilder, proxyDefinitionType, targetType, instanceField); + + // Create Methods + CreateMethods(proxyTypeBuilder, proxyDefinitionType, targetType, instanceField); + + // Create Type var proxyType = proxyTypeBuilder.CreateTypeInfo().AsType(); return new CreateTypeResult(proxyDefinitionType, proxyType, targetType, GetCreateProxyInstanceDelegate(moduleBuilder, proxyDefinitionType, proxyType, targetType), null); @@ -208,7 +208,8 @@ private static CreateTypeResult CreateProxyType(Type proxyDefinitionType, Type t private static FieldInfo CreateIDuckTypeImplementation(TypeBuilder proxyTypeBuilder, Type targetType) { var instanceType = targetType; - if (!UseDirectAccessTo(proxyTypeBuilder, targetType)) instanceType = typeof(object); + if (!UseDirectAccessTo(proxyTypeBuilder, targetType)) + instanceType = typeof(object); var instanceField = proxyTypeBuilder.DefineField("_currentInstance", instanceType, FieldAttributes.Private | FieldAttributes.InitOnly); @@ -221,7 +222,8 @@ private static FieldInfo CreateIDuckTypeImplementation(TypeBuilder proxyTypeBuil var il = getPropInstance.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, instanceField); - if (instanceType.IsValueType) il.Emit(OpCodes.Box, instanceType); + if (instanceType.IsValueType) + il.Emit(OpCodes.Box, instanceType); il.Emit(OpCodes.Ret); propInstance.SetGetMethod(getPropInstance); @@ -249,7 +251,8 @@ private static List GetProperties(Type proxyDefinitionType) var implementedInterfaces = proxyDefinitionType.GetInterfaces(); foreach (var imInterface in implementedInterfaces) { - if (imInterface == typeof(IDuckType)) continue; + if (imInterface == typeof(IDuckType)) + continue; var newProps = imInterface.GetProperties().Where(p => selectedProperties.All(i => i.Name != p.Name)); selectedProperties.AddRange(newProps); @@ -263,25 +266,28 @@ static IEnumerable GetBaseProperties(Type baseType) { if (prop.CanRead && (prop.GetMethod.IsAbstract || prop.GetMethod.IsVirtual)) yield return prop; - else if (prop.CanWrite && (prop.SetMethod.IsAbstract || prop.SetMethod.IsVirtual)) yield return prop; + else if (prop.CanWrite && (prop.SetMethod.IsAbstract || prop.SetMethod.IsVirtual)) + yield return prop; } } } private static void CreateProperties(TypeBuilder proxyTypeBuilder, Type proxyDefinitionType, Type targetType, FieldInfo instanceField) - { - // Gets all properties to be implemented + { + // Gets all properties to be implemented var proxyTypeProperties = GetProperties(proxyDefinitionType); foreach (var proxyProperty in proxyTypeProperties) - { - // Ignore the properties marked with `DuckIgnore` attribute - if (proxyProperty.GetCustomAttribute(true) is not null) continue; - - PropertyBuilder propertyBuilder = null; + { + // Ignore the properties marked with `DuckIgnore` attribute + if (proxyProperty.GetCustomAttribute(true) is not null) + continue; - // If the property is abstract or interface we make sure that we have the property defined in the new class - if ((proxyProperty.CanRead && proxyProperty.GetMethod.IsAbstract) || (proxyProperty.CanWrite && proxyProperty.SetMethod.IsAbstract)) propertyBuilder = proxyTypeBuilder.DefineProperty(proxyProperty.Name, PropertyAttributes.None, proxyProperty.PropertyType, null); + PropertyBuilder propertyBuilder = null; + + // If the property is abstract or interface we make sure that we have the property defined in the new class + if ((proxyProperty.CanRead && proxyProperty.GetMethod.IsAbstract) || (proxyProperty.CanWrite && proxyProperty.SetMethod.IsAbstract)) + propertyBuilder = proxyTypeBuilder.DefineProperty(proxyProperty.Name, PropertyAttributes.None, proxyProperty.PropertyType, null); var duckAttribute = proxyProperty.GetCustomAttribute(true) ?? new DuckAttribute(); duckAttribute.Name ??= proxyProperty.Name; @@ -295,34 +301,38 @@ private static void CreateProperties(TypeBuilder proxyTypeBuilder, Type proxyDef targetProperty = targetType.GetProperty(duckAttribute.Name, duckAttribute.BindingFlags); } catch - { - // This will run only when multiple indexers are defined in a class, that way we can end up with multiple properties with the same name. - // In this case we make sure we select the indexer we want + { + // This will run only when multiple indexers are defined in a class, that way we can end up with multiple properties with the same name. + // In this case we make sure we select the indexer we want targetProperty = targetType.GetProperty(duckAttribute.Name, proxyProperty.PropertyType, proxyProperty.GetIndexParameters().Select(i => i.ParameterType).ToArray()); } - if (targetProperty is null) break; + if (targetProperty is null) + break; propertyBuilder ??= proxyTypeBuilder.DefineProperty(proxyProperty.Name, PropertyAttributes.None, proxyProperty.PropertyType, null); if (proxyProperty.CanRead) - { - // Check if the target property can be read - if (!targetProperty.CanRead) DuckTypePropertyCantBeReadException.Throw(targetProperty); + { + // Check if the target property can be read + if (!targetProperty.CanRead) + DuckTypePropertyCantBeReadException.Throw(targetProperty); propertyBuilder.SetGetMethod(GetPropertyGetMethod(proxyTypeBuilder, targetType, proxyProperty, targetProperty, instanceField)); } if (proxyProperty.CanWrite) - { - // Check if the target property can be written - if (!targetProperty.CanWrite) DuckTypePropertyCantBeWrittenException.Throw(targetProperty); - - // Check if the target property declaring type is an struct (structs modification is not supported) - if (targetProperty.DeclaringType.IsValueType) DuckTypeStructMembersCannotBeChangedException.Throw(targetProperty.DeclaringType); + { + // Check if the target property can be written + if (!targetProperty.CanWrite) + DuckTypePropertyCantBeWrittenException.Throw(targetProperty); + + // Check if the target property declaring type is an struct (structs modification is not supported) + if (targetProperty.DeclaringType.IsValueType) + DuckTypeStructMembersCannotBeChangedException.Throw(targetProperty.DeclaringType); propertyBuilder.SetSetMethod(GetPropertySetMethod(proxyTypeBuilder, targetType, proxyProperty, targetProperty, instanceField)); @@ -332,20 +342,24 @@ private static void CreateProperties(TypeBuilder proxyTypeBuilder, Type proxyDef case DuckKind.Field: var targetField = targetType.GetField(duckAttribute.Name, duckAttribute.BindingFlags); - if (targetField is null) break; + if (targetField is null) + break; propertyBuilder ??= proxyTypeBuilder.DefineProperty(proxyProperty.Name, PropertyAttributes.None, proxyProperty.PropertyType, null); - if (proxyProperty.CanRead) propertyBuilder.SetGetMethod(GetFieldGetMethod(proxyTypeBuilder, targetType, proxyProperty, targetField, instanceField)); + if (proxyProperty.CanRead) + propertyBuilder.SetGetMethod(GetFieldGetMethod(proxyTypeBuilder, targetType, proxyProperty, targetField, instanceField)); if (proxyProperty.CanWrite) - { - // Check if the target field is marked as InitOnly (readonly) and throw an exception in that case - if ((targetField.Attributes & FieldAttributes.InitOnly) != 0) DuckTypeFieldIsReadonlyException.Throw(targetField); - - // Check if the target field declaring type is an struct (structs modification is not supported) - if (targetField.DeclaringType.IsValueType) DuckTypeStructMembersCannotBeChangedException.Throw(targetField.DeclaringType); + { + // Check if the target field is marked as InitOnly (readonly) and throw an exception in that case + if ((targetField.Attributes & FieldAttributes.InitOnly) != 0) + DuckTypeFieldIsReadonlyException.Throw(targetField); + + // Check if the target field declaring type is an struct (structs modification is not supported) + if (targetField.DeclaringType.IsValueType) + DuckTypeStructMembersCannotBeChangedException.Throw(targetField.DeclaringType); propertyBuilder.SetSetMethod(GetFieldSetMethod(proxyTypeBuilder, targetType, proxyProperty, targetField, instanceField)); } @@ -353,26 +367,31 @@ private static void CreateProperties(TypeBuilder proxyTypeBuilder, Type proxyDef break; } - if (propertyBuilder is null) continue; + if (propertyBuilder is null) + continue; - if (proxyProperty.CanRead && propertyBuilder.GetMethod is null) DuckTypePropertyOrFieldNotFoundException.Throw(proxyProperty.Name, duckAttribute.Name); + if (proxyProperty.CanRead && propertyBuilder.GetMethod is null) + DuckTypePropertyOrFieldNotFoundException.Throw(proxyProperty.Name, duckAttribute.Name); - if (proxyProperty.CanWrite && propertyBuilder.SetMethod is null) DuckTypePropertyOrFieldNotFoundException.Throw(proxyProperty.Name, duckAttribute.Name); + if (proxyProperty.CanWrite && propertyBuilder.SetMethod is null) + DuckTypePropertyOrFieldNotFoundException.Throw(proxyProperty.Name, duckAttribute.Name); } } private static void CreatePropertiesFromStruct(TypeBuilder proxyTypeBuilder, Type proxyDefinitionType, Type targetType, FieldInfo instanceField ) - { - // Gets all fields to be copied + { + // Gets all fields to be copied foreach (var proxyFieldInfo in proxyDefinitionType.GetFields()) - { - // Skip readonly fields - if ((proxyFieldInfo.Attributes & FieldAttributes.InitOnly) != 0) continue; - - // Ignore the fields marked with `DuckIgnore` attribute - if (proxyFieldInfo.GetCustomAttribute(true) is not null) continue; + { + // Skip readonly fields + if ((proxyFieldInfo.Attributes & FieldAttributes.InitOnly) != 0) + continue; + + // Ignore the fields marked with `DuckIgnore` attribute + if (proxyFieldInfo.GetCustomAttribute(true) is not null) + continue; PropertyBuilder propertyBuilder = null; @@ -383,10 +402,12 @@ FieldInfo instanceField { case DuckKind.Property: var targetProperty = targetType.GetProperty(duckAttribute.Name, duckAttribute.BindingFlags); - if (targetProperty is null) break; - - // Check if the target property can be read - if (!targetProperty.CanRead) DuckTypePropertyCantBeReadException.Throw(targetProperty); + if (targetProperty is null) + break; + + // Check if the target property can be read + if (!targetProperty.CanRead) + DuckTypePropertyCantBeReadException.Throw(targetProperty); propertyBuilder = proxyTypeBuilder.DefineProperty(proxyFieldInfo.Name, PropertyAttributes.None, proxyFieldInfo.FieldType, null); @@ -396,7 +417,8 @@ FieldInfo instanceField case DuckKind.Field: var targetField = targetType.GetField(duckAttribute.Name, duckAttribute.BindingFlags); - if (targetField is null) break; + if (targetField is null) + break; propertyBuilder = proxyTypeBuilder.DefineProperty(proxyFieldInfo.Name, PropertyAttributes.None, proxyFieldInfo.FieldType, null); @@ -404,7 +426,8 @@ FieldInfo instanceField break; } - if (propertyBuilder is null) DuckTypePropertyOrFieldNotFoundException.Throw(proxyFieldInfo.Name, duckAttribute.Name); + if (propertyBuilder is null) + DuckTypePropertyOrFieldNotFoundException.Throw(proxyFieldInfo.Name, duckAttribute.Name); } } @@ -430,7 +453,8 @@ private static Delegate GetCreateProxyInstanceDelegate(ModuleBuilder moduleBuild il.Emit(OpCodes.Newobj, ctor); - if (proxyType.IsValueType) il.Emit(OpCodes.Box, proxyType); + if (proxyType.IsValueType) + il.Emit(OpCodes.Box, proxyType); il.Emit(OpCodes.Ret); var delegateType = typeof(CreateProxyInstance<>).MakeGenericType(proxyDefinitionType); @@ -447,13 +471,13 @@ private static Delegate CreateStructCopyMethod(ModuleBuilder moduleBuilder, Type new[] { typeof(object) }, typeof(Elastic.Apm.Profiler.Managed.DuckTyping.DuckType).Module, true); - var il = createStructMethod.GetILGenerator(); - - // First we declare the locals + var il = createStructMethod.GetILGenerator(); + + // First we declare the locals var proxyLocal = il.DeclareLocal(proxyType); - var structLocal = il.DeclareLocal(proxyDefinitionType); - - // We create an instance of the proxy type + var structLocal = il.DeclareLocal(proxyDefinitionType); + + // We create an instance of the proxy type il.Emit(OpCodes.Ldloca_S, proxyLocal.LocalIndex); il.Emit(OpCodes.Ldarg_0); if (UseDirectAccessTo(moduleBuilder, targetType)) @@ -464,46 +488,48 @@ private static Delegate CreateStructCopyMethod(ModuleBuilder moduleBuilder, Type il.Emit(OpCodes.Castclass, targetType); } - il.Emit(OpCodes.Call, ctor); - - // Create the destination structure + il.Emit(OpCodes.Call, ctor); + + // Create the destination structure il.Emit(OpCodes.Ldloca_S, structLocal.LocalIndex); - il.Emit(OpCodes.Initobj, proxyDefinitionType); - - // Start copy properties from the proxy to the structure + il.Emit(OpCodes.Initobj, proxyDefinitionType); + + // Start copy properties from the proxy to the structure foreach (var finfo in proxyDefinitionType.GetFields()) - { - // Skip readonly fields - if ((finfo.Attributes & FieldAttributes.InitOnly) != 0) continue; - - // Ignore the fields marked with `DuckIgnore` attribute - if (finfo.GetCustomAttribute(true) is not null) continue; + { + // Skip readonly fields + if ((finfo.Attributes & FieldAttributes.InitOnly) != 0) + continue; + + // Ignore the fields marked with `DuckIgnore` attribute + if (finfo.GetCustomAttribute(true) is not null) + continue; var prop = proxyType.GetProperty(finfo.Name); il.Emit(OpCodes.Ldloca_S, structLocal.LocalIndex); il.Emit(OpCodes.Ldloca_S, proxyLocal.LocalIndex); il.EmitCall(OpCodes.Call, prop.GetMethod, null); il.Emit(OpCodes.Stfld, finfo); - } - - // Return + } + + // Return il.WriteLoadLocal(structLocal.LocalIndex); il.Emit(OpCodes.Ret); var delegateType = typeof(CreateProxyInstance<>).MakeGenericType(proxyDefinitionType); return createStructMethod.CreateDelegate(delegateType); - } - + } + /// /// Struct to store the result of creating a proxy type /// public readonly struct CreateTypeResult - { + { /// /// Gets if the proxy type creation was successful /// - public readonly bool Success; - + public readonly bool Success; + /// /// Target type /// @@ -511,8 +537,8 @@ private static Delegate CreateStructCopyMethod(ModuleBuilder moduleBuilder, Type private readonly Type _proxyType; private readonly ExceptionDispatchInfo _exceptionInfo; - private readonly Delegate _activator; - + private readonly Delegate _activator; + /// /// Initializes a new instance of the struct. /// @@ -539,8 +565,8 @@ ExceptionDispatchInfo exceptionInfo typeof(CreateProxyInstance<>).MakeGenericType(proxyTypeDefinition), this); } - } - + } + /// /// Gets the Proxy type /// @@ -552,8 +578,8 @@ public Type ProxyType _exceptionInfo?.Throw(); return _proxyType; } - } - + } + /// /// Create a new proxy instance from a target instance /// @@ -561,8 +587,8 @@ public Type ProxyType /// Target instance value /// Proxy instance [MethodImpl(MethodImplOptions.AggressiveInlining)] - public T CreateInstance(object instance) => ((CreateProxyInstance)_activator)(instance); - + public T CreateInstance(object instance) => ((CreateProxyInstance)_activator)(instance); + /// /// Get if the proxy instance can be created /// @@ -579,26 +605,26 @@ private T ThrowOnError(object instance) _exceptionInfo.Throw(); return default; } - } - + } + /// /// Generics Create Cache FastPath /// /// Type of proxy definition public static class CreateCache - { + { /// /// Gets the type of T /// - public static readonly Type Type = typeof(T); - + public static readonly Type Type = typeof(T); + /// /// Gets if the T type is visible /// public static readonly bool IsVisible = Type.IsPublic || Type.IsNestedPublic; - private static CreateTypeResult _fastPath; - + private static CreateTypeResult _fastPath; + /// /// Gets the proxy type for a target type using the T proxy definition /// @@ -606,8 +632,8 @@ public static class CreateCache /// CreateTypeResult instance [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CreateTypeResult GetProxy(Type targetType) - { - // We set a fast path for the first proxy type for a proxy definition. (It's likely to have a proxy definition just for one target type) + { + // We set a fast path for the first proxy type for a proxy definition. (It's likely to have a proxy definition just for one target type) var fastPath = _fastPath; if (fastPath.TargetType == targetType) return fastPath; @@ -619,8 +645,8 @@ public static CreateTypeResult GetProxy(Type targetType) _fastPath = result; return result; - } - + } + /// /// Create a new instance of a proxy type for a target instance using the T proxy definition /// @@ -633,8 +659,8 @@ public static T Create(object instance) return default; return GetProxy(instance.GetType()).CreateInstance(instance); - } - + } + /// /// Get if the proxy instance can be created /// @@ -651,7 +677,7 @@ public static bool CanCreate(object instance) [MethodImpl(MethodImplOptions.AggressiveInlining)] private static CreateTypeResult GetProxySlow(Type targetType) - { + { #if NET45 if (!Type.IsValueType && !IsVisible) { diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckTypeExceptions.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckTypeExceptions.cs index ae90cc080..e77a48ead 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckTypeExceptions.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckTypeExceptions.cs @@ -1,22 +1,22 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Diagnostics; -using System.Reflection; - +using System.Reflection; + #pragma warning disable SA1649 // File name must match first type name #pragma warning disable SA1402 // File may only contain a single class - + namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// DuckType Exception /// @@ -24,8 +24,8 @@ public class DuckTypeException : Exception { internal DuckTypeException(string message) : base(message) { } - } - + } + /// /// DuckType proxy type definition is null /// @@ -36,8 +36,8 @@ private DuckTypeProxyTypeDefinitionIsNull() [DebuggerHidden] internal static void Throw() => throw new DuckTypeProxyTypeDefinitionIsNull(); - } - + } + /// /// DuckType target object instance is null /// @@ -48,8 +48,8 @@ private DuckTypeTargetObjectInstanceIsNull() [DebuggerHidden] internal static void Throw() => throw new DuckTypeTargetObjectInstanceIsNull(); - } - + } + /// /// DuckType invalid type conversion exception /// @@ -60,8 +60,8 @@ private DuckTypeInvalidTypeConversionException(Type actualType, Type expectedTyp [DebuggerHidden] internal static void Throw(Type actualType, Type expectedType) => throw new DuckTypeInvalidTypeConversionException(actualType, expectedType); - } - + } + /// /// DuckType property can't be read /// @@ -69,12 +69,13 @@ public class DuckTypePropertyCantBeReadException : DuckTypeException { private DuckTypePropertyCantBeReadException(PropertyInfo property) : base( - $"The property '{property.Name}' can't be read, you should remove the getter from the proxy definition base type class or interface.") { } + $"The property '{property.Name}' can't be read, you should remove the getter from the proxy definition base type class or interface.") + { } [DebuggerHidden] internal static void Throw(PropertyInfo property) => throw new DuckTypePropertyCantBeReadException(property); - } - + } + /// /// DuckType property can't be written /// @@ -82,12 +83,13 @@ public class DuckTypePropertyCantBeWrittenException : DuckTypeException { private DuckTypePropertyCantBeWrittenException(PropertyInfo property) : base( - $"The property '{property.Name}' can't be written, you should remove the setter from the proxy definition base type class or interface.") { } + $"The property '{property.Name}' can't be written, you should remove the setter from the proxy definition base type class or interface.") + { } [DebuggerHidden] internal static void Throw(PropertyInfo property) => throw new DuckTypePropertyCantBeWrittenException(property); - } - + } + /// /// DuckType property argument doesn't have the same argument length /// @@ -98,8 +100,8 @@ private DuckTypePropertyArgumentsLengthException(PropertyInfo property) [DebuggerHidden] internal static void Throw(PropertyInfo property) => throw new DuckTypePropertyArgumentsLengthException(property); - } - + } + /// /// DuckType field is readonly /// @@ -110,8 +112,8 @@ private DuckTypeFieldIsReadonlyException(FieldInfo field) [DebuggerHidden] internal static void Throw(FieldInfo field) => throw new DuckTypeFieldIsReadonlyException(field); - } - + } + /// /// DuckType property or field not found /// @@ -123,8 +125,8 @@ private DuckTypePropertyOrFieldNotFoundException(string name, string duckAttribu [DebuggerHidden] internal static void Throw(string name, string duckAttributeName) => throw new DuckTypePropertyOrFieldNotFoundException(name, duckAttributeName); - } - + } + /// /// DuckType type is not public exception /// @@ -135,8 +137,8 @@ private DuckTypeTypeIsNotPublicException(Type type, string argumentName) [DebuggerHidden] internal static void Throw(Type type, string argumentName) => throw new DuckTypeTypeIsNotPublicException(type, argumentName); - } - + } + /// /// DuckType struct members cannot be changed exception /// @@ -147,8 +149,8 @@ private DuckTypeStructMembersCannotBeChangedException(Type type) [DebuggerHidden] internal static void Throw(Type type) => throw new DuckTypeStructMembersCannotBeChangedException(type); - } - + } + /// /// DuckType target method can not be found exception /// @@ -159,8 +161,8 @@ private DuckTypeTargetMethodNotFoundException(MethodInfo method) [DebuggerHidden] internal static void Throw(MethodInfo method) => throw new DuckTypeTargetMethodNotFoundException(method); - } - + } + /// /// DuckType proxy method parameter is missing exception /// @@ -172,8 +174,8 @@ private DuckTypeProxyMethodParameterIsMissingException(MethodInfo proxyMethod, P [DebuggerHidden] internal static void Throw(MethodInfo proxyMethod, ParameterInfo targetParameterInfo) => throw new DuckTypeProxyMethodParameterIsMissingException(proxyMethod, targetParameterInfo); - } - + } + /// /// DuckType parameter signature mismatch between proxy and target method /// @@ -185,8 +187,8 @@ private DuckTypeProxyAndTargetMethodParameterSignatureMismatchException(MethodIn [DebuggerHidden] internal static void Throw(MethodInfo proxyMethod, MethodInfo targetMethod) => throw new DuckTypeProxyAndTargetMethodParameterSignatureMismatchException(proxyMethod, targetMethod); - } - + } + /// /// DuckType proxy methods with generic parameters are not supported in non public instances exception /// @@ -198,8 +200,8 @@ private DuckTypeProxyMethodsWithGenericParametersNotSupportedInNonPublicInstance [DebuggerHidden] internal static void Throw(MethodInfo proxyMethod) => throw new DuckTypeProxyMethodsWithGenericParametersNotSupportedInNonPublicInstancesException(proxyMethod); - } - + } + /// /// DuckType proxy method has an ambiguous match in the target type exception /// @@ -207,7 +209,8 @@ public class DuckTypeTargetMethodAmbiguousMatchException : DuckTypeException { private DuckTypeTargetMethodAmbiguousMatchException(MethodInfo proxyMethod, MethodInfo targetMethod, MethodInfo targetMethod2) : base( - $"The proxy method '{proxyMethod}' matches at least two methods in the target type. Method1 = '{targetMethod}' and Method2 = '{targetMethod2}'") { } + $"The proxy method '{proxyMethod}' matches at least two methods in the target type. Method1 = '{targetMethod}' and Method2 = '{targetMethod2}'") + { } [DebuggerHidden] internal static void Throw(MethodInfo proxyMethod, MethodInfo targetMethod, MethodInfo targetMethod2) => diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckTypeExtensions.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckTypeExtensions.cs index 5510a2bbe..c37dafc92 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckTypeExtensions.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/DuckTypeExtensions.cs @@ -1,23 +1,23 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Runtime.CompilerServices; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck type extensions /// public static class DuckTypeExtensions - { + { /// /// Gets the duck type instance for the object implementing a base class or interface T /// @@ -26,8 +26,8 @@ public static class DuckTypeExtensions /// DuckType instance [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T DuckCast(this object instance) - => DuckType.Create(instance); - + => DuckType.Create(instance); + /// /// Gets the duck type instance for the object implementing a base class or interface T /// @@ -36,8 +36,8 @@ public static T DuckCast(this object instance) /// DuckType instance [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object DuckCast(this object instance, Type targetType) - => DuckType.Create(targetType, instance); - + => DuckType.Create(targetType, instance); + /// /// Tries to ducktype the object implementing a base class or interface T /// @@ -63,8 +63,8 @@ public static bool TryDuckCast(this object instance, out T value) value = default; return false; - } - + } + /// /// Tries to ducktype the object implementing a base class or interface T /// @@ -90,8 +90,8 @@ public static bool TryDuckCast(this object instance, Type targetType, out object value = default; return false; - } - + } + /// /// Gets the duck type instance for the object implementing a base class or interface T /// @@ -113,8 +113,8 @@ public static T DuckAs(this object instance) } return null; - } - + } + /// /// Gets the duck type instance for the object implementing a base class or interface T /// @@ -135,8 +135,8 @@ public static object DuckAs(this object instance, Type targetType) } return null; - } - + } + /// /// Gets if a proxy can be created /// @@ -153,8 +153,8 @@ public static bool DuckIs(this object instance) return DuckType.CanCreate(instance); return false; - } - + } + /// /// Gets if a proxy can be created /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/IDuckType.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/IDuckType.cs index 8693c3457..d754c1bbd 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/IDuckType.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/IDuckType.cs @@ -1,27 +1,27 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Duck type interface /// public interface IDuckType - { + { /// /// Gets instance /// - object Instance { get; } - + object Instance { get; } + /// /// Gets instance Type /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/ILHelpersExtensions.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/ILHelpersExtensions.cs index 68d411aaf..f16d081c9 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/ILHelpersExtensions.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/ILHelpersExtensions.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Linq; @@ -15,7 +15,7 @@ using System.Reflection.Emit; namespace Elastic.Apm.Profiler.Managed.DuckTyping -{ +{ /// /// Internal IL Helpers /// @@ -34,30 +34,32 @@ internal static void CreateDelegateTypeFor(TypeBuilder proxyType, DynamicMethod var modBuilder = (ModuleBuilder)proxyType.Module; var delegateType = modBuilder.DefineType($"{dynamicMethod.Name}Delegate_" + Guid.NewGuid().ToString("N"), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, - typeof(MulticastDelegate)); - - // Delegate .ctor + typeof(MulticastDelegate)); + + // Delegate .ctor var constructorBuilder = delegateType.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) }); - constructorBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); - - // Define the Invoke method for the delegate + constructorBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); + + // Define the Invoke method for the delegate var parameters = dynamicMethod.GetParameters(); var paramTypes = new Type[parameters.Length]; - for (var i = 0; i < parameters.Length; i++) paramTypes[i] = parameters[i].ParameterType; + for (var i = 0; i < parameters.Length; i++) + paramTypes[i] = parameters[i].ParameterType; var methodBuilder = delegateType.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, dynamicMethod.ReturnType, paramTypes); - for (var i = 0; i < parameters.Length; i++) methodBuilder.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name); + for (var i = 0; i < parameters.Length; i++) + methodBuilder.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name); methodBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); delType = delegateType.CreateTypeInfo().AsType(); invokeMethod = delType.GetMethod("Invoke"); - } - + } + /// /// Load instance argument /// @@ -67,7 +69,8 @@ internal static void CreateDelegateTypeFor(TypeBuilder proxyType, DynamicMethod internal static void LoadInstanceArgument(this LazyILGenerator il, Type actualType, Type expectedType) { il.Emit(OpCodes.Ldarg_0); - if (actualType == expectedType) return; + if (actualType == expectedType) + return; if (expectedType.IsValueType) { @@ -78,8 +81,8 @@ internal static void LoadInstanceArgument(this LazyILGenerator il, Type actualTy } else il.Emit(OpCodes.Castclass, expectedType); - } - + } + /// /// Write load arguments /// @@ -88,7 +91,8 @@ internal static void LoadInstanceArgument(this LazyILGenerator il, Type actualTy /// Define if we need to take into account the instance argument internal static void WriteLoadArgument(this LazyILGenerator il, int index, bool isStatic) { - if (!isStatic) index += 1; + if (!isStatic) + index += 1; switch (index) { @@ -108,8 +112,8 @@ internal static void WriteLoadArgument(this LazyILGenerator il, int index, bool il.Emit(OpCodes.Ldarg_S, index); break; } - } - + } + /// /// Write load local /// @@ -135,8 +139,8 @@ internal static void WriteLoadLocal(this LazyILGenerator il, int index) il.Emit(OpCodes.Ldloc_S, index); break; } - } - + } + /// /// Write load local /// @@ -162,8 +166,8 @@ internal static void WriteLoadLocal(this ILGenerator il, int index) il.Emit(OpCodes.Ldloc_S, index); break; } - } - + } + /// /// Write store local /// @@ -189,8 +193,8 @@ internal static void WriteStoreLocal(this LazyILGenerator il, int index) il.Emit(OpCodes.Stloc_S, index); break; } - } - + } + /// /// Write constant int value /// @@ -238,8 +242,8 @@ internal static void WriteInt(this LazyILGenerator il, int value) il.Emit(OpCodes.Ldc_I4_S, value); else il.Emit(OpCodes.Ldc_I4, value); - } - + } + /// /// Convert a current type to an expected type /// @@ -251,35 +255,36 @@ internal static void WriteTypeConversion(this LazyILGenerator il, Type actualTyp var actualUnderlyingType = actualType.IsEnum ? Enum.GetUnderlyingType(actualType) : actualType; var expectedUnderlyingType = expectedType.IsEnum ? Enum.GetUnderlyingType(expectedType) : expectedType; - if (actualUnderlyingType == expectedUnderlyingType) return; + if (actualUnderlyingType == expectedUnderlyingType) + return; if (actualUnderlyingType.IsValueType) { if (expectedUnderlyingType.IsValueType) - { - // If both underlying types are value types then both must be of the same type. + { + // If both underlying types are value types then both must be of the same type. DuckTypeInvalidTypeConversionException.Throw(actualType, expectedType); } else - { - // An underlying type can be boxed and converted to an object or interface type if the actual type support this - // if not we should throw. + { + // An underlying type can be boxed and converted to an object or interface type if the actual type support this + // if not we should throw. if (expectedUnderlyingType == typeof(object)) - { - // If the expected type is object we just need to box the value + { + // If the expected type is object we just need to box the value il.Emit(OpCodes.Box, actualType); } else if (expectedUnderlyingType.IsAssignableFrom(actualUnderlyingType)) - { - // If the expected type can be assigned from the value type (ex: struct implementing an interface) + { + // If the expected type can be assigned from the value type (ex: struct implementing an interface) il.Emit(OpCodes.Box, actualType); il.Emit(OpCodes.Castclass, expectedType); } else - { - // If the expected type can't be assigned from the actual value type. - // Means if the expected type is an interface the actual type doesn't implement it. - // So no possible conversion or casting can be made here. + { + // If the expected type can't be assigned from the actual value type. + // Means if the expected type is an interface the actual type doesn't implement it. + // So no possible conversion or casting can be made here. DuckTypeInvalidTypeConversionException.Throw(actualType, expectedType); } } @@ -287,12 +292,12 @@ internal static void WriteTypeConversion(this LazyILGenerator il, Type actualTyp else { if (expectedUnderlyingType.IsValueType) - { - // We only allow conversions from objects or interface type if the actual type support this - // if not we should throw. + { + // We only allow conversions from objects or interface type if the actual type support this + // if not we should throw. if (actualUnderlyingType == typeof(object) || actualUnderlyingType.IsAssignableFrom(expectedUnderlyingType)) - { - // WARNING: The actual type instance can't be detected at this point, we have to check it at runtime. + { + // WARNING: The actual type instance can't be detected at this point, we have to check it at runtime. /* * In this case we emit something like: * { @@ -302,7 +307,7 @@ internal static void WriteTypeConversion(this LazyILGenerator il, Type actualTyp * * return ([expectedType])value; * } - */ + */ var lblIsExpected = il.DefineLabel(); il.Emit(OpCodes.Dup); @@ -318,10 +323,11 @@ internal static void WriteTypeConversion(this LazyILGenerator il, Type actualTyp else DuckTypeInvalidTypeConversionException.Throw(actualType, expectedType); } - else if (expectedUnderlyingType != typeof(object)) il.Emit(OpCodes.Castclass, expectedUnderlyingType); + else if (expectedUnderlyingType != typeof(object)) + il.Emit(OpCodes.Castclass, expectedUnderlyingType); } - } - + } + /// /// Write a Call to a method using Calli /// @@ -337,8 +343,8 @@ internal static void WriteMethodCalli(this LazyILGenerator il, MethodInfo method method.ReturnType, method.GetParameters().Select(p => p.ParameterType).ToArray(), null); - } - + } + /// /// Write a DynamicMethod call by creating and injecting a custom delegate in the proxyType /// @@ -346,27 +352,27 @@ internal static void WriteMethodCalli(this LazyILGenerator il, MethodInfo method /// Dynamic method to get called /// ProxyType builder internal static void WriteDynamicMethodCall(this LazyILGenerator il, DynamicMethod dynamicMethod, TypeBuilder proxyType) - { - // We create a custom delegate inside the module builder + { + // We create a custom delegate inside the module builder CreateDelegateTypeFor(proxyType, dynamicMethod, out var delegateType, out var invokeMethod); int index; lock (_dynamicMethods) { _dynamicMethods.Add(dynamicMethod); index = _dynamicMethods.Count - 1; - } - - // We fill the DelegateCache<> for that custom type with the delegate instance + } + + // We fill the DelegateCache<> for that custom type with the delegate instance var fillDelegateMethodInfo = typeof(Elastic.Apm.Profiler.Managed.DuckTyping.DuckType.DelegateCache<>).MakeGenericType(delegateType) .GetMethod("FillDelegate", BindingFlags.NonPublic | BindingFlags.Static); - fillDelegateMethodInfo.Invoke(null, new object[] { index }); - - // We get the delegate instance and load it in to the stack before the parameters (at the begining of the IL body) + fillDelegateMethodInfo.Invoke(null, new object[] { index }); + + // We get the delegate instance and load it in to the stack before the parameters (at the begining of the IL body) il.SetOffset(0); il.EmitCall(OpCodes.Call, typeof(DuckType.DelegateCache<>).MakeGenericType(delegateType).GetMethod("GetDelegate"), null); - il.ResetOffset(); - - // We emit the call to the delegate invoke method. + il.ResetOffset(); + + // We emit the call to the delegate invoke method. il.EmitCall(OpCodes.Callvirt, invokeMethod, null); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/IgnoresAccessChecksToAttribute.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/IgnoresAccessChecksToAttribute.cs index e555edae7..f38785a15 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/IgnoresAccessChecksToAttribute.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/IgnoresAccessChecksToAttribute.cs @@ -1,29 +1,29 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - -// ReSharper disable once CheckNamespace - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +// ReSharper disable once CheckNamespace + namespace System.Runtime.CompilerServices -{ +{ /// /// This attribute is recognized by the CLR and allow us to disable visibility checks for certain assemblies (only from 4.6+) /// [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class IgnoresAccessChecksToAttribute : Attribute - { + { /// /// Initializes a new instance of the class. /// /// Assembly name - public IgnoresAccessChecksToAttribute(string assemblyName) => AssemblyName = assemblyName; - + public IgnoresAccessChecksToAttribute(string assemblyName) => AssemblyName = assemblyName; + /// /// Gets the assembly name /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/LazyILGenerator.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/LazyILGenerator.cs index 3a39a4d54..e50181295 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/LazyILGenerator.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/LazyILGenerator.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Reflection; diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/TypesTuple.cs b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/TypesTuple.cs index c68a521eb..a5c985fc9 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/TypesTuple.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/DuckTyping/TypesTuple.cs @@ -1,29 +1,29 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.DuckTyping { internal readonly struct TypesTuple : IEquatable - { + { /// /// The proxy definition type /// - public readonly Type ProxyDefinitionType; - + public readonly Type ProxyDefinitionType; + /// /// The target type /// - public readonly Type TargetType; - + public readonly Type TargetType; + /// /// Initializes a new instance of the struct. /// @@ -33,8 +33,8 @@ public TypesTuple(Type proxyDefinitionType, Type targetType) { ProxyDefinitionType = proxyDefinitionType; TargetType = targetType; - } - + } + /// /// Gets the struct hashcode /// @@ -48,8 +48,8 @@ public override int GetHashCode() hash = (hash ^ TargetType.GetHashCode()) * 16777619; return hash; } - } - + } + /// /// Gets if the struct is equal to other object or struct /// @@ -58,8 +58,8 @@ public override int GetHashCode() public override bool Equals(object obj) => obj is TypesTuple vTuple && ProxyDefinitionType == vTuple.ProxyDefinitionType && - TargetType == vTuple.TargetType; - + TargetType == vTuple.TargetType; + /// public bool Equals(TypesTuple other) => ProxyDefinitionType == other.ProxyDefinitionType && diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/ExecutionSegmentExtensions.cs b/src/profiler/Elastic.Apm.Profiler.Managed/ExecutionSegmentExtensions.cs index 0bb879ad3..4a642a0d5 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/ExecutionSegmentExtensions.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/ExecutionSegmentExtensions.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Runtime.CompilerServices; using Elastic.Apm.Api; diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/AdoNetTypeNames.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/AdoNetTypeNames.cs index 85fd74354..64d835589 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/AdoNetTypeNames.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/AdoNetTypeNames.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Elastic.Apm.Profiler.Managed.Core; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryAsyncIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryAsyncIntegration.cs index 0a073b6e5..a85733902 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryAsyncIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryAsyncIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using System.Threading; @@ -16,7 +16,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// Task[int] [Command].ExecuteNonQueryAsync(CancellationToken) @@ -36,7 +36,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentSystemData(Method = ExecuteNonQueryAsync, ReturnType = TaskInt32, ParameterTypes = new[] { ClrTypeNames.CancellationToken })] [InstrumentSystemDataCommon(Method = ExecuteNonQueryAsync, ReturnType = TaskInt32, ParameterTypes = new[] { ClrTypeNames.CancellationToken })] public class CommandExecuteNonQueryAsyncIntegration - { + { /// /// OnMethodBegin callback /// @@ -48,8 +48,8 @@ public static CallTargetState OnMethodBegin(TTarget instance, Cancellat { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnAsyncMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryIntegration.cs index 1212f1aad..25230ca6f 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using Elastic.Apm.Api; @@ -15,7 +15,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// int [Command].ExecuteNonQuery() @@ -30,7 +30,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentSystemDataSqlClient(Method = ExecuteNonQuery, ReturnType = ClrTypeNames.Int32)] [InstrumentMicrosoftDataSqlClient(Method = ExecuteNonQuery, ReturnType = ClrTypeNames.Int32)] public class CommandExecuteNonQueryIntegration - { + { /// /// OnMethodBegin callback /// @@ -41,8 +41,8 @@ public static CallTargetState OnMethodBegin(TTarget instance) { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryWithBehaviorIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryWithBehaviorIntegration.cs index 10b26ce56..72356d156 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryWithBehaviorIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteNonQueryWithBehaviorIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using Elastic.Apm.Api; @@ -15,7 +15,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// int [Command].ExecuteNonQuery(CommandBehavior) @@ -36,7 +36,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentMicrosoftDataSqlClient(Method = ExecuteNonQuery, ReturnType = ClrTypeNames.Int32, ParameterTypes = new[] { AdoNetTypeNames.CommandBehavior })] public class CommandExecuteNonQueryWithBehaviorIntegration - { + { /// /// OnMethodBegin callback /// @@ -49,8 +49,8 @@ public class CommandExecuteNonQueryWithBehaviorIntegration { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderAsyncIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderAsyncIntegration.cs index 48957790a..38ff45c4c 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderAsyncIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderAsyncIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using System.Threading; @@ -16,7 +16,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// Task[*DataReader] [Command].ExecuteReaderAsync(CancellationToken) @@ -39,7 +39,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentMicrosoftDataSqlClient(Method = ExecuteReaderAsync, ReturnType = MicrosoftDataSqlServer.TaskDataReader, ParameterTypes = new[] { ClrTypeNames.CancellationToken })] public class CommandExecuteReaderAsyncIntegration - { + { /// /// OnMethodBegin callback /// @@ -51,8 +51,8 @@ public static CallTargetState OnMethodBegin(TTarget instance, Cancellat { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnAsyncMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderIntegration.cs index b8a2d2592..3db673fae 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using Elastic.Apm.Api; @@ -14,7 +14,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// [*]DataReader [Command].ExecuteReader() @@ -29,7 +29,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentSystemDataSqlClient(Method = ExecuteReader, ReturnType = SystemDataSqlServer.DataReader)] [InstrumentMicrosoftDataSqlClient(Method = ExecuteReader, ReturnType = MicrosoftDataSqlServer.DataReader)] public class CommandExecuteReaderIntegration - { + { /// /// OnMethodBegin callback /// @@ -40,8 +40,8 @@ public static CallTargetState OnMethodBegin(TTarget instance) { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderWithBehaviorAsyncIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderWithBehaviorAsyncIntegration.cs index 9b2df53c9..b7e7686c4 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderWithBehaviorAsyncIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderWithBehaviorAsyncIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using System.Threading; @@ -16,7 +16,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// Task[*DataReader] [Command].ExecuteReaderAsync(CommandBehavior, CancellationToken) @@ -61,7 +61,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentSystemDataCommon(Method = ExecuteDbDataReaderAsync, ReturnType = TaskDbDataReader, ParameterTypes = new[] { AdoNetTypeNames.CommandBehavior, ClrTypeNames.CancellationToken })] public class CommandExecuteReaderWithBehaviorAsyncIntegration - { + { /// /// OnMethodBegin callback /// @@ -77,8 +77,8 @@ CancellationToken cancellationToken { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnAsyncMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderWithBehaviorIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderWithBehaviorIntegration.cs index c4039f6db..63c26441d 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderWithBehaviorIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteReaderWithBehaviorIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using Elastic.Apm.Api; @@ -14,7 +14,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// [*]DataReader [Command].ExecuteReader(CommandBehavior) @@ -50,7 +50,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentMicrosoftDataSqlClient(Method = ExecuteDbDataReader, ReturnType = DbDataReader, ParameterTypes = new[] { AdoNetTypeNames.CommandBehavior })] public class CommandExecuteReaderWithBehaviorIntegration - { + { /// /// OnMethodBegin callback /// @@ -63,8 +63,8 @@ public class CommandExecuteReaderWithBehaviorIntegration { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarAsyncIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarAsyncIntegration.cs index 13366d1e2..92861bc98 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarAsyncIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarAsyncIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using System.Threading; @@ -16,7 +16,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// Task[object] [Command].ExecuteScalarAsync(CancellationToken) @@ -36,7 +36,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentSystemData(Method = ExecuteScalarAsync, ReturnType = TaskObject, ParameterTypes = new[] { ClrTypeNames.CancellationToken })] [InstrumentSystemDataCommon(Method = ExecuteScalarAsync, ReturnType = TaskObject, ParameterTypes = new[] { ClrTypeNames.CancellationToken })] public class CommandExecuteScalarAsyncIntegration - { + { /// /// OnMethodBegin callback /// @@ -48,8 +48,8 @@ public static CallTargetState OnMethodBegin(TTarget instance, Cancellat { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnAsyncMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarIntegration.cs index 4f779e857..00525388f 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using Elastic.Apm.Api; @@ -15,7 +15,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// object [Command].ExecuteScalar() @@ -30,7 +30,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentSystemDataSqlClient(Method = ExecuteScalar, ReturnType = ClrTypeNames.Object)] [InstrumentMicrosoftDataSqlClient(Method = ExecuteScalar, ReturnType = ClrTypeNames.Object)] public class CommandExecuteScalarIntegration - { + { /// /// OnMethodBegin callback /// @@ -41,8 +41,8 @@ public static CallTargetState OnMethodBegin(TTarget instance) { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarWithBehaviorIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarWithBehaviorIntegration.cs index 79e93cef7..c50fce4e7 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarWithBehaviorIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/CommandExecuteScalarWithBehaviorIntegration.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Data; using Elastic.Apm.Api; @@ -15,7 +15,7 @@ using static Elastic.Apm.Profiler.Managed.Integrations.AdoNet.AdoNetTypeNames; namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet -{ +{ /// /// CallTarget instrumentation for: /// object [Command].ExecuteScalar(CommandBehavior) @@ -35,7 +35,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AdoNet [InstrumentMicrosoftDataSqlClient(Method = ExecuteScalar, ReturnType = ClrTypeNames.Object, ParameterTypes = new[] { AdoNetTypeNames.CommandBehavior })] public class CommandExecuteScalarWithBehaviorIntegration - { + { /// /// OnMethodBegin callback /// @@ -48,8 +48,8 @@ public class CommandExecuteScalarWithBehaviorIntegration { var command = (IDbCommand)instance; return new CallTargetState(DbSpanFactory.CreateSpan(Agent.Instance, command), command); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/DbSpanFactory.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/DbSpanFactory.cs index 168bf9ee6..adb396193 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/DbSpanFactory.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AdoNet/DbSpanFactory.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Data; using Elastic.Apm.Api; @@ -25,18 +25,18 @@ static DbSpanFactory() internal static ISpan CreateSpan(ApmAgent agent, IDbCommand command) { if (agent.Tracer.CurrentTransaction is null) - return null; - - // if the current execution segment is - // 1. already for this instrumentation or instrumentation is AdoNet (System.Data.Common.DbCommand) and the type is "db" - // and - // 2. for the same command text - // skip creating another db span for it, to prevent instrumenting delegated methods. - if (agent.GetCurrentExecutionSegment() is Span span && - (span.InstrumentationFlag.HasFlag(_instrumentationFlag) || - span.Type == ApiConstants.TypeDb && - (_instrumentationFlag == InstrumentationFlag.AdoNet || span.InstrumentationFlag == InstrumentationFlag.AdoNet)) && - span.Name == DbSpanCommon.GetDbSpanName(command)) + return null; + + // if the current execution segment is + // 1. already for this instrumentation or instrumentation is AdoNet (System.Data.Common.DbCommand) and the type is "db" + // and + // 2. for the same command text + // skip creating another db span for it, to prevent instrumenting delegated methods. + if (agent.GetCurrentExecutionSegment() is Span span && + (span.InstrumentationFlag.HasFlag(_instrumentationFlag) || + span.Type == ApiConstants.TypeDb && + (_instrumentationFlag == InstrumentationFlag.AdoNet || span.InstrumentationFlag == InstrumentationFlag.AdoNet)) && + span.Name == DbSpanCommon.GetDbSpanName(command)) return null; return agent.TracerInternal.DbSpanCommon.StartSpan(agent, command, _instrumentationFlag); diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AspNet/ElasticApmModuleIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AspNet/ElasticApmModuleIntegration.cs index d2fc66f7a..35679c3e8 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AspNet/ElasticApmModuleIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/AspNet/ElasticApmModuleIntegration.cs @@ -1,24 +1,24 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - - -using System.Threading; +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + + +using System.Threading; #if NETFRAMEWORK using System.Web; -using Elastic.Apm.AspNetFullFramework; +using Elastic.Apm.AspNetFullFramework; #endif using Elastic.Apm.Profiler.Managed.CallTarget; using Elastic.Apm.Profiler.Managed.Core; namespace Elastic.Apm.Profiler.Managed.Integrations.AspNet -{ +{ /// /// System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore calltarget instrumentation /// @@ -33,12 +33,12 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.AspNet MaximumVersion = "4.*.*", Group = "AspNet")] public class ElasticApmModuleIntegration - { + { /// /// Indicates whether we're initializing the HttpModule for the first time /// - private static int FirstInitialization = 1; - + private static int FirstInitialization = 1; + /// /// OnMethodBegin callback /// @@ -54,23 +54,23 @@ TFunc setHostingEnvironmentCultures ) { if (Interlocked.Exchange(ref FirstInitialization, 0) != 1) - { - // The HttpModule was already registered + { + // The HttpModule was already registered return CallTargetState.GetDefault(); } try - { -// directive applied just to here and to .NET framework specific using directives, to allow -// the integrations file generator to pick this integration up, irrespective of version. + { + // directive applied just to here and to .NET framework specific using directives, to allow + // the integrations file generator to pick this integration up, irrespective of version. #if NETFRAMEWORK - HttpApplication.RegisterModule(typeof(ElasticApmModule)); + HttpApplication.RegisterModule(typeof(ElasticApmModule)); #endif } catch - { - // Unable to dynamically register module - // Not sure if we can technically log yet or not, so do nothing + { + // Unable to dynamically register module + // Not sure if we can technically log yet or not, so do nothing } return CallTargetState.GetDefault(); diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/CachedMessageHeadersHelper.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/CachedMessageHeadersHelper.cs index 98ba07aa9..dca9dbe11 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/CachedMessageHeadersHelper.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/CachedMessageHeadersHelper.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Reflection.Emit; using Elastic.Apm.Profiler.Managed.DuckTyping; @@ -36,8 +36,8 @@ static CachedMessageHeadersHelper() il.Emit(OpCodes.Ret); _activator = (Func)createHeadersMethod.CreateDelegate(typeof(Func)); - } - + } + /// /// Creates a Confluent.Kafka.Headers object and assigns it to an `IMessage` proxy /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IConsumeException.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IConsumeException.cs index 908843f02..038a5e84c 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IConsumeException.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IConsumeException.cs @@ -1,24 +1,24 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// ConsumeException interface for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IConsumeException - { + { /// /// Gets the consume result associated with the consume request /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IConsumeResult.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IConsumeResult.cs index e16d053b9..0155b08ac 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IConsumeResult.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IConsumeResult.cs @@ -1,43 +1,43 @@ -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// ConsumeResult for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IConsumeResult - { + { /// /// Gets the topic /// - public string Topic { get; } - + public string Topic { get; } + /// /// Gets the partition /// - public Partition Partition { get; } - + public Partition Partition { get; } + /// /// Gets the offset /// - public Offset Offset { get; } - + public Offset Offset { get; } + /// /// Gets the Kafka record /// - public IMessage Message { get; } - + public IMessage Message { get; } + /// /// Gets a value indicating whether gets whether the message is a partition EOF /// - // ReSharper disable once InconsistentNaming + // ReSharper disable once InconsistentNaming public bool IsPartitionEOF { get; } } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IDeliveryReport.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IDeliveryReport.cs index 160cefc88..232bc1883 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IDeliveryReport.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IDeliveryReport.cs @@ -1,24 +1,24 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// DeliveryReport interface for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IDeliveryReport : IDeliveryResult - { + { /// /// Gets the Error associated with the delivery report /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IDeliveryResult.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IDeliveryResult.cs index d31c884f5..8a570e482 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IDeliveryResult.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IDeliveryResult.cs @@ -1,29 +1,29 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// DeliveryResult interface for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IDeliveryResult - { + { /// /// Gets the Kafka partition. /// - public Partition Partition { get; } - + public Partition Partition { get; } + /// /// Gets the Kafka offset /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IError.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IError.cs index 37a0ccf65..e8ee09ed3 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IError.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IError.cs @@ -1,29 +1,29 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Error interface for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IError - { + { /// /// Gets a value indicating whether the error is really an error /// - public bool IsError { get; } - + public bool IsError { get; } + /// /// Gets the string representation of the error /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IHeaders.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IHeaders.cs index 64fbfa02c..28a7cc4e5 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IHeaders.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IHeaders.cs @@ -1,37 +1,37 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Headers interface for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IHeaders - { + { /// /// Adds a header to the collection /// /// The header's key value /// The value of the header. May be null. Format strings as UTF8 - public void Add(string key, byte[] val); - + public void Add(string key, byte[] val); + /// /// Removes all headers for the given key. /// /// The key to remove all headers for - public void Remove(string key); - + public void Remove(string key); + /// /// Try to get the value of the latest header with the specified key. /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IMessage.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IMessage.cs index 9019cf079..1ff70d5a0 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IMessage.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IMessage.cs @@ -1,34 +1,34 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Message interface for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IMessage - { + { /// /// Gets the value of the message /// - public object Value { get; } - + public object Value { get; } + /// /// Gets the timestamp that the message was produced /// - public ITimestamp Timestamp { get; } - + public ITimestamp Timestamp { get; } + /// /// Gets or sets the headers for the record /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IProduceException.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IProduceException.cs index ea65775e2..9184bbf17 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IProduceException.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/IProduceException.cs @@ -1,24 +1,24 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// ProduceException interface for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IProduceException - { + { /// /// Gets the delivery result associated with the produce request /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITimestamp.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITimestamp.cs index e9d335482..25e846fc0 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITimestamp.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITimestamp.cs @@ -1,18 +1,18 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Timestamp struct for duck-typing /// Requires boxing, but necessary as we need to duck-type too @@ -20,12 +20,12 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface ITimestamp - { + { /// /// Gets the timestamp type /// - public int Type { get; } - + public int Type { get; } + /// /// Gets the UTC DateTime for the timestamp /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITopicPartition.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITopicPartition.cs index 1cfc27873..c074f083b 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITopicPartition.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITopicPartition.cs @@ -1,29 +1,29 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// TopicPartition interface for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface ITopicPartition - { + { /// /// Gets the Kafka topic name. /// - public string Topic { get; } - + public string Topic { get; } + /// /// Gets the Kafka partition. /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITypedDeliveryHandlerShimAction.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITypedDeliveryHandlerShimAction.cs index e6c5d1ef2..2865aab51 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITypedDeliveryHandlerShimAction.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/ITypedDeliveryHandlerShimAction.cs @@ -1,25 +1,25 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// TypedDeliveryHandlerShim_Action for duck-typing /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface ITypedDeliveryHandlerShimAction - { + { /// /// Sets the delivery report handler /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerCloseIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerCloseIntegration.cs index d900f6402..bb01f13f3 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerCloseIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerCloseIntegration.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; using Elastic.Apm.Profiler.Managed.CallTarget; using Elastic.Apm.Profiler.Managed.Core; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Confluent.Kafka Consumer.Consume calltarget instrumentation /// @@ -30,7 +30,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public class KafkaConsumerCloseIntegration - { + { /// /// OnMethodBegin callback /// @@ -38,12 +38,12 @@ public class KafkaConsumerCloseIntegration /// Instance value, aka `this` of the instrumented method. /// Calltarget state value public static CallTargetState OnMethodBegin(TTarget instance) - { - // If we are already in a consumer scope, close it. + { + // If we are already in a consumer scope, close it. KafkaIntegration.CloseConsumerTransaction(Agent.Instance); return CallTargetState.GetDefault(); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerConsumeIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerConsumeIntegration.cs index c64597d2b..d06a901dd 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerConsumeIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerConsumeIntegration.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; using Elastic.Apm.Profiler.Managed.CallTarget; @@ -15,7 +15,7 @@ using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Confluent.Kafka Consumer.Consume calltarget instrumentation /// @@ -31,7 +31,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public class KafkaConsumerConsumeIntegration - { + { /// /// OnMethodBegin callback /// @@ -40,12 +40,12 @@ public class KafkaConsumerConsumeIntegration /// The maximum period of time the call may block. /// Calltarget state value public static CallTargetState OnMethodBegin(TTarget instance, int millisecondsTimeout) - { - // If we are already in a consumer scope, close it, and start a new one on method exit. + { + // If we are already in a consumer scope, close it, and start a new one on method exit. KafkaIntegration.CloseConsumerTransaction(Agent.Instance); return CallTargetState.GetDefault(); - } - + } + /// /// OnMethodEnd callback /// @@ -69,9 +69,9 @@ CallTargetState state consumeResult = consumeException.ConsumerRecord; if (consumeResult is not null) - { - // creates a transaction and ends it on the next call to any of - // Consumer.Consume(), Consumer.Close() Consumer.Dispose() or Consumer.Unsubscribe() call + { + // creates a transaction and ends it on the next call to any of + // Consumer.Consume(), Consumer.Close() Consumer.Dispose() or Consumer.Unsubscribe() call var transaction = KafkaIntegration.CreateConsumerTransaction( Agent.Instance, consumeResult.Topic, diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerDisposeIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerDisposeIntegration.cs index 333994397..47c91b1fd 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerDisposeIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerDisposeIntegration.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; using Elastic.Apm.Profiler.Managed.CallTarget; using Elastic.Apm.Profiler.Managed.Core; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Confluent.Kafka Consumer.Consume calltarget instrumentation /// @@ -30,7 +30,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public class KafkaConsumerDisposeIntegration - { + { /// /// OnMethodBegin callback /// @@ -38,12 +38,12 @@ public class KafkaConsumerDisposeIntegration /// Instance value, aka `this` of the instrumented method. /// Calltarget state value public static CallTargetState OnMethodBegin(TTarget instance) - { - // If we are already in a consumer scope, close it. + { + // If we are already in a consumer scope, close it. KafkaIntegration.CloseConsumerTransaction(Agent.Instance); return CallTargetState.GetDefault(); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerUnsubscribeIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerUnsubscribeIntegration.cs index 2c1dbd2d8..1f73318a0 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerUnsubscribeIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaConsumerUnsubscribeIntegration.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; using Elastic.Apm.Profiler.Managed.CallTarget; using Elastic.Apm.Profiler.Managed.Core; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Confluent.Kafka Consumer.Consume calltarget instrumentation /// @@ -30,7 +30,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public class KafkaConsumerUnsubscribeIntegration - { + { /// /// OnMethodBegin callback /// @@ -38,12 +38,12 @@ public class KafkaConsumerUnsubscribeIntegration /// Instance value, aka `this` of the instrumented method. /// Calltarget state value public static CallTargetState OnMethodBegin(TTarget instance) - { - // If we are already in a consumer scope, close it. + { + // If we are already in a consumer scope, close it. KafkaIntegration.CloseConsumerTransaction(Agent.Instance); return CallTargetState.GetDefault(); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaHeadersCollection.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaHeadersCollection.cs index 559b1fd54..b2a596833 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaHeadersCollection.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaHeadersCollection.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Linq; @@ -15,33 +15,33 @@ using Elastic.Apm.Logging; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// A collection of headers. /// internal interface IHeadersCollection - { + { /// /// Returns all header values for a specified header stored in the collection. /// /// The specified header to return values for. /// Zero or more header strings. - IEnumerable GetValues(string name); - + IEnumerable GetValues(string name); + /// /// Sets the value of an entry in the collection, replacing any previous values. /// /// The header to add to the collection. /// The content of the header. - void Set(string name, string value); - + void Set(string name, string value); + /// /// Adds the specified header and its value into the collection. /// /// The header to add to the collection. /// The content of the header. - void Add(string name, string value); - + void Add(string name, string value); + /// /// Removes the specified header from the collection. /// @@ -61,8 +61,8 @@ public KafkaHeadersCollection(IHeaders headers, IApmLogger logger) } public IEnumerable GetValues(string name) - { - // This only returns the _last_ bytes. Accessing other values is more expensive and should generally be unnecessary + { + // This only returns the _last_ bytes. Accessing other values is more expensive and should generally be unnecessary if (_headers.TryGetLastBytes(name, out var bytes)) { try diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaIntegration.cs index bfb9c1a8c..6e383a480 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaIntegration.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Linq; using Elastic.Apm.Api; @@ -36,8 +36,8 @@ internal static ISpan CreateProducerSpan(IApmAgent agent, ITopicPartition topicP ISpan span = null; try - { - // no current transaction, don't create a span + { + // no current transaction, don't create a span var currentTransaction = agent.Tracer.CurrentTransaction; if (currentTransaction is null) return span; @@ -139,9 +139,9 @@ IMessage message transaction.SetLabel("partition", partition.ToString()); if (offset is not null) - transaction.SetLabel("offset", offset.ToString()); - - // record only queue topic name and age on context for now. capture body and headers potentially in future + transaction.SetLabel("offset", offset.ToString()); + + // record only queue topic name and age on context for now. capture body and headers potentially in future transaction.Context.Message = new Message { Queue = new Queue { Name = topic } }; if (transaction is Transaction realTransaction && message is not null && message.Timestamp.Type != 0) { @@ -178,8 +178,8 @@ internal static void CloseConsumerTransaction(IApmAgent agent) { agent.Logger.Error()?.LogException(ex, "Error closing Kafka consumer transaction"); } - } - + } + /// /// Try to inject the trace context into the Kafka message headers /// @@ -203,8 +203,8 @@ internal static void CloseConsumerTransaction(IApmAgent agent) adapter.Set(TraceContext.TraceStateHeaderName, distributedTracingData.TraceState.ToTextHeader()); } catch (Exception ex) - { - // don't keep trying if we run into problems + { + // don't keep trying if we run into problems HeadersInjectionEnabled = false; agent.Logger.Warning()?.LogException(ex, "There was a problem injecting headers into the Kafka record. Disabling headers injection"); } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceAsyncIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceAsyncIntegration.cs index ea7c5b39a..3a1ac58d2 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceAsyncIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceAsyncIntegration.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; using System.Threading; @@ -16,7 +16,7 @@ using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Confluent.Kafka Producer.Produce calltarget instrumentation /// @@ -32,7 +32,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public class KafkaProduceAsyncIntegration - { + { /// /// OnMethodBegin callback /// @@ -61,8 +61,8 @@ public class KafkaProduceAsyncIntegration KafkaIntegration.TryInjectHeaders(agent, span, message); return new CallTargetState(span); - } - + } + /// /// OnAsyncMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceSyncDeliveryHandlerIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceSyncDeliveryHandlerIntegration.cs index b6e4031d1..037a2cf9f 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceSyncDeliveryHandlerIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceSyncDeliveryHandlerIntegration.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; using System.Reflection; @@ -18,7 +18,7 @@ using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Confluent.Kafka Producer.TypedDeliveryHandlerShim_Action.HandleDeliveryReport calltarget instrumentation /// @@ -34,7 +34,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public class KafkaProduceSyncDeliveryHandlerIntegration - { + { /// /// OnMethodBegin callback /// @@ -53,29 +53,29 @@ public class KafkaProduceSyncDeliveryHandlerIntegration ) { if (handler is null) - { - // Handled in KafkaProduceSyncIntegration + { + // Handled in KafkaProduceSyncIntegration return CallTargetState.GetDefault(); } try { - var agent = Agent.Instance; - - // The current span should be started in KafkaProduceSyncIntegration.OnMethodBegin - // The OnMethodBegin and OnMethodEnd of this integration happens between KafkaProduceSyncIntegration.OnMethodBegin - // and KafkaProduceSyncIntegration.OnMethodEnd, so the consumer span is active for the duration of this integration - var span = agent.Tracer.CurrentSpan; - // span may be null when the Produce call is to an ignored topic. + var agent = Agent.Instance; + + // The current span should be started in KafkaProduceSyncIntegration.OnMethodBegin + // The OnMethodBegin and OnMethodEnd of this integration happens between KafkaProduceSyncIntegration.OnMethodBegin + // and KafkaProduceSyncIntegration.OnMethodEnd, so the consumer span is active for the duration of this integration + var span = agent.Tracer.CurrentSpan; + // span may be null when the Produce call is to an ignored topic. if (span is null) return CallTargetState.GetDefault(); var newAction = CachedWrapperDelegate.CreateWrapper(handler, span); - Action updateHandlerAction = inst => inst.Handler = newAction; - - // store the call to update the handler variable as state - // so we update it at the _end_ of the constructor + Action updateHandlerAction = inst => inst.Handler = newAction; + + // store the call to update the handler variable as state + // so we update it at the _end_ of the constructor return new CallTargetState(span, updateHandlerAction); } catch (Exception ex) @@ -83,8 +83,8 @@ public class KafkaProduceSyncDeliveryHandlerIntegration Agent.Instance.Logger.Error()?.LogException(ex, "Error creating wrapped delegate for delivery report"); return CallTargetState.GetDefault(); } - } - + } + /// /// OnMethodEnd callback /// @@ -95,8 +95,8 @@ public class KafkaProduceSyncDeliveryHandlerIntegration /// A response value, in an async scenario will be T of Task of T public static CallTargetReturn OnMethodEnd(TTarget instance, Exception exception, CallTargetState state) { - if (state.State is Action updateHandlerAction - && instance.TryDuckCast(out var shim)) + if (state.State is Action updateHandlerAction + && instance.TryDuckCast(out var shim)) { var agent = Agent.Instance; @@ -106,16 +106,16 @@ public static CallTargetReturn OnMethodEnd(TTarget instance, Exception } catch (Exception ex) { - agent.Logger.Error()?.LogException(ex, "There was an error updating the delivery report handler"); - // Not ideal to close the span here immediately, but as we can't trace the result, - // we don't really have a choice + agent.Logger.Error()?.LogException(ex, "There was an error updating the delivery report handler"); + // Not ideal to close the span here immediately, but as we can't trace the result, + // we don't really have a choice state.Segment?.End(); } } return CallTargetReturn.GetDefault(); - } - + } + /// /// Helper method used by to create a delegate /// @@ -130,22 +130,22 @@ public static CallTargetReturn OnMethodEnd(TTarget instance, Exception { var isError = report?.Error is not null && report.Error.IsError; if (isError) - { - // Set the error manually, as we don't have an exception + stack trace here - // Should we create a stack trace manually? + { + // Set the error manually, as we don't have an exception + stack trace here + // Should we create a stack trace manually? var ex = new Exception(report.Error.ToString()); span.CaptureException(ex); } if (report?.Partition is not null) - span.SetLabel("partition", report.Partition.ToString()); - - // Won't have offset if is error + span.SetLabel("partition", report.Partition.ToString()); + + // Won't have offset if is error if (!isError && report?.Offset is not null) span.SetLabel("offset", report.Offset.ToString()); - } - - // call previous delegate + } + + // call previous delegate try { originalHandler(value); @@ -154,8 +154,8 @@ public static CallTargetReturn OnMethodEnd(TTarget instance, Exception { span.End(); } - }; - + }; + /// /// Helper class for creating a that wraps an , /// @@ -165,24 +165,24 @@ internal static class CachedWrapperDelegate private static readonly CreateWrapperDelegate _createWrapper; static CachedWrapperDelegate() - { - // This type makes the following assumption: TActionDelegate = Action ! - - // Get the Action WrapHelper.WrapAction(Action value) methodinfo + { + // This type makes the following assumption: TActionDelegate = Action ! + + // Get the Action WrapHelper.WrapAction(Action value) methodinfo var wrapActionMethod = typeof(KafkaProduceSyncDeliveryHandlerIntegration) - .GetMethod(nameof(WrapAction), BindingFlags.Public | BindingFlags.Static); - - // Create the generic method using the inner generic types of TActionDelegate => TParam - wrapActionMethod = wrapActionMethod.MakeGenericMethod(typeof(TActionDelegate).GetGenericArguments()); - - // With Action WrapHelper.WrapAction(Action value) method info we create a delegate + .GetMethod(nameof(WrapAction), BindingFlags.Public | BindingFlags.Static); + + // Create the generic method using the inner generic types of TActionDelegate => TParam + wrapActionMethod = wrapActionMethod.MakeGenericMethod(typeof(TActionDelegate).GetGenericArguments()); + + // With Action WrapHelper.WrapAction(Action value) method info we create a delegate _createWrapper = (CreateWrapperDelegate)wrapActionMethod.CreateDelegate(typeof(CreateWrapperDelegate)); } private delegate TActionDelegate CreateWrapperDelegate(TActionDelegate value, ISpan span); - public static TActionDelegate CreateWrapper(TActionDelegate value, ISpan span) => - // we call the delegate passing the instance of the previous delegate + public static TActionDelegate CreateWrapper(TActionDelegate value, ISpan span) => + // we call the delegate passing the instance of the previous delegate _createWrapper(value, span); } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceSyncIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceSyncIntegration.cs index 164296036..5e725ed8e 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceSyncIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/KafkaProduceSyncIntegration.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; using Elastic.Apm.Profiler.Managed.CallTarget; @@ -15,7 +15,7 @@ using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Confluent.Kafka Producer.Produce calltarget instrumentation /// @@ -34,7 +34,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public class KafkaProduceSyncIntegration - { + { /// /// OnMethodBegin callback /// @@ -52,10 +52,10 @@ public class KafkaProduceSyncIntegration ) where TMessage : IMessage { - var agent = Agent.Instance; - - // manually doing duck cast here so we have access to the _original_ TopicPartition type - // as a generic parameter, for injecting headers + var agent = Agent.Instance; + + // manually doing duck cast here so we have access to the _original_ TopicPartition type + // as a generic parameter, for injecting headers var span = KafkaIntegration.CreateProducerSpan( agent, topicPartition.DuckCast(), @@ -66,8 +66,8 @@ public class KafkaProduceSyncIntegration KafkaIntegration.TryInjectHeaders(agent, span, message); return new CallTargetState(span); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/Offset.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/Offset.cs index ac88917b4..937dd38a0 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/Offset.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/Offset.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; -using Elastic.Apm.Profiler.Managed.DuckTyping; - -// ReSharper disable SA1310 - +using Elastic.Apm.Profiler.Managed.DuckTyping; + +// ReSharper disable SA1310 + namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Partition for duck-typing /// @@ -26,13 +26,13 @@ public struct Offset private const long RdKafkaOffsetBeginning = -2; private const long RdKafkaOffsetEnd = -1; private const long RdKafkaOffsetStored = -1000; - private const long RdKafkaOffsetInvalid = -1001; - + private const long RdKafkaOffsetInvalid = -1001; + /// /// Gets the long value corresponding to this offset /// - public long Value; - + public long Value; + /// /// Based on the original implementation /// https://github.com/confluentinc/confluent-kafka-dotnet/blob/643c8fdc90f54f4d82d5135ae7e91a995f0efdee/src/Confluent.Kafka/Offset.cs#L274 diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/Partition.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/Partition.cs index 908febfd8..51e9e2080 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/Partition.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/Kafka/Partition.cs @@ -1,18 +1,18 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka -{ +{ /// /// Partition for duck-typing /// @@ -20,18 +20,18 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.Kafka [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public struct Partition - { + { /// /// Gets the int value corresponding to this partition /// - public int Value; - + public int Value; + /// /// Gets whether or not this is one of the special /// partition values. /// - public bool IsSpecial; - + public bool IsSpecial; + /// /// Based on the original implementation /// https://github.com/confluentinc/confluent-kafka-dotnet/blob/master/src/Confluent.Kafka/Partition.cs#L217-L224 diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicDeliverIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicDeliverIntegration.cs index 5ee9d71be..77c591997 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicDeliverIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicDeliverIntegration.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; using System.Linq; @@ -19,7 +19,7 @@ using Elastic.Apm.Profiler.Managed.Core; namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq -{ +{ /// /// RabbitMQ.Client BasicDeliver calltarget instrumentation /// @@ -39,7 +39,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public class BasicDeliverIntegration - { + { /// /// OnMethodBegin callback /// @@ -59,7 +59,7 @@ public class BasicDeliverIntegration bool redelivered, string exchange, string routingKey, TBasicProperties basicProperties, TBody body ) where TBasicProperties : IBasicProperties - where TBody : IBody // ReadOnlyMemory body in 6.0.0 + where TBody : IBody // ReadOnlyMemory body in 6.0.0 { var agent = Agent.Instance; if (agent.Tracer.CurrentTransaction is not null) @@ -75,9 +75,9 @@ public class BasicDeliverIntegration matcher.GetMatcher()); return default; - } - - // try to extract propagated context values from headers + } + + // try to extract propagated context values from headers DistributedTracingData distributedTracingData = null; if (basicProperties?.Headers != null) { @@ -107,8 +107,8 @@ public class BasicDeliverIntegration transaction.SetLabel("message_size", body?.Length ?? 0); return new CallTargetState(transaction); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicGetIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicGetIntegration.cs index 86252dd19..765d1f3b1 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicGetIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicGetIntegration.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.ComponentModel; using Elastic.Apm.Api; @@ -19,7 +19,7 @@ using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq -{ +{ /// /// RabbitMQ.Client BasicGet calltarget instrumentation /// @@ -35,7 +35,7 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public class BasicGetIntegration - { + { /// /// OnMethodBegin callback /// @@ -45,8 +45,8 @@ public class BasicGetIntegration /// The original autoAck argument /// Calltarget state value public static CallTargetState OnMethodBegin(TTarget instance, string queue, bool autoAck) => - new CallTargetState(segment: null, state: queue, startTime: DateTimeOffset.UtcNow); - + new CallTargetState(segment: null, state: queue, startTime: DateTimeOffset.UtcNow); + /// /// OnMethodEnd callback /// @@ -79,10 +79,10 @@ CallTargetState state matcher.GetMatcher()); return new CallTargetReturn(basicGetResult); - } - - // check if there is an actual instance of the duck-typed type. RabbitMQ client can return null when the server - // answers that there are no messages available + } + + // check if there is an actual instance of the duck-typed type. RabbitMQ client can return null when the server + // answers that there are no messages available var instanceNotNull = basicGetResult.Instance != null; if (instanceNotNull) { diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicPublishIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicPublishIntegration.cs index ffe492f2d..2587822aa 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicPublishIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/BasicPublishIntegration.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.ComponentModel; @@ -20,7 +20,7 @@ using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq -{ +{ /// /// RabbitMQ.Client BasicPublish calltarget instrumentation /// @@ -40,8 +40,8 @@ namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq [EditorBrowsable(EditorBrowsableState.Never)] public class BasicPublishIntegration { - private static readonly string[] DeliveryModeStrings = { null, "1", "2" }; - + private static readonly string[] DeliveryModeStrings = { null, "1", "2" }; + /// /// OnMethodBegin callback /// @@ -59,7 +59,7 @@ public class BasicPublishIntegration bool mandatory, TBasicProperties basicProperties, TBody body ) where TBasicProperties : IBasicProperties, IDuckType - where TBody : IBody, IDuckType // Versions < 6.0.0: TBody is byte[] // Versions >= 6.0.0: TBody is ReadOnlyMemory + where TBody : IBody, IDuckType // Versions < 6.0.0: TBody is byte[] // Versions >= 6.0.0: TBody is ReadOnlyMemory { var agent = Agent.Instance; var transaction = agent.Tracer.CurrentTransaction; @@ -97,9 +97,9 @@ public class BasicPublishIntegration var deliveryMode = DeliveryModeStrings[0x3 & basicProperties.DeliveryMode]; if (deliveryMode != null) span.SetLabel("delivery_mode", deliveryMode); - } - - // add distributed tracing headers to the message + } + + // add distributed tracing headers to the message basicProperties.Headers ??= new Dictionary(); var distributedTracingData = span.OutgoingDistributedTracingData; ContextPropagation.HeadersSetter(basicProperties.Headers, TraceContext.TraceParentHeaderName, @@ -109,8 +109,8 @@ public class BasicPublishIntegration } return new CallTargetState(span); - } - + } + /// /// OnMethodEnd callback /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/ContextPropagation.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/ContextPropagation.cs index 93b06f523..0bb5ff3f0 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/ContextPropagation.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/ContextPropagation.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Linq; diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBasicGetResult.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBasicGetResult.cs index fea81cbf1..30a5f6705 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBasicGetResult.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBasicGetResult.cs @@ -1,39 +1,39 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq -{ +{ /// /// BasicGetResult interface for ducktyping /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IBasicGetResult - { + { /// /// Gets the message body of the result /// - IBody Body { get; } - + IBody Body { get; } + /// /// Gets the message properties /// - IBasicProperties BasicProperties { get; } - + IBasicProperties BasicProperties { get; } + /// /// Retrieve the exchange this message was published to. /// - string Exchange { get; } - + string Exchange { get; } + /// /// Retrieve the routing key with which this message was published. /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBasicProperties.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBasicProperties.cs index 96f81bc7a..345113016 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBasicProperties.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBasicProperties.cs @@ -1,31 +1,31 @@ -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Collections.Generic; using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq -{ +{ /// /// BasicProperties interface for ducktyping /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IBasicProperties - { + { /// /// Gets or sets the headers of the message /// /// Message headers - IDictionary Headers { get; set; } - + IDictionary Headers { get; set; } + /// /// Gets the delivery mode of the message /// - byte DeliveryMode { get; } - + byte DeliveryMode { get; } + /// /// Returns true if the DeliveryMode property is present /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBody.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBody.cs index be73d6343..8188202c6 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBody.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/IBody.cs @@ -1,24 +1,24 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.ComponentModel; namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq -{ +{ /// /// Body interface for ducktyping /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public interface IBody - { + { /// /// Gets the length of the message body /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/RabbitMQIntegration.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/RabbitMQIntegration.cs index 40159a16e..a2cf2061b 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/RabbitMQIntegration.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Integrations/RabbitMq/RabbitMQIntegration.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Integrations.RabbitMq { internal static class RabbitMqIntegration { - internal const string Name = "RabbitMQ"; - - // ReSharper disable once InconsistentNaming + internal const string Name = "RabbitMQ"; + + // ReSharper disable once InconsistentNaming internal const string IBasicPropertiesTypeName = "RabbitMQ.Client.IBasicProperties"; internal const string Subtype = "rabbitmq"; diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Logger.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Logger.cs index b73c17492..3674e9aba 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Logger.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Logger.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Diagnostics; @@ -10,8 +10,8 @@ using System.Text; namespace Elastic.Apm.Profiler.Managed -{ - // match the log levels of the profiler logger +{ + // match the log levels of the profiler logger internal enum LogLevel { Trace = 0, @@ -81,16 +81,16 @@ public static void Log(LogLevel level, string message, params object[] args) return; } catch - { - // ignore + { + // ignore } } Console.Error.WriteLine($"[{DateTimeOffset.Now:O}] [{Levels[level]}] {message}", args); } catch - { - // ignore + { + // ignore } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/DelegateMetadata.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/DelegateMetadata.cs index 4ff016342..f18922c9d 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/DelegateMetadata.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/DelegateMetadata.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.Reflection @@ -31,8 +31,8 @@ public static DelegateMetadata Create() Type returnType; if (delegateType.Name.StartsWith("Func`")) - { - // last generic type argument is the return type + { + // last generic type argument is the return type var parameterCount = genericTypeArguments.Length - 1; parameterTypes = new Type[parameterCount]; Array.Copy(genericTypeArguments, parameterTypes, parameterCount); @@ -49,7 +49,10 @@ public static DelegateMetadata Create() return new DelegateMetadata { - Generics = genericTypeArguments, Parameters = parameterTypes, ReturnType = returnType, Type = delegateType + Generics = genericTypeArguments, + Parameters = parameterTypes, + ReturnType = returnType, + Type = delegateType }; } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/DynamicMethodBuilder.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/DynamicMethodBuilder.cs index 7745a9b61..7fe7078ad 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/DynamicMethodBuilder.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/DynamicMethodBuilder.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections; using System.Collections.Concurrent; @@ -16,7 +16,7 @@ using System.Reflection.Emit; namespace Elastic.Apm.Profiler.Managed.Reflection -{ +{ /// /// Helper class to create instances of using . /// @@ -24,8 +24,8 @@ namespace Elastic.Apm.Profiler.Managed.Reflection internal static class DynamicMethodBuilder where TDelegate : Delegate { - private static readonly ConcurrentDictionary Cache = new ConcurrentDictionary(new KeyComparer()); - + private static readonly ConcurrentDictionary Cache = new ConcurrentDictionary(new KeyComparer()); + /// /// Gets a previously cache delegate used to call the specified method, /// or creates and caches a new delegate if not found. @@ -52,8 +52,8 @@ internal static class DynamicMethodBuilder key.MethodName, key.CallOpCode, key.MethodParameterTypes, - key.MethodGenericArguments)); - + key.MethodGenericArguments)); + /// /// Creates a simple using that /// calls a method with the specified name and parameter types. @@ -79,8 +79,8 @@ internal static class DynamicMethodBuilder Type returnType; if (delegateType.Name.StartsWith("Func`")) - { - // last generic type argument is the return type + { + // last generic type argument is the return type var parameterCount = genericTypeArguments.Length - 1; parameterTypes = new Type[parameterCount]; Array.Copy(genericTypeArguments, parameterTypes, parameterCount); @@ -93,29 +93,31 @@ internal static class DynamicMethodBuilder returnType = typeof(void); } else - throw new Exception($"Only Func<> or Action<> are supported in {nameof(CreateMethodCallDelegate)}."); - - // find any method that matches by name and parameter types + throw new Exception($"Only Func<> or Action<> are supported in {nameof(CreateMethodCallDelegate)}."); + + // find any method that matches by name and parameter types var methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) - .Where(m => m.Name == methodName); - - // if methodParameterTypes was specified, check for a method that matches + .Where(m => m.Name == methodName); + + // if methodParameterTypes was specified, check for a method that matches if (methodParameterTypes != null) { methods = methods.Where( m => { var ps = m.GetParameters(); - if (ps.Length != methodParameterTypes.Length) return false; + if (ps.Length != methodParameterTypes.Length) + return false; for (var i = 0; i < ps.Length; i++) { var t1 = ps[i].ParameterType; - var t2 = methodParameterTypes[i]; - - // generics can be tricky to compare for type equality - // so we will just check the namespace and name - if (t1.Namespace != t2.Namespace || t1.Name != t2.Name) return false; + var t2 = methodParameterTypes[i]; + + // generics can be tricky to compare for type equality + // so we will just check the namespace and name + if (t1.Namespace != t2.Namespace || t1.Name != t2.Name) + return false; } return true; @@ -131,13 +133,14 @@ internal static class DynamicMethodBuilder var methodInfo = methods.FirstOrDefault(); if (methodInfo == null) - { - // method not found - // TODO: logging + { + // method not found + // TODO: logging return null; } - if (methodGenericArguments != null) methodInfo = methodInfo.MakeGenericMethod(methodGenericArguments); + if (methodGenericArguments != null) + methodInfo = methodInfo.MakeGenericMethod(methodGenericArguments); Type[] effectiveParameterTypes; @@ -146,17 +149,17 @@ internal static class DynamicMethodBuilder if (methodInfo.IsStatic) effectiveParameterTypes = reflectedParameterTypes.ToArray(); else - { - // for instance methods, insert object's type as first element in array + { + // for instance methods, insert object's type as first element in array effectiveParameterTypes = new[] { type } .Concat(reflectedParameterTypes) .ToArray(); } var dynamicMethod = new DynamicMethod(methodInfo.Name, returnType, parameterTypes, ObjectExtensions.Module, skipVisibility: true); - var il = dynamicMethod.GetILGenerator(); - - // load each argument and cast or unbox as necessary + var il = dynamicMethod.GetILGenerator(); + + // load each argument and cast or unbox as necessary for (ushort argumentIndex = 0; argumentIndex < parameterTypes.Length; argumentIndex++) { var delegateParameterType = parameterTypes[argumentIndex]; @@ -183,18 +186,19 @@ internal static class DynamicMethodBuilder if (underlyingParameterType.IsValueType && delegateParameterType == typeof(object)) il.Emit(OpCodes.Unbox_Any, underlyingParameterType); - else if (underlyingParameterType != delegateParameterType) il.Emit(OpCodes.Castclass, underlyingParameterType); + else if (underlyingParameterType != delegateParameterType) + il.Emit(OpCodes.Castclass, underlyingParameterType); } if (callOpCode == OpCodeValue.Call || methodInfo.IsStatic) - { - // non-virtual call (e.g. static method, or method override calling overriden implementation) + { + // non-virtual call (e.g. static method, or method override calling overriden implementation) il.Emit(OpCodes.Call, methodInfo); } else if (callOpCode == OpCodeValue.Callvirt) - { - // Note: C# compiler uses CALLVIRT for non-virtual - // instance methods to get the cheap null check + { + // Note: C# compiler uses CALLVIRT for non-virtual + // instance methods to get the cheap null check il.Emit(OpCodes.Callvirt, methodInfo); } else @@ -212,7 +216,8 @@ internal static class DynamicMethodBuilder throw new ArgumentException( $"Cannot reliably convert the target method's return type {methodInfo.ReturnType.FullName} (reference type) to the delegate method's return type {returnType.FullName} (value type)"); } - else if (!methodInfo.ReturnType.IsValueType && !returnType.IsValueType && methodInfo.ReturnType != returnType) il.Emit(OpCodes.Castclass, returnType); + else if (!methodInfo.ReturnType.IsValueType && !returnType.IsValueType && methodInfo.ReturnType != returnType) + il.Emit(OpCodes.Castclass, returnType); il.Emit(OpCodes.Ret); return (TDelegate)dynamicMethod.CreateDelegate(delegateType); @@ -244,17 +249,23 @@ private class KeyComparer : IEqualityComparer { public bool Equals(Key x, Key y) { - if (!object.Equals(x.Type, y.Type)) return false; + if (!object.Equals(x.Type, y.Type)) + return false; - if (!object.Equals(x.MethodName, y.MethodName)) return false; + if (!object.Equals(x.MethodName, y.MethodName)) + return false; - if (!object.Equals(x.CallOpCode, y.CallOpCode)) return false; + if (!object.Equals(x.CallOpCode, y.CallOpCode)) + return false; - if (!object.Equals(x.ReturnType, y.ReturnType)) return false; + if (!object.Equals(x.ReturnType, y.ReturnType)) + return false; - if (!ArrayEquals(x.MethodParameterTypes, y.MethodParameterTypes)) return false; + if (!ArrayEquals(x.MethodParameterTypes, y.MethodParameterTypes)) + return false; - if (!ArrayEquals(x.MethodGenericArguments, y.MethodGenericArguments)) return false; + if (!ArrayEquals(x.MethodGenericArguments, y.MethodGenericArguments)) + return false; return true; } @@ -265,22 +276,26 @@ public int GetHashCode(Key obj) { var hash = 17; - if (obj.Type != null) hash = (hash * 23) + obj.Type.GetHashCode(); + if (obj.Type != null) + hash = (hash * 23) + obj.Type.GetHashCode(); - if (obj.MethodName != null) hash = (hash * 23) + obj.MethodName.GetHashCode(); + if (obj.MethodName != null) + hash = (hash * 23) + obj.MethodName.GetHashCode(); hash = (hash * 23) + obj.CallOpCode.GetHashCode(); if (obj.MethodParameterTypes != null) { foreach (var t in obj.MethodParameterTypes) - if (t != null) hash = (hash * 23) + t.GetHashCode(); + if (t != null) + hash = (hash * 23) + t.GetHashCode(); } if (obj.MethodGenericArguments != null) { foreach (var t in obj.MethodGenericArguments) - if (t != null) hash = (hash * 23) + t.GetHashCode(); + if (t != null) + hash = (hash * 23) + t.GetHashCode(); } return hash; @@ -289,9 +304,11 @@ public int GetHashCode(Key obj) private static bool ArrayEquals(T[] array1, T[] array2) { - if (array1 == null && array2 == null) return true; + if (array1 == null && array2 == null) + return true; - if (array1 == null || array2 == null) return false; + if (array1 == null || array2 == null) + return false; return ((IStructuralEquatable)array1).Equals(array2, EqualityComparer.Default); } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/Interception.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/Interception.cs index 4c11a6aff..b93323f25 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/Interception.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/Interception.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Diagnostics; @@ -23,7 +23,8 @@ internal static Type[] ParamsToTypes(params object[] objectsToCheck) { var types = new Type[objectsToCheck.Length]; - for (var i = 0; i < objectsToCheck.Length; i++) types[i] = objectsToCheck[i]?.GetType(); + for (var i = 0; i < objectsToCheck.Length; i++) + types[i] = objectsToCheck[i]?.GetType(); return types; } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/MemberResult.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/MemberResult.cs index 6da553cf9..bf64f65fa 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/MemberResult.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/MemberResult.cs @@ -1,18 +1,18 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.Reflection { internal readonly struct MemberResult - { + { /// /// A static value used to represent a member that was not found. /// @@ -37,7 +37,8 @@ public MemberResult(T value) public MemberResult GetProperty(string propertyName) { - if (!HasValue || Value == null || !Value.TryGetPropertyValue(propertyName, out TResult result)) return MemberResult.NotFound; + if (!HasValue || Value == null || !Value.TryGetPropertyValue(propertyName, out TResult result)) + return MemberResult.NotFound; return new MemberResult(result); } @@ -46,7 +47,8 @@ public MemberResult GetProperty(string propertyName) public MemberResult GetField(string fieldName) { - if (!HasValue || Value == null || !Value.TryGetFieldValue(fieldName, out TResult result)) return MemberResult.NotFound; + if (!HasValue || Value == null || !Value.TryGetFieldValue(fieldName, out TResult result)) + return MemberResult.NotFound; return new MemberResult(result); } @@ -55,7 +57,8 @@ public MemberResult GetField(string fieldName) public MemberResult CallMethod(string methodName, TArg1 arg1) { - if (!HasValue || Value == null || !Value.TryCallMethod(methodName, arg1, out TResult result)) return MemberResult.NotFound; + if (!HasValue || Value == null || !Value.TryCallMethod(methodName, arg1, out TResult result)) + return MemberResult.NotFound; return new MemberResult(result); } @@ -64,7 +67,8 @@ public MemberResult GetField(string fieldName) public override string ToString() { - if (!HasValue || Value == null) return string.Empty; + if (!HasValue || Value == null) + return string.Empty; return Value.ToString(); } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/MethodBuilder.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/MethodBuilder.cs index c60ef7692..2f48d148f 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/MethodBuilder.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/MethodBuilder.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -20,26 +20,26 @@ namespace Elastic.Apm.Profiler.Managed.Reflection { internal class MethodBuilder where TDelegate : Delegate - { + { /// /// Global dictionary for caching reflected delegates /// - private static readonly ConcurrentDictionary Cache = new ConcurrentDictionary(new KeyComparer()); - + private static readonly ConcurrentDictionary Cache = new ConcurrentDictionary(new KeyComparer()); + #pragma warning disable 649 /// /// Feature flag used primarily for forcing testing of the token lookup strategy. /// - // ReSharper disable once StaticMemberInGenericType - private static readonly bool ForceMdTokenLookup; - + // ReSharper disable once StaticMemberInGenericType + private static readonly bool ForceMdTokenLookup; + /// /// Feature flag used primarily for forcing testing of the fallback lookup strategy. /// - // ReSharper disable once StaticMemberInGenericType - private static readonly bool ForceFallbackLookup; + // ReSharper disable once StaticMemberInGenericType + private static readonly bool ForceFallbackLookup; #pragma warning restore 649 - + private readonly Module _resolutionModule; private readonly int _mdToken; private readonly int _originalOpCodeValue; @@ -59,19 +59,19 @@ internal class MethodBuilder private bool _forceMethodDefResolve; static MethodBuilder() - { - // TODO: implement environment variables for these? - // ForceMdTokenLookup = bool.TryParse(EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.Debug.ForceMdTokenLookup), out bool result) - // ? result - // : false; - // ForceFallbackLookup = bool.TryParse(EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.Debug.ForceFallbackLookup), out result) - // ? result && !ForceMdTokenLookup - // : false; + { + // TODO: implement environment variables for these? + // ForceMdTokenLookup = bool.TryParse(EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.Debug.ForceMdTokenLookup), out bool result) + // ? result + // : false; + // ForceFallbackLookup = bool.TryParse(EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.Debug.ForceFallbackLookup), out result) + // ? result && !ForceMdTokenLookup + // : false; } private MethodBuilder(Guid moduleVersionId, int mdToken, int opCode, string methodName) - : this(ModuleLookup.Get(moduleVersionId), mdToken, opCode, methodName) => - // Save the Guid for logging purposes + : this(ModuleLookup.Get(moduleVersionId), mdToken, opCode, methodName) => + // Save the Guid for logging purposes _moduleVersionId = moduleVersionId; private MethodBuilder(Module resolutionModule, int mdToken, int opCode, string methodName) @@ -195,9 +195,9 @@ public TDelegate Build() callingModule: _resolutionModule); return Cache.GetOrAdd(cacheKey, key => - { - // Validate requirements at the last possible moment - // Don't do more than needed before checking the cache + { + // Validate requirements at the last possible moment + // Don't do more than needed before checking the cache key.Builder.ValidateRequirements(); return key.Builder.EmitDelegate(); }); @@ -210,9 +210,9 @@ private TDelegate EmitDelegate() if (_resolutionModule != null) { try - { - // Don't resolve until we build, as it may be an unnecessary lookup because of the cache - // We also may need the generics which were specified + { + // Don't resolve until we build, as it may be an unnecessary lookup because of the cache + // We also may need the generics which were specified if (_forceMethodDefResolve || (_declaringTypeGenerics == null && _methodGenerics == null)) { _methodBase = @@ -243,7 +243,8 @@ private TDelegate EmitDelegate() if (!requiresBestEffortMatching && _methodBase is MethodInfo info) { - if (info.IsGenericMethodDefinition) info = MakeGenericMethod(info); + if (info.IsGenericMethodDefinition) + info = MakeGenericMethod(info); methodInfo = VerifyMethodFromToken(info); } @@ -254,8 +255,8 @@ private TDelegate EmitDelegate() $"Unable to resolve method {_concreteTypeName}.{_methodName} by metadata token: {_mdToken}. Exiting because {nameof(ForceMdTokenLookup)}() is true."); } else if (methodInfo == null || ForceFallbackLookup) - { - // mdToken didn't work out, fallback + { + // mdToken didn't work out, fallback methodInfo = TryFindMethod(); } @@ -266,8 +267,8 @@ private TDelegate EmitDelegate() Type returnType; if (delegateType.Name.StartsWith("Func`")) - { - // last generic type argument is the return type + { + // last generic type argument is the return type var parameterCount = delegateGenericArgs.Length - 1; delegateParameterTypes = new Type[parameterCount]; Array.Copy(delegateGenericArgs, delegateParameterTypes, parameterCount); @@ -282,7 +283,8 @@ private TDelegate EmitDelegate() else throw new Exception($"Only Func<> or Action<> are supported in {nameof(MethodBuilder)}."); - if (methodInfo.IsGenericMethodDefinition) methodInfo = MakeGenericMethod(methodInfo); + if (methodInfo.IsGenericMethodDefinition) + methodInfo = MakeGenericMethod(methodInfo); Type[] effectiveParameterTypes; @@ -292,17 +294,17 @@ private TDelegate EmitDelegate() if (methodInfo.IsStatic) effectiveParameterTypes = reflectedParameterTypes.ToArray(); else - { - // for instance methods, insert object's type as first element in array + { + // for instance methods, insert object's type as first element in array effectiveParameterTypes = new[] { _concreteType } .Concat(reflectedParameterTypes) .ToArray(); } var dynamicMethod = new DynamicMethod(methodInfo.Name, returnType, delegateParameterTypes, ObjectExtensions.Module, skipVisibility: true); - var il = dynamicMethod.GetILGenerator(); - - // load each argument and cast or unbox as necessary + var il = dynamicMethod.GetILGenerator(); + + // load each argument and cast or unbox as necessary for (ushort argumentIndex = 0; argumentIndex < delegateParameterTypes.Length; argumentIndex++) { var delegateParameterType = delegateParameterTypes[argumentIndex]; @@ -329,18 +331,19 @@ private TDelegate EmitDelegate() if (underlyingParameterType.IsValueType && delegateParameterType == typeof(object)) il.Emit(OpCodes.Unbox_Any, underlyingParameterType); - else if (underlyingParameterType != delegateParameterType) il.Emit(OpCodes.Castclass, underlyingParameterType); + else if (underlyingParameterType != delegateParameterType) + il.Emit(OpCodes.Castclass, underlyingParameterType); } if (_opCode == OpCodeValue.Call || methodInfo.IsStatic) - { - // non-virtual call (e.g. static method, or method override calling overriden implementation) + { + // non-virtual call (e.g. static method, or method override calling overriden implementation) il.Emit(OpCodes.Call, methodInfo); } else if (_opCode == OpCodeValue.Callvirt) - { - // Note: C# compiler uses CALLVIRT for non-virtual - // instance methods to get the cheap null check + { + // Note: C# compiler uses CALLVIRT for non-virtual + // instance methods to get the cheap null check il.Emit(OpCodes.Callvirt, methodInfo); } else @@ -358,7 +361,8 @@ private TDelegate EmitDelegate() throw new ArgumentException( $"Cannot reliably convert the target method's return type {methodInfo.ReturnType.FullName} (reference type) to the delegate method's return type {returnType.FullName} (value type)"); } - else if (!methodInfo.ReturnType.IsValueType && !returnType.IsValueType && methodInfo.ReturnType != returnType) il.Emit(OpCodes.Castclass, returnType); + else if (!methodInfo.ReturnType.IsValueType && !returnType.IsValueType && methodInfo.ReturnType != returnType) + il.Emit(OpCodes.Castclass, returnType); il.Emit(OpCodes.Ret); return (TDelegate)dynamicMethod.CreateDelegate(typeof(TDelegate)); @@ -366,14 +370,15 @@ private TDelegate EmitDelegate() private MethodInfo MakeGenericMethod(MethodInfo methodInfo) { - if (_methodGenerics == null || _methodGenerics.Length == 0) throw new ArgumentException($"Must specify {nameof(_methodGenerics)} for a generic method."); + if (_methodGenerics == null || _methodGenerics.Length == 0) + throw new ArgumentException($"Must specify {nameof(_methodGenerics)} for a generic method."); return methodInfo.MakeGenericMethod(_methodGenerics); } private MethodInfo VerifyMethodFromToken(MethodInfo methodInfo) - { - // Verify baselines to ensure this isn't the wrong method somehow + { + // Verify baselines to ensure this isn't the wrong method somehow var detailMessage = $"Unexpected method: {_concreteTypeName}.{_methodName} received for mdToken: {_mdToken} in module: {_resolutionModule?.FullyQualifiedName ?? "NULL"}, {_resolutionModule?.ModuleVersionId ?? _moduleVersionId}"; @@ -407,9 +412,11 @@ private MethodInfo VerifyMethodFromToken(MethodInfo methodInfo) private void ValidateRequirements() { - if (_concreteType == null) throw new ArgumentException($"{nameof(_concreteType)} must be specified."); + if (_concreteType == null) + throw new ArgumentException($"{nameof(_concreteType)} must be specified."); - if (string.IsNullOrWhiteSpace(_methodName)) throw new ArgumentException($"There must be a {nameof(_methodName)} specified to ensure fallback {nameof(TryFindMethod)} is viable."); + if (string.IsNullOrWhiteSpace(_methodName)) + throw new ArgumentException($"There must be a {nameof(_methodName)} specified to ensure fallback {nameof(TryFindMethod)} is viable."); if (_namespaceAndNameFilter != null && _namespaceAndNameFilter.Length != _parameters.Length + 1) { @@ -419,7 +426,8 @@ private void ValidateRequirements() if (_explicitParameterTypes != null) { - if (_explicitParameterTypes.Length != _parameters.Length) throw new ArgumentException($"The {nameof(_explicitParameterTypes)} must match the {_parameters} count."); + if (_explicitParameterTypes.Length != _parameters.Length) + throw new ArgumentException($"The {nameof(_explicitParameterTypes)} must match the {_parameters} count."); for (var i = 0; i < _explicitParameterTypes.Length; i++) { @@ -427,8 +435,8 @@ private void ValidateRequirements() var parameterType = _parameters[i]; if (parameterType == null) - { - // Nothing to check + { + // Nothing to check continue; } @@ -448,9 +456,9 @@ private MethodInfo TryFindMethod() Logger.Log(LogLevel.Warn, $"Using fallback method matching ({logDetail})"); var methods = - _concreteType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); - - // A legacy fallback attempt to match on the concrete type + _concreteType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); + + // A legacy fallback attempt to match on the concrete type methods = methods .Where(mi => mi.Name == _methodName && (_returnType == null || mi.ReturnType == _returnType)) @@ -464,18 +472,20 @@ private MethodInfo TryFindMethod() { var parameters = m.GetParameters(); - if ((parameters.Length + 1) != _namespaceAndNameFilter.Length) return false; + if ((parameters.Length + 1) != _namespaceAndNameFilter.Length) + return false; var typesToCheck = new Type[] { m.ReturnType }.Concat(m.GetParameters().Select(p => p.ParameterType)).ToArray(); for (var i = 0; i < typesToCheck.Length; i++) { if (_namespaceAndNameFilter[i] == ClrTypeNames.Ignore) - { - // Allow for not specifying + { + // Allow for not specifying continue; } - if ($"{typesToCheck[i].Namespace}.{typesToCheck[i].Name}" != _namespaceAndNameFilter[i]) return false; + if ($"{typesToCheck[i].Namespace}.{typesToCheck[i].Name}" != _namespaceAndNameFilter[i]) + return false; } return true; @@ -509,16 +519,18 @@ private MethodInfo TryFindMethod() { Logger.Log(LogLevel.Info, $"Resolved by viable generics ({logDetail})"); return methods[0]; - } - - // Attempt to trim down further + } + + // Attempt to trim down further methods = methods.Where(ParametersAreExact).ToArray(); - if (methods.Length > 1) throw new ArgumentException($"Unable to safely resolve method, found {methods.Length} matches ({logDetail})"); + if (methods.Length > 1) + throw new ArgumentException($"Unable to safely resolve method, found {methods.Length} matches ({logDetail})"); var methodInfo = methods.SingleOrDefault(); - if (methodInfo == null) throw new ArgumentException($"Unable to resolve method, started with {matchesOnNameAndReturn} by name match ({logDetail})"); + if (methodInfo == null) + throw new ArgumentException($"Unable to resolve method, started with {matchesOnNameAndReturn} by name match ({logDetail})"); return methodInfo; } @@ -528,8 +540,8 @@ private bool ParametersAreViable(MethodInfo mi) var parameters = mi.GetParameters(); if (parameters.Length != _parameters.Length) - { - // expected parameters don't match actual count + { + // expected parameters don't match actual count return false; } @@ -542,33 +554,34 @@ private bool ParametersAreViable(MethodInfo mi) var expectedParameterType = GetExpectedParameterTypeByIndex(i); if (expectedParameterType == null) - { - // Skip the rest of this check, as we can't know the type + { + // Skip the rest of this check, as we can't know the type continue; } if (parameterType.IsGenericParameter) - { - // This requires different evaluation + { + // This requires different evaluation if (MeetsGenericArgumentRequirements(parameterType, expectedParameterType)) - { - // Good to go + { + // Good to go continue; - } - - // We didn't meet this generic argument's requirements + } + + // We didn't meet this generic argument's requirements return false; } - if (!parameterType.IsAssignableFrom(expectedParameterType)) return false; + if (!parameterType.IsAssignableFrom(expectedParameterType)) + return false; } return true; } private bool ParametersAreExact(MethodInfo mi) - { - // We can already assume that the counts match by this point + { + // We can already assume that the counts match by this point var parameters = mi.GetParameters(); for (var i = 0; i < parameters.Length; i++) @@ -580,12 +593,13 @@ private bool ParametersAreExact(MethodInfo mi) var actualArgumentType = GetExpectedParameterTypeByIndex(i); if (actualArgumentType == null) - { - // Skip the rest of this check, as we can't know the type + { + // Skip the rest of this check, as we can't know the type continue; } - if (parameterType != actualArgumentType) return false; + if (parameterType != actualArgumentType) + return false; } return true; @@ -597,30 +611,30 @@ private bool ParametersAreExact(MethodInfo mi) : _parameters[i]; private bool GenericsAreViable(MethodInfo mi) - { - // Non-Generic Method - { IsGenericMethod: false, ContainsGenericParameters: false, IsGenericMethodDefinition: false } - // Generic Method Definition - { IsGenericMethod: true, ContainsGenericParameters: true, IsGenericMethodDefinition: true } - // Open Constructed Method - { IsGenericMethod: true, ContainsGenericParameters: true, IsGenericMethodDefinition: false } - // Closed Constructed Method - { IsGenericMethod: true, ContainsGenericParameters: false, IsGenericMethodDefinition: false } - + { + // Non-Generic Method - { IsGenericMethod: false, ContainsGenericParameters: false, IsGenericMethodDefinition: false } + // Generic Method Definition - { IsGenericMethod: true, ContainsGenericParameters: true, IsGenericMethodDefinition: true } + // Open Constructed Method - { IsGenericMethod: true, ContainsGenericParameters: true, IsGenericMethodDefinition: false } + // Closed Constructed Method - { IsGenericMethod: true, ContainsGenericParameters: false, IsGenericMethodDefinition: false } + if (_methodGenerics == null) - { - // We expect no generic arguments for this method + { + // We expect no generic arguments for this method return mi.ContainsGenericParameters == false; } if (!mi.IsGenericMethod) - { - // There is really nothing to compare here - // Make sure we aren't looking for generics where there aren't + { + // There is really nothing to compare here + // Make sure we aren't looking for generics where there aren't return _methodGenerics?.Length == 0; } var genericArgs = mi.GetGenericArguments(); if (genericArgs.Length != _methodGenerics.Length) - { - // Count of arguments mismatch + { + // Count of arguments mismatch return false; } @@ -630,7 +644,8 @@ private bool GenericsAreViable(MethodInfo mi) { var expectedGenericArg = _methodGenerics[actualGenericArg.GenericParameterPosition]; - if (!MeetsGenericArgumentRequirements(actualGenericArg, expectedGenericArg)) return false; + if (!MeetsGenericArgumentRequirements(actualGenericArg, expectedGenericArg)) + return false; } } @@ -642,8 +657,8 @@ private bool MeetsGenericArgumentRequirements(Type actualGenericArg, Type expect var constraints = actualGenericArg.GetGenericParameterConstraints(); if (constraints.Any(constraint => !constraint.IsAssignableFrom(expectedArg))) - { - // We have failed to meet a constraint + { + // We have failed to meet a constraint return false; } @@ -671,22 +686,29 @@ private class KeyComparer : IEqualityComparer { public bool Equals(Key x, Key y) { - if (x.CallingModuleMetadataToken != y.CallingModuleMetadataToken) return false; + if (x.CallingModuleMetadataToken != y.CallingModuleMetadataToken) + return false; var builder1 = x.Builder; var builder2 = y.Builder; - if (builder1._mdToken != builder2._mdToken) return false; + if (builder1._mdToken != builder2._mdToken) + return false; - if (builder1._opCode != builder2._opCode) return false; + if (builder1._opCode != builder2._opCode) + return false; - if (builder1._concreteType != builder2._concreteType) return false; + if (builder1._concreteType != builder2._concreteType) + return false; - if (!ArrayEquals(x.ExplicitParams, y.ExplicitParams)) return false; + if (!ArrayEquals(x.ExplicitParams, y.ExplicitParams)) + return false; - if (!ArrayEquals(builder1._methodGenerics, builder2._methodGenerics)) return false; + if (!ArrayEquals(builder1._methodGenerics, builder2._methodGenerics)) + return false; - if (!ArrayEquals(builder1._declaringTypeGenerics, builder2._declaringTypeGenerics)) return false; + if (!ArrayEquals(builder1._declaringTypeGenerics, builder2._declaringTypeGenerics)) + return false; return true; } @@ -711,25 +733,31 @@ public int GetHashCode(Key obj) private static int GetHashCode(Type[] array) { - if (array == null) return 0; + if (array == null) + return 0; var value = array.Length; - for (var i = 0; i < array.Length; i++) value = unchecked((value * 31) + array[i]?.GetHashCode() ?? 0); + for (var i = 0; i < array.Length; i++) + value = unchecked((value * 31) + array[i]?.GetHashCode() ?? 0); return value; } private static bool ArrayEquals(Type[] array1, Type[] array2) { - if (array1 == null) return array2 == null; + if (array1 == null) + return array2 == null; - if (array2 == null) return false; + if (array2 == null) + return false; - if (array1.Length != array2.Length) return false; + if (array1.Length != array2.Length) + return false; for (var i = 0; i < array1.Length; i++) - if (array1[i] != array2[i]) return false; + if (array1[i] != array2[i]) + return false; return true; } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/ModuleLookup.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/ModuleLookup.cs index 75e09f658..b6f0e3e3e 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/ModuleLookup.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/ModuleLookup.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Concurrent; using System.Reflection; @@ -16,7 +16,7 @@ namespace Elastic.Apm.Profiler.Managed.Reflection { internal static class ModuleLookup - { + { /// /// Some naive upper limit to resolving assemblies that we can use to stop making expensive calls. /// @@ -32,19 +32,21 @@ internal static class ModuleLookup Get(Marshal.PtrToStructure(new IntPtr(moduleVersionPointer))); public static Module Get(Guid moduleVersionId) - { - // First attempt at cached values with no blocking - if (_modules.TryGetValue(moduleVersionId, out var value)) return value; - - // Block if a population event is happening - _populationResetEvent.Wait(); - - // See if the previous population event populated what we need - if (_modules.TryGetValue(moduleVersionId, out value)) return value; + { + // First attempt at cached values with no blocking + if (_modules.TryGetValue(moduleVersionId, out var value)) + return value; + + // Block if a population event is happening + _populationResetEvent.Wait(); + + // See if the previous population event populated what we need + if (_modules.TryGetValue(moduleVersionId, out value)) + return value; if (_failures >= MaxFailures) - { - // For some unforeseeable reason we have failed on a lot of AppDomain lookups + { + // For some unforeseeable reason we have failed on a lot of AppDomain lookups if (!_shortCircuitLogicHasLogged) { Logger.Log(LogLevel.Warn, @@ -52,9 +54,9 @@ public static Module Get(Guid moduleVersionId) } return null; - } - - // Block threads on this event + } + + // Block threads on this event _populationResetEvent.Reset(); try @@ -67,8 +69,8 @@ public static Module Get(Guid moduleVersionId) Logger.Log(LogLevel.Error, ex, "Error when populating modules."); } finally - { - // Continue threads blocked on this event + { + // Continue threads blocked on this event _populationResetEvent.Set(); } @@ -80,8 +82,9 @@ public static Module Get(Guid moduleVersionId) private static void PopulateModules() { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); - foreach (var assembly in assemblies) - foreach (var module in assembly.Modules) _modules.TryAdd(module.ModuleVersionId, module); + foreach (var assembly in assemblies) + foreach (var module in assembly.Modules) + _modules.TryAdd(module.ModuleVersionId, module); } } } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/ObjectExtensions.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/ObjectExtensions.cs index 53e248704..82941ead0 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/ObjectExtensions.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/ObjectExtensions.cs @@ -1,26 +1,26 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Concurrent; using System.Reflection; using System.Reflection.Emit; namespace Elastic.Apm.Profiler.Managed.Reflection -{ +{ /// /// Provides helper methods to access object members by emitting IL dynamically. /// internal static class ObjectExtensions - { - // A new module to be emitted in the current AppDomain which will contain DynamicMethods - // and have same evidence/permissions as this AppDomain + { + // A new module to be emitted in the current AppDomain which will contain DynamicMethods + // and have same evidence/permissions as this AppDomain internal static readonly ModuleBuilder Module; private static readonly ConcurrentDictionary Cache = @@ -30,17 +30,17 @@ internal static class ObjectExtensions new ConcurrentDictionary(); static ObjectExtensions() - { + { #if NETFRAMEWORK - var asm = - AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("Elastic.Apm.Profiler.Managed.DynamicAssembly"), AssemblyBuilderAccess.Run); + var asm = + AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("Elastic.Apm.Profiler.Managed.DynamicAssembly"), AssemblyBuilderAccess.Run); #else var asm = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Elastic.Apm.Profiler.Managed.DynamicAssembly"), AssemblyBuilderAccess.Run); #endif Module = asm.DefineDynamicModule("DynamicModule"); - } - + } + /// /// Tries to call an instance method with the specified name, a single parameter, and a return value. /// @@ -75,8 +75,8 @@ static ObjectExtensions() value = default; return false; - } - + } + /// /// Tries to call an instance method with the specified name, two parameters, and no return value. /// @@ -110,8 +110,8 @@ static ObjectExtensions() } return false; - } - + } + /// /// Tries to call an instance method with the specified name and a return value. /// @@ -157,8 +157,8 @@ public static bool TryCallMethod(this object source, string methodName, public static MemberResult CallVoidMethod(this object source, string methodName, TArg1 arg1, TArg2 arg2) => source.TryCallVoidMethod(methodName, arg1, arg2) ? new MemberResult(null) - : MemberResult.NotFound; - + : MemberResult.NotFound; + /// /// Tries to get the value of an instance property with the specified name. /// @@ -190,7 +190,8 @@ public static bool TryGetPropertyValue(this object source, string prope public static MemberResult GetProperty(this object source, string propertyName) { - if (source == null) return MemberResult.NotFound; + if (source == null) + return MemberResult.NotFound; return source.TryGetPropertyValue(propertyName, out TResult result) ? new MemberResult(result) @@ -198,8 +199,8 @@ public static MemberResult GetProperty(this object source, str } public static MemberResult GetProperty(this object source, string propertyName) => - GetProperty(source, propertyName); - + GetProperty(source, propertyName); + /// /// Tries to get the value of an instance field with the specified name. /// @@ -238,7 +239,8 @@ public static bool TryGetFieldValue(this object source, string fieldNam { var fieldInfo = containerType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - if (fieldInfo == null) return null; + if (fieldInfo == null) + return null; var dynamicMethod = new DynamicMethod($"{containerType.FullName}.{fieldName}", typeof(TResult), new Type[] { typeof(object) }, ObjectExtensions.Module, skipVisibility: true); @@ -255,7 +257,8 @@ public static bool TryGetFieldValue(this object source, string fieldNam if (fieldInfo.FieldType.IsValueType && typeof(TResult) == typeof(object)) il.Emit(OpCodes.Box, fieldInfo.FieldType); - else if (fieldInfo.FieldType != typeof(TResult)) il.Emit(OpCodes.Castclass, typeof(TResult)); + else if (fieldInfo.FieldType != typeof(TResult)) + il.Emit(OpCodes.Castclass, typeof(TResult)); il.Emit(OpCodes.Ret); return (Func)dynamicMethod.CreateDelegate(typeof(Func)); diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/OpCodeValues.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/OpCodeValues.cs index 72a79a69f..9827802b8 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/OpCodeValues.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/OpCodeValues.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Reflection { internal enum OpCodeValue : short - { + { /// - Call = 40, - + Call = 40, + /// Callvirt = 111 } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/PropertyFetcher.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/PropertyFetcher.cs index a8d7a694d..d615407e5 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/PropertyFetcher.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/PropertyFetcher.cs @@ -1,39 +1,39 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Linq.Expressions; using System.Reflection; namespace Elastic.Apm.Profiler.Managed.Reflection -{ - // TODO: Use one defined in Elastic.Apm +{ + // TODO: Use one defined in Elastic.Apm internal class PropertyFetcher { private readonly string _propertyName; private Type _expectedType; - private object _fetchForExpectedType; - + private object _fetchForExpectedType; + /// /// Initializes a new instance of the class. /// /// The name of the property that this instance will fetch. - public PropertyFetcher(string propertyName) => _propertyName = propertyName; - + public PropertyFetcher(string propertyName) => _propertyName = propertyName; + /// /// Gets the value of the property on the specified object. /// /// Type of the result. /// The object that contains the property. /// The value of the property on the specified object. - public T Fetch(object obj) => Fetch(obj, obj.GetType()); - + public T Fetch(object obj) => Fetch(obj, obj.GetType()); + /// /// Gets the value of the property on the specified object. /// @@ -52,8 +52,8 @@ public T Fetch(object obj, Type objType) } return ((PropertyFetch)_fetchForExpectedType).Fetch(obj); - } - + } + /// /// PropertyFetch is a helper class. It takes a PropertyInfo and then knows how /// to efficiently fetch that property from a .NET object (See Fetch method). @@ -67,20 +67,20 @@ private class PropertyFetch private PropertyFetch() => _propertyFetch = _ => default; private PropertyFetch(PropertyInfo propertyInfo) - { - // Generate lambda: arg => (T)((TObject)arg).get_property(); - var param = Expression.Parameter(typeof(object), "arg"); // arg => - var cast = Expression.Convert(param, propertyInfo.DeclaringType); // (TObject)arg - var propertyFetch = Expression.Property(cast, propertyInfo); // get_property() - var castResult = Expression.Convert(propertyFetch, typeof(T)); // (T)result - - // Generate the actual lambda - var lambda = Expression.Lambda(typeof(Func), castResult, param); - - // Compile it for faster access + { + // Generate lambda: arg => (T)((TObject)arg).get_property(); + var param = Expression.Parameter(typeof(object), "arg"); // arg => + var cast = Expression.Convert(param, propertyInfo.DeclaringType); // (TObject)arg + var propertyFetch = Expression.Property(cast, propertyInfo); // get_property() + var castResult = Expression.Convert(propertyFetch, typeof(T)); // (T)result + + // Generate the actual lambda + var lambda = Expression.Lambda(typeof(Func), castResult, param); + + // Compile it for faster access _propertyFetch = (Func)lambda.Compile(); - } - + } + /// /// Create a property fetcher from a .NET Reflection class that /// represents a property of a particular type. @@ -90,14 +90,14 @@ private PropertyFetch(PropertyInfo propertyInfo) public static PropertyFetch FetcherForProperty(PropertyInfo propertyInfo) { if (propertyInfo == null) - { - // returns null on any fetch. + { + // returns null on any fetch. return new PropertyFetch(); } return new PropertyFetch(propertyInfo); - } - + } + /// /// Gets the value of the property on the specified object. /// diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/TypeExtensions.cs b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/TypeExtensions.cs index a8262c941..6ec7e17bd 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/TypeExtensions.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/Reflection/TypeExtensions.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Reflection { public static class TypeExtensions @@ -18,13 +18,15 @@ public static class TypeExtensions string instrumentedTypeName ) { - if (runtimeObject == null) return null; + if (runtimeObject == null) + return null; var currentType = runtimeObject.GetType(); while (currentType != null) { - if (currentType.Name == instrumentedTypeName && currentType.Namespace == instrumentedNamespace) return currentType; + if (currentType.Name == instrumentedTypeName && currentType.Namespace == instrumentedNamespace) + return currentType; currentType = currentType.BaseType; } diff --git a/src/profiler/Elastic.Apm.Profiler.Managed/TracerExtensions.cs b/src/profiler/Elastic.Apm.Profiler.Managed/TracerExtensions.cs index aefa8fae8..6d1efa19b 100644 --- a/src/profiler/Elastic.Apm.Profiler.Managed/TracerExtensions.cs +++ b/src/profiler/Elastic.Apm.Profiler.Managed/TracerExtensions.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Elastic.Apm.Api; namespace Elastic.Apm.Profiler.Managed -{ - // TODO: this should be public in Elastic.Apm somewhere +{ + // TODO: this should be public in Elastic.Apm somewhere internal static class TracerExtensions { public static IExecutionSegment CurrentExecutionSegment(this ITracer tracer) => diff --git a/src/startuphook/Elastic.Apm.StartupHook.Loader/Loader.cs b/src/startuphook/Elastic.Apm.StartupHook.Loader/Loader.cs index d837dd787..b4d60a4f6 100644 --- a/src/startuphook/Elastic.Apm.StartupHook.Loader/Loader.cs +++ b/src/startuphook/Elastic.Apm.StartupHook.Loader/Loader.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.IO; using System.Reflection; @@ -16,12 +16,12 @@ using ElasticApmStartupHook; namespace Elastic.Apm.StartupHook.Loader -{ +{ /// /// Starts the agent /// internal class Loader - { + { /// /// The directory in which the executing assembly is located /// @@ -32,8 +32,8 @@ private static string AssemblyDirectory var location = Assembly.GetExecutingAssembly().Location; return Path.GetDirectoryName(location); } - } - + } + /// /// Initializes and starts the agent /// diff --git a/src/startuphook/ElasticApmAgentStartupHook/StartupHook.cs b/src/startuphook/ElasticApmAgentStartupHook/StartupHook.cs index 20ead433c..8fcf9d4ed 100644 --- a/src/startuphook/ElasticApmAgentStartupHook/StartupHook.cs +++ b/src/startuphook/ElasticApmAgentStartupHook/StartupHook.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Feature.Tests/APMServerAuthenticationWithAPIKeyAndSecretTokenStepDefinitions.cs b/test/Elastic.Apm.Feature.Tests/APMServerAuthenticationWithAPIKeyAndSecretTokenStepDefinitions.cs index dfb2509b3..2c3652673 100644 --- a/test/Elastic.Apm.Feature.Tests/APMServerAuthenticationWithAPIKeyAndSecretTokenStepDefinitions.cs +++ b/test/Elastic.Apm.Feature.Tests/APMServerAuthenticationWithAPIKeyAndSecretTokenStepDefinitions.cs @@ -9,8 +9,8 @@ namespace Elastic.Apm.Feature.Tests { - [Binding] - public class APMServerAuthenticationWithAPIKeyAndSecretTokenStepDefinitions + [Binding] + public class APMServerAuthenticationWithAPIKeyAndSecretTokenStepDefinitions { private readonly ApiKeyFeatureContext _apiKeyFeatureContext; diff --git a/test/Elastic.Apm.Feature.Tests/CloudProviderSteps.cs b/test/Elastic.Apm.Feature.Tests/CloudProviderSteps.cs index 7911139f0..f543e6112 100644 --- a/test/Elastic.Apm.Feature.Tests/CloudProviderSteps.cs +++ b/test/Elastic.Apm.Feature.Tests/CloudProviderSteps.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Net; using System.Net.Http; @@ -94,8 +94,8 @@ public void EnvironmentVariablesSet(Table table) [When("^cloud metadata is collected$")] public void CollectCloudMetadata() - { - // create the agent and capture a transaction to send metadata + { + // create the agent and capture a transaction to send metadata var agent = _scenarioContext.Get(); agent.Tracer.CaptureTransaction("Transaction", "feature", () => { }); diff --git a/test/Elastic.Apm.Feature.Tests/ConfigurationSteps.cs b/test/Elastic.Apm.Feature.Tests/ConfigurationSteps.cs index 0a1936300..0e56b8e62 100644 --- a/test/Elastic.Apm.Feature.Tests/ConfigurationSteps.cs +++ b/test/Elastic.Apm.Feature.Tests/ConfigurationSteps.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using TechTalk.SpecFlow; namespace Elastic.Apm.Feature.Tests diff --git a/test/Elastic.Apm.Feature.Tests/OpenTelemetryBridgeStepDefinitions.cs b/test/Elastic.Apm.Feature.Tests/OpenTelemetryBridgeStepDefinitions.cs index fbb813769..55f2b2461 100644 --- a/test/Elastic.Apm.Feature.Tests/OpenTelemetryBridgeStepDefinitions.cs +++ b/test/Elastic.Apm.Feature.Tests/OpenTelemetryBridgeStepDefinitions.cs @@ -24,8 +24,8 @@ public void GivenAnAgent() var mockPaylodSender = new MockPayloadSender(); _scenarioContext.Add("payloadSender", mockPaylodSender); using (var agent = new ApmAgent(new TestAgentComponents( - configuration: new MockConfiguration(openTelemetryBridgeEnabled: "true"), - apmServerInfo: MockApmServerInfo.Version716, payloadSender: mockPaylodSender))) + configuration: new MockConfiguration(openTelemetryBridgeEnabled: "true"), + apmServerInfo: MockApmServerInfo.Version716, payloadSender: mockPaylodSender))) _scenarioContext.Add("agent", agent); } @@ -257,7 +257,8 @@ public void ThenElasticBridgedSpanOTelAttributesAreCopiedAs_Is() var payloadSender = _scenarioContext.Get("payloadSender"); - foreach (var item in attributes) (payloadSender.FirstSpan as Span).Otel.Attributes[item.Key].Should().Be(item.Value); + foreach (var item in attributes) + (payloadSender.FirstSpan as Span).Otel.Attributes[item.Key].Should().Be(item.Value); } [Then(@"Elastic bridged span destination resource is set to ""([^""]*)""")] diff --git a/test/Elastic.Apm.Feature.Tests/PayloadCollector.cs b/test/Elastic.Apm.Feature.Tests/PayloadCollector.cs index 64ee24c77..0cc02c208 100644 --- a/test/Elastic.Apm.Feature.Tests/PayloadCollector.cs +++ b/test/Elastic.Apm.Feature.Tests/PayloadCollector.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.IO; @@ -44,8 +44,8 @@ private static JObject[] ParseJObjects(string json) } public void Wait() - { - // wait for the wait handle to be signalled + { + // wait for the wait handle to be signalled var timeout = TimeSpan.FromSeconds(30); if (!_waitHandle.WaitOne(timeout)) throw new Exception($"Did not receive payload within {timeout}"); diff --git a/test/Elastic.Apm.Feature.Tests/TestConfiguration.cs b/test/Elastic.Apm.Feature.Tests/TestConfiguration.cs index 33ecc2849..f64ef3ec6 100644 --- a/test/Elastic.Apm.Feature.Tests/TestConfiguration.cs +++ b/test/Elastic.Apm.Feature.Tests/TestConfiguration.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using Elastic.Apm.Config; diff --git a/test/Elastic.Apm.Feature.Tests/UserAgentSteps.cs b/test/Elastic.Apm.Feature.Tests/UserAgentSteps.cs index f2c48a998..b77bf5bf4 100644 --- a/test/Elastic.Apm.Feature.Tests/UserAgentSteps.cs +++ b/test/Elastic.Apm.Feature.Tests/UserAgentSteps.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Linq; using System.Net; using System.Net.Http; @@ -34,9 +34,9 @@ public void ThenTheUserAgentHeaderMatchesRegex(string match) { var regex = new Regex(match); var payloadCollector = _scenarioContext.Get(); - var agent = _scenarioContext.Get(); - - // capture a transaction so that the agent sends a payload + var agent = _scenarioContext.Get(); + + // capture a transaction so that the agent sends a payload agent.Tracer.CaptureTransaction("User agent", "app", () => { }); payloadCollector.Wait(); @@ -149,9 +149,9 @@ public void ThenTheUser_AgentHeaderMatchesRegex(string p0) { var regex = new Regex(p0); var payloadCollector = _scenarioContext.Get(); - var agent = _scenarioContext.Get(); - - // capture a transaction so that the agent sends a payload + var agent = _scenarioContext.Get(); + + // capture a transaction so that the agent sends a payload agent.Tracer.CaptureTransaction("User agent", "app", () => { }); payloadCollector.Wait(); diff --git a/test/Elastic.Apm.Tests.MockApmServer/AssertValidExtensions.cs b/test/Elastic.Apm.Tests.MockApmServer/AssertValidExtensions.cs index 421552b65..53e2b6a78 100644 --- a/test/Elastic.Apm.Tests.MockApmServer/AssertValidExtensions.cs +++ b/test/Elastic.Apm.Tests.MockApmServer/AssertValidExtensions.cs @@ -269,7 +269,8 @@ internal static void AssertValid(this List thisObj) thisObj.Should().NotBeNull(); thisObj.Should().NotBeEmpty(); - foreach (var stackFrame in thisObj) stackFrame.AssertValid(); + foreach (var stackFrame in thisObj) + stackFrame.AssertValid(); } internal static void AssertValid(this CapturedStackFrame thisObj) diff --git a/test/Elastic.Apm.Tests.MockApmServer/Controllers/AgentsConfigController.cs b/test/Elastic.Apm.Tests.MockApmServer/Controllers/AgentsConfigController.cs index ae1c9f6dd..28cc9fc06 100644 --- a/test/Elastic.Apm.Tests.MockApmServer/Controllers/AgentsConfigController.cs +++ b/test/Elastic.Apm.Tests.MockApmServer/Controllers/AgentsConfigController.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -51,7 +51,8 @@ private IActionResult GetImpl() , Request.QueryString, DbgUtils.CurrentThreadDesc); var getAgentsConfig = _mockApmServer.GetAgentsConfig; - if (getAgentsConfig == null) return NotFound("Get-agents-config API is not enabled"); + if (getAgentsConfig == null) + return NotFound("Get-agents-config API is not enabled"); var result = getAgentsConfig(Request, Response); diff --git a/test/Elastic.Apm.Tests.MockApmServer/Controllers/IntakeV2EventsController.cs b/test/Elastic.Apm.Tests.MockApmServer/Controllers/IntakeV2EventsController.cs index c117de1bf..74c371e49 100644 --- a/test/Elastic.Apm.Tests.MockApmServer/Controllers/IntakeV2EventsController.cs +++ b/test/Elastic.Apm.Tests.MockApmServer/Controllers/IntakeV2EventsController.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -10,15 +10,15 @@ using System.Text; using System.Threading.Tasks; using Elastic.Apm.Helpers; +using Elastic.Apm.Libraries.Newtonsoft.Json; +using Elastic.Apm.Libraries.Newtonsoft.Json.Linq; using Elastic.Apm.Logging; -using Elastic.Apm.Tests.Utilities; using Elastic.Apm.Specification; +using Elastic.Apm.Tests.Utilities; using FluentAssertions; using Microsoft.AspNetCore.Mvc; using NJsonSchema; using Xunit.Sdk; -using Elastic.Apm.Libraries.Newtonsoft.Json; -using Elastic.Apm.Libraries.Newtonsoft.Json.Linq; // ReSharper disable UnusedAutoPropertyAccessor.Local @@ -77,7 +77,8 @@ private async Task ParsePayload() } string requestBody; - using (var reader = new StreamReader(Request.Body, Encoding.UTF8)) requestBody = await reader.ReadToEndAsync(); + using (var reader = new StreamReader(Request.Body, Encoding.UTF8)) + requestBody = await reader.ReadToEndAsync(); var numberOfParsedLines = 0; using (var sr = new StringReader(requestBody)) @@ -122,7 +123,8 @@ private async Task ParsePayloadLineAndAddToReceivedData(string line) async Task HandleParsed(string dtoType, TDto dto, ImmutableList accumulatingList, Action action) where TDto : IDto { - if (dto == null) return; + if (dto == null) + return; foundDto.Should().BeFalse($"There should be exactly one object per line: `{line}'"); foundDto = true; diff --git a/test/Elastic.Apm.Tests.MockApmServer/MetricSetDto.cs b/test/Elastic.Apm.Tests.MockApmServer/MetricSetDto.cs index aea7641a8..949138c9a 100644 --- a/test/Elastic.Apm.Tests.MockApmServer/MetricSetDto.cs +++ b/test/Elastic.Apm.Tests.MockApmServer/MetricSetDto.cs @@ -30,7 +30,8 @@ public override string ToString() var resultBuilder = new ToStringBuilder(nameof(MetricSetDto)); resultBuilder.Add("Timestamp", Timestamp); var samplesToStringBuilder = new ToStringBuilder(""); - foreach (var sample in Samples) resultBuilder.Add(sample.Key, sample.Value); + foreach (var sample in Samples) + resultBuilder.Add(sample.Key, sample.Value); resultBuilder.Add("samples", samplesToStringBuilder.ToString()); return resultBuilder.ToString(); } diff --git a/test/Elastic.Apm.Tests.MockApmServer/MockApmServer.cs b/test/Elastic.Apm.Tests.MockApmServer/MockApmServer.cs index 2a6ab2acc..ec09874d6 100644 --- a/test/Elastic.Apm.Tests.MockApmServer/MockApmServer.cs +++ b/test/Elastic.Apm.Tests.MockApmServer/MockApmServer.cs @@ -75,7 +75,8 @@ public MockApmServer(IApmLogger logger, string dbgCurrentTestName, bool useHttps _dbgCurrentTestName = dbgCurrentTestName; _useHttps = useHttps; - if (!useHttps) return; + if (!useHttps) + return; using var ms = new MemoryStream(); using var certStream = typeof(MockApmServer).Assembly.GetManifestResourceStream("Elastic.Apm.Tests.MockApmServer.cert.pfx"); @@ -134,8 +135,10 @@ public int FindAvailablePortToListen() } } - if (currentPort + 1 == PortScanRange.End) currentPort = PortScanRange.Begin; - else ++currentPort; + if (currentPort + 1 == PortScanRange.End) + currentPort = PortScanRange.Begin; + else + ++currentPort; } } @@ -160,12 +163,14 @@ public void Run(int port) internal TResult DoUnderLock(Func func) { - lock (_lock) return func(); + lock (_lock) + return func(); } internal Task DoUnderLock(Func> asyncFunc) { - lock (_lock) return asyncFunc(); + lock (_lock) + return asyncFunc(); } public async Task StopAsync() diff --git a/test/Elastic.Apm.Tests.MockApmServer/Program.cs b/test/Elastic.Apm.Tests.MockApmServer/Program.cs index bc44d8c24..56a90cb23 100644 --- a/test/Elastic.Apm.Tests.MockApmServer/Program.cs +++ b/test/Elastic.Apm.Tests.MockApmServer/Program.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.MockApmServer/Startup.cs b/test/Elastic.Apm.Tests.MockApmServer/Startup.cs index 0aba2d6af..9e1811009 100644 --- a/test/Elastic.Apm.Tests.MockApmServer/Startup.cs +++ b/test/Elastic.Apm.Tests.MockApmServer/Startup.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/AgentTimerForTesting.cs b/test/Elastic.Apm.Tests.Utilities/AgentTimerForTesting.cs index d9c395318..33bdc4732 100644 --- a/test/Elastic.Apm.Tests.Utilities/AgentTimerForTesting.cs +++ b/test/Elastic.Apm.Tests.Utilities/AgentTimerForTesting.cs @@ -73,7 +73,8 @@ public void WaitForTimeToPassAndUntil(TimeSpan timeSpan, Func untilConditi { CatchUpMockTimerToReal(realNow); var leftToWait = targetInstant - realNow; - if (leftToWait <= TimeSpan.Zero) break; + if (leftToWait <= TimeSpan.Zero) + break; _logger.Debug() ?.Log("Waiting for time to pass..." @@ -85,7 +86,8 @@ public void WaitForTimeToPassAndUntil(TimeSpan timeSpan, Func untilConditi realNow = _realAgentTimer.Now; } - if (untilCondition != null) WaitUntil(untilCondition, dbgDesc); + if (untilCondition != null) + WaitUntil(untilCondition, dbgDesc); } private void WaitUntil(Func untilCondition, Func dbgDesc) diff --git a/test/Elastic.Apm.Tests.Utilities/Azure/AzureCredentials.cs b/test/Elastic.Apm.Tests.Utilities/Azure/AzureCredentials.cs index 759c1fcd5..9c0971fa1 100644 --- a/test/Elastic.Apm.Tests.Utilities/Azure/AzureCredentials.cs +++ b/test/Elastic.Apm.Tests.Utilities/Azure/AzureCredentials.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.IO; @@ -11,21 +11,21 @@ using ProcNet; namespace Elastic.Apm.Tests.Utilities.Azure -{ +{ /// /// Unauthenticated Azure credentials /// public class Unauthenticated : AzureCredentials { - } - + } + /// /// Azure credentials authentication with a User account. /// public class AzureUserAccount : AzureCredentials { - } - + } + /// /// Azure credentials authenticated with a Service Principal /// @@ -64,14 +64,14 @@ public override void AddToArguments(StartArguments startArguments) } public abstract class AzureCredentials - { - // ReSharper disable InconsistentNaming + { + // ReSharper disable InconsistentNaming protected const string ARM_CLIENT_ID = nameof(ARM_CLIENT_ID); protected const string ARM_CLIENT_SECRET = nameof(ARM_CLIENT_SECRET); protected const string ARM_TENANT_ID = nameof(ARM_TENANT_ID); - protected const string ARM_SUBSCRIPTION_ID = nameof(ARM_SUBSCRIPTION_ID); - // ReSharper restore InconsistentNaming - + protected const string ARM_SUBSCRIPTION_ID = nameof(ARM_SUBSCRIPTION_ID); + // ReSharper restore InconsistentNaming + private static readonly Lazy _lazyCredentials = new Lazy(LoadCredentials, LazyThreadSafetyMode.ExecutionAndPublication); @@ -101,8 +101,8 @@ private static AzureCredentials LoadCredentials() return LoggedIntoAccountWithAzureCli() ? new AzureUserAccount() : new Unauthenticated(); - } - + } + /// /// Checks that Azure CLI is installed and in the PATH, and is logged into an account /// @@ -110,9 +110,9 @@ private static AzureCredentials LoadCredentials() private static bool LoggedIntoAccountWithAzureCli() { try - { - // run azure CLI using cmd on Windows so that %~dp0 in az.cmd expands to - // the path containing the cmd file. + { + // run azure CLI using cmd on Windows so that %~dp0 in az.cmd expands to + // the path containing the cmd file. var binary = TestEnvironment.IsWindows ? "cmd" : "az"; @@ -128,8 +128,8 @@ private static bool LoggedIntoAccountWithAzureCli() Console.WriteLine(e); return false; } - } - + } + /// /// A set of Azure credentials obtained from environment variables or account authenticated with Azure CLI 2.0. /// If no credentials are found, an unauthenticated credential is returned. diff --git a/test/Elastic.Apm.Tests.Utilities/Azure/AzureCredentialsFactAttribute.cs b/test/Elastic.Apm.Tests.Utilities/Azure/AzureCredentialsFactAttribute.cs index 7a42dfea6..d410ef782 100644 --- a/test/Elastic.Apm.Tests.Utilities/Azure/AzureCredentialsFactAttribute.cs +++ b/test/Elastic.Apm.Tests.Utilities/Azure/AzureCredentialsFactAttribute.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Xunit; namespace Elastic.Apm.Tests.Utilities.Azure -{ +{ /// /// Attribute applied to a test that should be run by the test runner if Azure credentials are available /// diff --git a/test/Elastic.Apm.Tests.Utilities/Azure/AzureResourceException.cs b/test/Elastic.Apm.Tests.Utilities/Azure/AzureResourceException.cs index 6161c464a..c5118c581 100644 --- a/test/Elastic.Apm.Tests.Utilities/Azure/AzureResourceException.cs +++ b/test/Elastic.Apm.Tests.Utilities/Azure/AzureResourceException.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; namespace Elastic.Apm.Tests.Utilities.Azure diff --git a/test/Elastic.Apm.Tests.Utilities/Azure/AzureResources.cs b/test/Elastic.Apm.Tests.Utilities/Azure/AzureResources.cs index f947c2fec..49541180a 100644 --- a/test/Elastic.Apm.Tests.Utilities/Azure/AzureResources.cs +++ b/test/Elastic.Apm.Tests.Utilities/Azure/AzureResources.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; namespace Elastic.Apm.Tests.Utilities.Azure @@ -15,9 +15,9 @@ public static string CreateResourceGroupName(string suffix) { var prefix = Environment.GetEnvironmentVariable("AZURE_RESOURCE_GROUP_PREFIX"); if (string.IsNullOrEmpty(prefix)) - prefix = "dotnet"; - - // check that we'll be under the max length before calculating machine name truncation + prefix = "dotnet"; + + // check that we'll be under the max length before calculating machine name truncation var maxMachineNameLength = ResourceGroupMaxLength - (prefix + "--" + suffix).Length; if (maxMachineNameLength < 0) { diff --git a/test/Elastic.Apm.Tests.Utilities/Data/TransactionMaxSpansTestData.cs b/test/Elastic.Apm.Tests.Utilities/Data/TransactionMaxSpansTestData.cs index 5351de4c2..9141c3940 100644 --- a/test/Elastic.Apm.Tests.Utilities/Data/TransactionMaxSpansTestData.cs +++ b/test/Elastic.Apm.Tests.Utilities/Data/TransactionMaxSpansTestData.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/Docker/DockerFactAttribute.cs b/test/Elastic.Apm.Tests.Utilities/Docker/DockerFactAttribute.cs index d06c810ed..010614605 100644 --- a/test/Elastic.Apm.Tests.Utilities/Docker/DockerFactAttribute.cs +++ b/test/Elastic.Apm.Tests.Utilities/Docker/DockerFactAttribute.cs @@ -1,14 +1,14 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using ProcNet; using Xunit; namespace Elastic.Apm.Tests.Utilities.Docker -{ +{ /// /// Test method that should be run only if docker exists on the host /// diff --git a/test/Elastic.Apm.Tests.Utilities/Docker/DockerTheoryAttribute.cs b/test/Elastic.Apm.Tests.Utilities/Docker/DockerTheoryAttribute.cs index 2038e786b..4b1f95788 100644 --- a/test/Elastic.Apm.Tests.Utilities/Docker/DockerTheoryAttribute.cs +++ b/test/Elastic.Apm.Tests.Utilities/Docker/DockerTheoryAttribute.cs @@ -1,14 +1,14 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using ProcNet; using Xunit; namespace Elastic.Apm.Tests.Utilities.Docker -{ +{ /// /// Test method that should be run only if docker exists on the host /// diff --git a/test/Elastic.Apm.Tests.Utilities/Docker/DockerUtils.cs b/test/Elastic.Apm.Tests.Utilities/Docker/DockerUtils.cs index 7776a0828..684e4d283 100644 --- a/test/Elastic.Apm.Tests.Utilities/Docker/DockerUtils.cs +++ b/test/Elastic.Apm.Tests.Utilities/Docker/DockerUtils.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.IO; using Xunit; diff --git a/test/Elastic.Apm.Tests.Utilities/EnvVarUtils.cs b/test/Elastic.Apm.Tests.Utilities/EnvVarUtils.cs index 18d8617ee..d0b6554a6 100644 --- a/test/Elastic.Apm.Tests.Utilities/EnvVarUtils.cs +++ b/test/Elastic.Apm.Tests.Utilities/EnvVarUtils.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -13,7 +13,8 @@ internal static class EnvVarUtils internal static bool GetBoolValue(string envVarName, bool defaultValue, out string reason) { var value = GetBoolValue(envVarName, out reason); - if (value == null) return defaultValue; + if (value == null) + return defaultValue; return value.Value; } diff --git a/test/Elastic.Apm.Tests.Utilities/FlushingTextWriterToLineWriterAdaptor.cs b/test/Elastic.Apm.Tests.Utilities/FlushingTextWriterToLineWriterAdaptor.cs index 5e1475499..e3ccd817f 100644 --- a/test/Elastic.Apm.Tests.Utilities/FlushingTextWriterToLineWriterAdaptor.cs +++ b/test/Elastic.Apm.Tests.Utilities/FlushingTextWriterToLineWriterAdaptor.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/FlushingTextWriterToLoggerAdaptor.cs b/test/Elastic.Apm.Tests.Utilities/FlushingTextWriterToLoggerAdaptor.cs index d070bb9ac..5576bee36 100644 --- a/test/Elastic.Apm.Tests.Utilities/FlushingTextWriterToLoggerAdaptor.cs +++ b/test/Elastic.Apm.Tests.Utilities/FlushingTextWriterToLoggerAdaptor.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/ILineWriter.cs b/test/Elastic.Apm.Tests.Utilities/ILineWriter.cs index 7e023bd13..8479980e5 100644 --- a/test/Elastic.Apm.Tests.Utilities/ILineWriter.cs +++ b/test/Elastic.Apm.Tests.Utilities/ILineWriter.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/InMemoryBlockingLogger.cs b/test/Elastic.Apm.Tests.Utilities/InMemoryBlockingLogger.cs index b94862f69..8e72616c0 100644 --- a/test/Elastic.Apm.Tests.Utilities/InMemoryBlockingLogger.cs +++ b/test/Elastic.Apm.Tests.Utilities/InMemoryBlockingLogger.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; @@ -40,7 +40,8 @@ public bool IsEnabled(LogLevel level) public void Log(LogLevel level, TState state, Exception e, Func formatter) { - if (!IsEnabled(level)) return; + if (!IsEnabled(level)) + return; _lines.Enqueue(formatter(state, e)); _waitHandle.Set(); diff --git a/test/Elastic.Apm.Tests.Utilities/JsonFileDataAttribute.cs b/test/Elastic.Apm.Tests.Utilities/JsonFileDataAttribute.cs index 1faa9fd3b..3698d3530 100644 --- a/test/Elastic.Apm.Tests.Utilities/JsonFileDataAttribute.cs +++ b/test/Elastic.Apm.Tests.Utilities/JsonFileDataAttribute.cs @@ -35,11 +35,11 @@ public override IEnumerable GetData(MethodInfo testMethod) { case JTokenType.Array: foreach (var t in jToken) - yield return new []{ t.ToObject(_inputDataType) }; + yield return new[] { t.ToObject(_inputDataType) }; break; case JTokenType.Object: foreach (var kvp in (JObject)jToken) - yield return new [] { kvp.Key, kvp.Value.ToObject(_inputDataType) }; + yield return new[] { kvp.Key, kvp.Value.ToObject(_inputDataType) }; break; default: throw new Exception($"Unexpected JSON input: '{jToken}'"); diff --git a/test/Elastic.Apm.Tests.Utilities/JsonUtils.cs b/test/Elastic.Apm.Tests.Utilities/JsonUtils.cs index 1f59cab69..392f0db80 100644 --- a/test/Elastic.Apm.Tests.Utilities/JsonUtils.cs +++ b/test/Elastic.Apm.Tests.Utilities/JsonUtils.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/LineWriterToLoggerAdaptor.cs b/test/Elastic.Apm.Tests.Utilities/LineWriterToLoggerAdaptor.cs index 803c7f1e3..70b4ed49f 100644 --- a/test/Elastic.Apm.Tests.Utilities/LineWriterToLoggerAdaptor.cs +++ b/test/Elastic.Apm.Tests.Utilities/LineWriterToLoggerAdaptor.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/LocalPort.cs b/test/Elastic.Apm.Tests.Utilities/LocalPort.cs index 2885e6005..c0cb014a8 100644 --- a/test/Elastic.Apm.Tests.Utilities/LocalPort.cs +++ b/test/Elastic.Apm.Tests.Utilities/LocalPort.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Net; using System.Net.Sockets; @@ -17,7 +17,7 @@ public static int GetAvailablePort() using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(DefaultLoopbackEndpoint); - return ((IPEndPoint) socket.LocalEndPoint).Port; + return ((IPEndPoint)socket.LocalEndPoint).Port; } } } diff --git a/test/Elastic.Apm.Tests.Utilities/LocalServer.cs b/test/Elastic.Apm.Tests.Utilities/LocalServer.cs index bcb6fab7a..5f3213032 100644 --- a/test/Elastic.Apm.Tests.Utilities/LocalServer.cs +++ b/test/Elastic.Apm.Tests.Utilities/LocalServer.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/LoggingTestBase.cs b/test/Elastic.Apm.Tests.Utilities/LoggingTestBase.cs index b4cff0b41..d0dfc17c7 100644 --- a/test/Elastic.Apm.Tests.Utilities/LoggingTestBase.cs +++ b/test/Elastic.Apm.Tests.Utilities/LoggingTestBase.cs @@ -44,7 +44,8 @@ protected LoggingTestBase(ITestOutputHelper xUnitOutputHelper) if (config.LogToXunitEnabled) { lineWriters.Add(new XunitOutputToLineWriterAdaptor(xUnitOutputHelper, string.Format(config.LogToXunitLinePrefix, testId))); - if (!TestingConfig.IsRunningInIde) writerForStartFinish = lineWriters.ToArray(); + if (!TestingConfig.IsRunningInIde) + writerForStartFinish = lineWriters.ToArray(); } _loggerForStartFinish = new LineWriterToLoggerAdaptor(new SplittingLineWriter(writerForStartFinish), config.LogLevel); diff --git a/test/Elastic.Apm.Tests.Utilities/MockAgentTimer.cs b/test/Elastic.Apm.Tests.Utilities/MockAgentTimer.cs index 1437fa14e..85e700c74 100644 --- a/test/Elastic.Apm.Tests.Utilities/MockAgentTimer.cs +++ b/test/Elastic.Apm.Tests.Utilities/MockAgentTimer.cs @@ -92,7 +92,8 @@ internal void FastForward(TimeSpan timeSpanToFastForward, string dbgGoalDescript while (true) { var delayItem = _delayItems.RemoveEarliestToTrigger(targetNow); - if (!delayItem.HasValue) break; + if (!delayItem.HasValue) + break; Assertion.IfEnabled?.That(delayItem.Value.WhenToTrigger >= Now, "Delay item should not have past trigger time"); Now = delayItem.Value.WhenToTrigger; @@ -171,7 +172,8 @@ CancellationToken cancellationToken ) => DoUnderLock<(AgentTimeInstant _now, long?)>(() => { - if (whenToTrigger <= _now) return (_now, (long?)null); + if (whenToTrigger <= _now) + return (_now, (long?)null); var newItemId = _nextItemId++; @@ -184,7 +186,8 @@ CancellationToken cancellationToken DoUnderLock(() => { var index = _items.FindIndex(delayItem => delayItem.Id == itemId); - if (index == -1) return null; + if (index == -1) + return null; if (Assertion.IsEnabled && index != _items.Count - 1) { @@ -198,14 +201,16 @@ CancellationToken cancellationToken internal DelayItem? RemoveEarliestToTrigger(AgentTimeInstant whenToTrigger) => DoUnderLock(() => { - if (_items.IsEmpty() || _items[0].WhenToTrigger > whenToTrigger) return null; + if (_items.IsEmpty() || _items[0].WhenToTrigger > whenToTrigger) + return null; return RemoveAtReturnCopy(0); }); private void AssertValid() { - if (!Assertion.IsEnabled) return; + if (!Assertion.IsEnabled) + return; Assertion.IfEnabled?.That(Monitor.IsEntered(_lock), "Current thread should hold the lock"); diff --git a/test/Elastic.Apm.Tests.Utilities/MockPayloadSender.cs b/test/Elastic.Apm.Tests.Utilities/MockPayloadSender.cs index 43955ad4e..715ecf737 100644 --- a/test/Elastic.Apm.Tests.Utilities/MockPayloadSender.cs +++ b/test/Elastic.Apm.Tests.Utilities/MockPayloadSender.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -82,11 +82,13 @@ public bool WaitForTransactions(TimeSpan? timeout = null, int? count = null) var signalled = true; if (timeout is null) { - lock (_transactionLock) transactionCount = _transactions.Count; + lock (_transactionLock) + transactionCount = _transactions.Count; while (transactionCount < count && signalled) { signalled = _transactionWaitHandle.WaitOne(DefaultTimeout); - lock (_transactionLock) transactionCount = _transactions.Count; + lock (_transactionLock) + transactionCount = _transactions.Count; } } else @@ -100,7 +102,8 @@ public bool WaitForTransactions(TimeSpan? timeout = null, int? count = null) { var elapsedMilliseconds = Convert.ToInt32(timeout.Value.TotalMilliseconds - stopWatch.ElapsedMilliseconds); signalled = _transactionWaitHandle.WaitOne(elapsedMilliseconds); - lock (_transactionLock) transactionCount = _transactions.Count; + lock (_transactionLock) + transactionCount = _transactions.Count; } } @@ -123,23 +126,27 @@ public bool WaitForSpans(TimeSpan? timeout = null, int? count = null) var signalled = true; if (timeout is null) { - lock (_spanLock) spanCount = _spans.Count; + lock (_spanLock) + spanCount = _spans.Count; while (spanCount < count && signalled) { signalled = _spanWaitHandle.WaitOne(DefaultTimeout); - lock (_spanLock) spanCount = _spans.Count; + lock (_spanLock) + spanCount = _spans.Count; } } else { var stopWatch = Stopwatch.StartNew(); - lock (_spanLock) spanCount = _spans.Count; + lock (_spanLock) + spanCount = _spans.Count; while (spanCount < count && signalled) { var elapsedMilliseconds = Convert.ToInt32(timeout.Value.TotalMilliseconds - stopWatch.ElapsedMilliseconds); signalled = _spanWaitHandle.WaitOne(elapsedMilliseconds); - lock (_spanLock) spanCount = _spans.Count; + lock (_spanLock) + spanCount = _spans.Count; } } @@ -183,7 +190,8 @@ public IReadOnlyList Errors { get { - lock (_errorLock) return CreateImmutableSnapshot(_errors); + lock (_errorLock) + return CreateImmutableSnapshot(_errors); } } @@ -202,7 +210,8 @@ public IReadOnlyList Metrics { get { - lock (_metricsLock) return CreateImmutableSnapshot(_metrics); + lock (_metricsLock) + return CreateImmutableSnapshot(_metrics); } } @@ -210,7 +219,8 @@ public IReadOnlyList Spans { get { - lock (_spanLock) return CreateImmutableSnapshot(_spans); + lock (_spanLock) + return CreateImmutableSnapshot(_spans); } } @@ -218,7 +228,8 @@ public IReadOnlyList Transactions { get { - lock (_transactionLock) return CreateImmutableSnapshot(_transactions); + lock (_transactionLock) + return CreateImmutableSnapshot(_transactions); } } @@ -305,10 +316,14 @@ public void QueueMetrics(IMetricSet metricSet) public void Clear() { - lock (_spanLock) _spans.Clear(); - lock (_errorLock) _errors.Clear(); - lock (_transactionLock) _transactions.Clear(); - lock (_metricsLock) _metrics.Clear(); + lock (_spanLock) + _spans.Clear(); + lock (_errorLock) + _errors.Clear(); + lock (_transactionLock) + _transactions.Clear(); + lock (_metricsLock) + _metrics.Clear(); } private static IReadOnlyList CreateImmutableSnapshot(IEnumerable source) => new List(source); diff --git a/test/Elastic.Apm.Tests.Utilities/MockPayloadSenderWithFilters.cs b/test/Elastic.Apm.Tests.Utilities/MockPayloadSenderWithFilters.cs index e2d31808f..0f20422c5 100644 --- a/test/Elastic.Apm.Tests.Utilities/MockPayloadSenderWithFilters.cs +++ b/test/Elastic.Apm.Tests.Utilities/MockPayloadSenderWithFilters.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -20,7 +20,7 @@ public override void QueueTransaction(ITransaction transaction) { foreach (var filter in _transactionFilters) { - if(filter(transaction) != null) + if (filter(transaction) != null) base.QueueTransaction(transaction); } } diff --git a/test/Elastic.Apm.Tests.Utilities/MultiThreadsTestUtils.cs b/test/Elastic.Apm.Tests.Utilities/MultiThreadsTestUtils.cs index da520ebaf..95e1dbcdf 100644 --- a/test/Elastic.Apm.Tests.Utilities/MultiThreadsTestUtils.cs +++ b/test/Elastic.Apm.Tests.Utilities/MultiThreadsTestUtils.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -26,8 +26,10 @@ internal static TResult[] TestOnThreads(int numberOfThreads, Func new Thread(() => EachThreadDo(i))).ToList(); - foreach (var thread in threads) thread.Start(); - foreach (var thread in threads) thread.Join(); + foreach (var thread in threads) + thread.Start(); + foreach (var thread in threads) + thread.Join(); // ReSharper disable once ImplicitlyCapturedClosure exceptions.ForEachIndexed((ex, threadIndex) => diff --git a/test/Elastic.Apm.Tests.Utilities/RandomTestHelper.cs b/test/Elastic.Apm.Tests.Utilities/RandomTestHelper.cs index a0dfed892..34cf4ce00 100644 --- a/test/Elastic.Apm.Tests.Utilities/RandomTestHelper.cs +++ b/test/Elastic.Apm.Tests.Utilities/RandomTestHelper.cs @@ -33,11 +33,13 @@ private RandomTestHelper(int? seedArg, ITestOutputHelper xUnitOutputHelper, IApm private static (int, string) GetSeed(int? seedArg, ITestOutputHelper xUnitOutputHelper) { - if (seedArg.HasValue) return (seedArg.Value, "passed as argument"); + if (seedArg.HasValue) + return (seedArg.Value, "passed as argument"); var config = TestingConfig.ReadFromFromEnvVars(xUnitOutputHelper); // ReSharper disable once ConvertIfStatementToReturnStatement - if (config.RandomSeed.HasValue) return (config.RandomSeed.Value, "configured via environment variables"); + if (config.RandomSeed.HasValue) + return (config.RandomSeed.Value, "configured via environment variables"); return (new Random().Next(), "randomly generated"); } diff --git a/test/Elastic.Apm.Tests.Utilities/SolutionPaths.cs b/test/Elastic.Apm.Tests.Utilities/SolutionPaths.cs index 0a9fd3f30..0ecf73689 100644 --- a/test/Elastic.Apm.Tests.Utilities/SolutionPaths.cs +++ b/test/Elastic.Apm.Tests.Utilities/SolutionPaths.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.IO; using System.Linq; diff --git a/test/Elastic.Apm.Tests.Utilities/SplittingLineWriter.cs b/test/Elastic.Apm.Tests.Utilities/SplittingLineWriter.cs index 1a24eac32..2fdd9476a 100644 --- a/test/Elastic.Apm.Tests.Utilities/SplittingLineWriter.cs +++ b/test/Elastic.Apm.Tests.Utilities/SplittingLineWriter.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -12,7 +12,8 @@ public class SplittingLineWriter : ILineWriter public void WriteLine(string line) { - foreach (var lineWriter in _lineWriters) lineWriter.WriteLine(line); + foreach (var lineWriter in _lineWriters) + lineWriter.WriteLine(line); } } } diff --git a/test/Elastic.Apm.Tests.Utilities/SystemDiagnosticsTraceLineWriter.cs b/test/Elastic.Apm.Tests.Utilities/SystemDiagnosticsTraceLineWriter.cs index f4384fd35..d0a73e280 100644 --- a/test/Elastic.Apm.Tests.Utilities/SystemDiagnosticsTraceLineWriter.cs +++ b/test/Elastic.Apm.Tests.Utilities/SystemDiagnosticsTraceLineWriter.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/TempFile.cs b/test/Elastic.Apm.Tests.Utilities/TempFile.cs index 8897b9876..afd44f84e 100644 --- a/test/Elastic.Apm.Tests.Utilities/TempFile.cs +++ b/test/Elastic.Apm.Tests.Utilities/TempFile.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.IO; namespace Elastic.Apm.Tests.Utilities -{ +{ /// /// A temporary file that is deleted on dispose. /// @@ -25,8 +25,8 @@ public TempFile(string path) throw new ArgumentNullException(nameof(path)); _path = path; - } - + } + /// /// The path to the temporary file /// @@ -82,8 +82,8 @@ private void Dispose(bool disposing) File.Delete(_path); } catch - { - // best effort. do nothing if it fails + { + // best effort. do nothing if it fails } _path = null; } diff --git a/test/Elastic.Apm.Tests.Utilities/Terraform/TerraformResourceException.cs b/test/Elastic.Apm.Tests.Utilities/Terraform/TerraformResourceException.cs index b6c285c22..b0a2e3940 100644 --- a/test/Elastic.Apm.Tests.Utilities/Terraform/TerraformResourceException.cs +++ b/test/Elastic.Apm.Tests.Utilities/Terraform/TerraformResourceException.cs @@ -1,21 +1,21 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; namespace Elastic.Apm.Tests.Utilities.Terraform -{ +{ /// /// An exception from interacting with terraform resources. /// public class TerraformResourceException : Exception { public TerraformResourceException(string message, int exitCode, List output) - : base(string.Join(Environment.NewLine, new [] { message, $"exit code: {exitCode}", "output:" }.Concat(output))) + : base(string.Join(Environment.NewLine, new[] { message, $"exit code: {exitCode}", "output:" }.Concat(output))) { } diff --git a/test/Elastic.Apm.Tests.Utilities/Terraform/TerraformResources.cs b/test/Elastic.Apm.Tests.Utilities/Terraform/TerraformResources.cs index 30583119a..83a0b2a51 100644 --- a/test/Elastic.Apm.Tests.Utilities/Terraform/TerraformResources.cs +++ b/test/Elastic.Apm.Tests.Utilities/Terraform/TerraformResources.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.IO; @@ -15,7 +15,7 @@ using Xunit.Sdk; namespace Elastic.Apm.Tests.Utilities.Terraform -{ +{ /// /// Interact with Terraform templates to apply and destroy resources /// @@ -88,9 +88,9 @@ private void RunProcess(ObservableProcess process, Action onLine = null public void Init() { using var process = CreateProcess("init", "-no-color"); - RunProcess(process, _messageSink is null ? null: line => _messageSink.OnMessage(new DiagnosticMessage(line.Line))); - } - + RunProcess(process, _messageSink is null ? null : line => _messageSink.OnMessage(new DiagnosticMessage(line.Line))); + } + /// /// Applies the terraform infrastructure with the supplied variables /// @@ -115,9 +115,9 @@ public void Apply(IDictionary variables = null) } using var process = CreateProcess(args.ToArray()); - RunProcess(process, _messageSink is null ? null: line => _messageSink.OnMessage(new DiagnosticMessage(line.Line))); - } - + RunProcess(process, _messageSink is null ? null : line => _messageSink.OnMessage(new DiagnosticMessage(line.Line))); + } + /// /// Reads an output value from applied terraform managed infrastructure. /// @@ -134,8 +134,8 @@ public string Output(string name) }); return output.ToString(); - } - + } + /// /// Destroys the terraform managed infrastructure /// diff --git a/test/Elastic.Apm.Tests.Utilities/TestEnvironment.cs b/test/Elastic.Apm.Tests.Utilities/TestEnvironment.cs index 01c98e219..569780045 100644 --- a/test/Elastic.Apm.Tests.Utilities/TestEnvironment.cs +++ b/test/Elastic.Apm.Tests.Utilities/TestEnvironment.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Runtime.InteropServices; @@ -17,9 +17,9 @@ public static class TestEnvironment public static bool IsWindows { get; } static TestEnvironment() - { - // TODO this IsCi check is no longer valid, once we are green on Github Action - // we should be able to remove all special handling related to this + { + // TODO this IsCi check is no longer valid, once we are green on Github Action + // we should be able to remove all special handling related to this IsCi = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BUILD_ID")); IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); diff --git a/test/Elastic.Apm.Tests.Utilities/TestEnvironmentVariables.cs b/test/Elastic.Apm.Tests.Utilities/TestEnvironmentVariables.cs index b0d824a5d..85cc41df9 100644 --- a/test/Elastic.Apm.Tests.Utilities/TestEnvironmentVariables.cs +++ b/test/Elastic.Apm.Tests.Utilities/TestEnvironmentVariables.cs @@ -1,14 +1,14 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections; using Elastic.Apm.Helpers; namespace Elastic.Apm.Tests.Utilities { - public class TestEnvironmentVariables: IEnvironmentVariables + public class TestEnvironmentVariables : IEnvironmentVariables { private readonly Hashtable _hashTable; diff --git a/test/Elastic.Apm.Tests.Utilities/TestLogger.cs b/test/Elastic.Apm.Tests.Utilities/TestLogger.cs index 590966915..199a9ed6d 100644 --- a/test/Elastic.Apm.Tests.Utilities/TestLogger.cs +++ b/test/Elastic.Apm.Tests.Utilities/TestLogger.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/TestingConfig.cs b/test/Elastic.Apm.Tests.Utilities/TestingConfig.cs index 931546e18..a438cc4c2 100644 --- a/test/Elastic.Apm.Tests.Utilities/TestingConfig.cs +++ b/test/Elastic.Apm.Tests.Utilities/TestingConfig.cs @@ -68,7 +68,8 @@ internal interface IOptionMetadata private static LogLevel ParseLogLevel(string valueAsString) { - if (AbstractConfigurationReader.TryParseLogLevel(valueAsString, out var logLevel)) return logLevel; + if (AbstractConfigurationReader.TryParseLogLevel(valueAsString, out var logLevel)) + return logLevel; throw new FormatException($"`{valueAsString}' is not a valid log level"); } @@ -213,7 +214,8 @@ internal interface ISnapshot private static bool DetectIfRunningInIde() { - if (Environment.GetEnvironmentVariable("VisualStudioVersion") != null) return true; + if (Environment.GetEnvironmentVariable("VisualStudioVersion") != null) + return true; // ReSharper disable once LoopCanBeConvertedToQuery foreach (string envVarName in Environment.GetEnvironmentVariables().Keys) @@ -245,7 +247,8 @@ internal MutableSnapshot(IRawConfigSnapshot rawConfigSnapshot, ITestOutputHelper foreach (var optionMetadata in Options.All) { - if (optionMetadata == Options.LogLevelForTestingConfigParsing) continue; + if (optionMetadata == Options.LogLevelForTestingConfigParsing) + continue; optionMetadata.ParseAndSetProperty(rawConfigSnapshot, this, parsingLogger); } diff --git a/test/Elastic.Apm.Tests.Utilities/ToAllSinksLogger.cs b/test/Elastic.Apm.Tests.Utilities/ToAllSinksLogger.cs index 80e41a8d1..e8b3c6e0f 100644 --- a/test/Elastic.Apm.Tests.Utilities/ToAllSinksLogger.cs +++ b/test/Elastic.Apm.Tests.Utilities/ToAllSinksLogger.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests.Utilities/XUnit/CaptureRestoreActivityIdFormat.cs b/test/Elastic.Apm.Tests.Utilities/XUnit/CaptureRestoreActivityIdFormat.cs index 7f419f938..7b3584ac1 100644 --- a/test/Elastic.Apm.Tests.Utilities/XUnit/CaptureRestoreActivityIdFormat.cs +++ b/test/Elastic.Apm.Tests.Utilities/XUnit/CaptureRestoreActivityIdFormat.cs @@ -1,15 +1,15 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Diagnostics; using System.Reflection; using Xunit.Sdk; namespace Elastic.Apm.Tests.Utilities.XUnit -{ +{ /// /// Captures before the test run and restores it after. /// diff --git a/test/Elastic.Apm.Tests.Utilities/XUnit/XUnitLogger.cs b/test/Elastic.Apm.Tests.Utilities/XUnit/XUnitLogger.cs index 8b5a9b477..914c519ae 100644 --- a/test/Elastic.Apm.Tests.Utilities/XUnit/XUnitLogger.cs +++ b/test/Elastic.Apm.Tests.Utilities/XUnit/XUnitLogger.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using Elastic.Apm.Logging; using Xunit.Abstractions; @@ -26,7 +26,8 @@ public XUnitLogger(LogLevel level, ITestOutputHelper output, string scope = null public void Log(LogLevel level, TState state, Exception e, Func formatter) { - if (!IsEnabled(level)) return; + if (!IsEnabled(level)) + return; var message = formatter(state, e); if (_scope is null) diff --git a/test/Elastic.Apm.Tests.Utilities/XunitOutputToLineWriterAdaptor.cs b/test/Elastic.Apm.Tests.Utilities/XunitOutputToLineWriterAdaptor.cs index c0eccefe8..b48dd8891 100644 --- a/test/Elastic.Apm.Tests.Utilities/XunitOutputToLineWriterAdaptor.cs +++ b/test/Elastic.Apm.Tests.Utilities/XunitOutputToLineWriterAdaptor.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests/ApiTests/ApiTests.cs b/test/Elastic.Apm.Tests/ApiTests/ApiTests.cs index 9f211d5a4..a44e1dbd5 100644 --- a/test/Elastic.Apm.Tests/ApiTests/ApiTests.cs +++ b/test/Elastic.Apm.Tests/ApiTests/ApiTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -628,7 +628,8 @@ public void CallingEndMoreThanOnceIsNoop(bool isSampled) payloadSender.SignalEndSpans(); payloadSender.WaitForSpans(); payloadSender.Spans.Should().HaveCount(expectedSpansCount); - if (isSampled) payloadSender.FirstSpan.Name.Should().Be(TestSpan1); + if (isSampled) + payloadSender.FirstSpan.Name.Should().Be(TestSpan1); span.End(); payloadSender.SignalEndSpans(); @@ -672,7 +673,8 @@ public void CallToEndDoesNotChangeAlreadySetDuration(bool isSampled) payloadSender.SignalEndSpans(); payloadSender.WaitForSpans(); payloadSender.Spans.Should().HaveCount(expectedSpansCount); - if (isSampled) payloadSender.FirstSpan.Duration.Should().Be(123456.789); + if (isSampled) + payloadSender.FirstSpan.Duration.Should().Be(123456.789); payloadSender.Transactions.Should().HaveCount(0); transaction.Duration = 987654.321; diff --git a/test/Elastic.Apm.Tests/ApiTests/ConvenientApiTransactionTests.cs b/test/Elastic.Apm.Tests/ApiTests/ConvenientApiTransactionTests.cs index 684a9ac46..74b5fc923 100644 --- a/test/Elastic.Apm.Tests/ApiTests/ConvenientApiTransactionTests.cs +++ b/test/Elastic.Apm.Tests/ApiTests/ConvenientApiTransactionTests.cs @@ -525,7 +525,9 @@ public void TransactionWithRequestDetailed() new Request("GET", new Url { Full = "https://elastic.co", Raw = "https://elastic.co", HostName = "elastic", Protocol = "HTTP" }) { - HttpVersion = "2.0", Socket = new Socket { RemoteAddress = "127.0.0.1" }, Body = "123" + HttpVersion = "2.0", + Socket = new Socket { RemoteAddress = "127.0.0.1" }, + Body = "123" }; }); }); diff --git a/test/Elastic.Apm.Tests/ApiTests/DistributedTracingDataTests.cs b/test/Elastic.Apm.Tests/ApiTests/DistributedTracingDataTests.cs index bb0c1e6dd..235d1623b 100644 --- a/test/Elastic.Apm.Tests/ApiTests/DistributedTracingDataTests.cs +++ b/test/Elastic.Apm.Tests/ApiTests/DistributedTracingDataTests.cs @@ -73,7 +73,7 @@ public void InvalidDistributedTracingDataTest(string traceId, string parentId, s using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender1))) { var transaction = - agent.Tracer.StartTransaction(TestTransaction, UnitTest, BuildDistributedTracingData(traceId, parentId, traceFlags)); + agent.Tracer.StartTransaction(TestTransaction, UnitTest, BuildDistributedTracingData(traceId, parentId, traceFlags)); transaction.End(); } @@ -89,13 +89,13 @@ public void InvalidDistributedTracingDataTest(string traceId, string parentId, s [Fact] public void DistributedTracingDataWithSimpleAction_Valid() => AssertValidDistributedTracingData(agent => agent.Tracer.CaptureTransaction(TestTransaction, - UnitTest, () => { WaitHelpers.SleepMinimum(); }, BuildDistributedTracingData(ValidTraceId, ValidParentId, ValidTraceFlags))); + UnitTest, () => { WaitHelpers.SleepMinimum(); }, BuildDistributedTracingData(ValidTraceId, ValidParentId, ValidTraceFlags))); [Theory] [ClassData(typeof(InvalidDistributedTracingDataData))] public void DistributedTracingDataWithSimpleAction_Invalid(string traceId, string parentId, string traceFlags) => AssertInvalidDistributedTracingData(agent => agent.Tracer.CaptureTransaction(TestTransaction, - UnitTest, () => { WaitHelpers.SleepMinimum(); }, BuildDistributedTracingData(traceId, parentId, traceFlags)), traceId); + UnitTest, () => { WaitHelpers.SleepMinimum(); }, BuildDistributedTracingData(traceId, parentId, traceFlags)), traceId); /// @@ -106,7 +106,7 @@ public void InvalidDistributedTracingDataTest(string traceId, string parentId, s [Fact] public void DistributedTracingDataWitSimpleActionWithParameter_Valid() => AssertValidDistributedTracingData(agent => agent.Tracer.CaptureTransaction(TestTransaction, - UnitTest, _ => { WaitHelpers.SleepMinimum(); }, BuildDistributedTracingData(ValidTraceId, ValidParentId, ValidTraceFlags))); + UnitTest, _ => { WaitHelpers.SleepMinimum(); }, BuildDistributedTracingData(ValidTraceId, ValidParentId, ValidTraceFlags))); [Theory] [ClassData(typeof(InvalidDistributedTracingDataData))] @@ -261,7 +261,8 @@ private static void AssertValidDistributedTracingData(Action transact { var payloadSender = new MockPayloadSender(); - using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender))) transactionCreator(agent); + using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender))) + transactionCreator(agent); payloadSender.FirstTransaction.TraceId.Should().Be(ValidTraceId); payloadSender.FirstTransaction.ParentId.Should().Be(ValidParentId); @@ -271,7 +272,8 @@ private static void AssertInvalidDistributedTracingData(Action transa { var payloadSender = new MockPayloadSender(); - using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender))) transactionCreator(agent); + using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender))) + transactionCreator(agent); payloadSender.FirstTransaction.TraceId.Should().NotBe(traceId); payloadSender.FirstTransaction.ParentId.Should().BeNullOrWhiteSpace(); @@ -281,7 +283,8 @@ private static async Task AssertValidDistributedTracingData(Func { t.StartSpan("foo", "bar").End(); @@ -29,7 +29,7 @@ public void TestNonExitSpan() public void SimpleManualExitSpanWithNoContext() { var payloadSender = new MockPayloadSender(); - using var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender, configuration: new MockConfiguration(exitSpanMinDuration:"0"))); + using var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender, configuration: new MockConfiguration(exitSpanMinDuration: "0"))); agent.Tracer.CaptureTransaction("foo", "bar", t => { t.StartSpan("foo", "bar", isExitSpan: true).End(); @@ -43,7 +43,7 @@ public void SimpleManualExitSpanWithNoContext() public void SimpleManualExitSpanWithContext() { var payloadSender = new MockPayloadSender(); - using var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender, configuration: new MockConfiguration(exitSpanMinDuration:"0"))); + using var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender, configuration: new MockConfiguration(exitSpanMinDuration: "0"))); agent.Tracer.CaptureTransaction("foo", "bar", t => { var span = t.StartSpan("foo", "bar", isExitSpan: true); diff --git a/test/Elastic.Apm.Tests/ApmServerInfoProviderTests.cs b/test/Elastic.Apm.Tests/ApmServerInfoProviderTests.cs index cec21250e..e4f91cfc4 100644 --- a/test/Elastic.Apm.Tests/ApmServerInfoProviderTests.cs +++ b/test/Elastic.Apm.Tests/ApmServerInfoProviderTests.cs @@ -25,7 +25,7 @@ public async Task FillApmServerInfo_warns_on_missing_server_version() { Content = new StringContent("{}", Encoding.UTF8) })); - var httpClient = BackendCommUtils.BuildHttpClient(logger, configReader, service, nameof(ApmServerInfoProviderTests), httpMessageHandler); + var httpClient = BackendCommUtils.BuildHttpClient(logger, configReader, service, nameof(ApmServerInfoProviderTests), httpMessageHandler); var callbackWasCalled = false; await ApmServerInfoProvider.FillApmServerInfo(null, logger, configReader, httpClient, ((status, _) => diff --git a/test/Elastic.Apm.Tests/BackendCommTests/CentralConfig/CentralConfigFetcherTests.cs b/test/Elastic.Apm.Tests/BackendCommTests/CentralConfig/CentralConfigFetcherTests.cs index 87f8d2d03..abb037297 100644 --- a/test/Elastic.Apm.Tests/BackendCommTests/CentralConfig/CentralConfigFetcherTests.cs +++ b/test/Elastic.Apm.Tests/BackendCommTests/CentralConfig/CentralConfigFetcherTests.cs @@ -121,7 +121,7 @@ public void Should_Sanitize_HttpRequestMessage_In_Log() /// /// logger that has a log level switch but does not implement /// - private class UnswitchableLogger: IApmLogger + private class UnswitchableLogger : IApmLogger { public LogLevelSwitch LogLevelSwitch { get; } diff --git a/test/Elastic.Apm.Tests/BackendCommTests/CentralConfig/CentralConfigResponseParserTests.cs b/test/Elastic.Apm.Tests/BackendCommTests/CentralConfig/CentralConfigResponseParserTests.cs index bf0906faf..044fd9fca 100644 --- a/test/Elastic.Apm.Tests/BackendCommTests/CentralConfig/CentralConfigResponseParserTests.cs +++ b/test/Elastic.Apm.Tests/BackendCommTests/CentralConfig/CentralConfigResponseParserTests.cs @@ -73,7 +73,7 @@ public void ParseHttpResponse_ShouldUse5SecWaitTime_WhenMaxAgeIsLessThan5Sec(int waitInfoS.Interval.Should().Be(TimeSpan.FromSeconds(5)); - if(seconds < 5) + if (seconds < 5) { waitInfoS.Reason.Should().Be("The max-age directive in Cache-Control header in APM Server's response is less than 5 seconds, " + "which is less than expected by the spec - falling back to use 5 seconds wait time."); @@ -94,7 +94,7 @@ public void ParseHttpResponse_ShouldUse5SecWaitTime_WhenMaxAgeIsLessThan5Sec(int [InlineData(-1)] [InlineData(-10)] [InlineData(int.MinValue)] - public void ParseHttpResponse_ShouldUseDefaultWaitTime_WhenMaxAgeIsZeroOrNegative(int seconds) + public void ParseHttpResponse_ShouldUseDefaultWaitTime_WhenMaxAgeIsZeroOrNegative(int seconds) { var response = new HttpResponseMessage { diff --git a/test/Elastic.Apm.Tests/BackendCommTests/PayloadSenderTests.cs b/test/Elastic.Apm.Tests/BackendCommTests/PayloadSenderTests.cs index 3e40f4609..a83e0d1a0 100644 --- a/test/Elastic.Apm.Tests/BackendCommTests/PayloadSenderTests.cs +++ b/test/Elastic.Apm.Tests/BackendCommTests/PayloadSenderTests.cs @@ -21,10 +21,10 @@ using Elastic.Apm.Tests.Utilities; using FluentAssertions; using FluentAssertions.Extensions; +using RichardSzalay.MockHttp; using Xunit; using Xunit.Abstractions; using MockHttpMessageHandler = Elastic.Apm.Tests.Utilities.MockHttpMessageHandler; -using RichardSzalay.MockHttp; namespace Elastic.Apm.Tests.BackendCommTests { diff --git a/test/Elastic.Apm.Tests/BackendCommTests/ServiceActivationTests.cs b/test/Elastic.Apm.Tests/BackendCommTests/ServiceActivationTests.cs index a276694ce..9631ae2e8 100644 --- a/test/Elastic.Apm.Tests/BackendCommTests/ServiceActivationTests.cs +++ b/test/Elastic.Apm.Tests/BackendCommTests/ServiceActivationTests.cs @@ -16,9 +16,9 @@ using Elastic.Apm.Report; using Elastic.Apm.Tests.Utilities; using FluentAssertions; +using RichardSzalay.MockHttp; using Xunit; using Xunit.Abstractions; -using RichardSzalay.MockHttp; namespace Elastic.Apm.Tests.BackendCommTests { diff --git a/test/Elastic.Apm.Tests/BreakdownTests.cs b/test/Elastic.Apm.Tests/BreakdownTests.cs index 14a730075..48c788d3c 100644 --- a/test/Elastic.Apm.Tests/BreakdownTests.cs +++ b/test/Elastic.Apm.Tests/BreakdownTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -569,7 +569,8 @@ public void MoreThan1KBreakDownMetrics() var t = agent.TracerInternal.StartTransactionInternal("test", "request"); var rnd = new Random(); - for (var i = 0; i < 5000; i++) t.CaptureSpan("foo", $"bar-{rnd.Next().ToString()}", () => { }); + for (var i = 0; i < 5000; i++) + t.CaptureSpan("foo", $"bar-{rnd.Next().ToString()}", () => { }); t.End(); } @@ -613,9 +614,12 @@ public void SameTransactionWithMultipleSameSpans() { agent.TracerInternal.CaptureTransaction("test", "request", (t) => { - for (var j = 0; j < 10; j++) t.CaptureSpan("Span1", ApiConstants.TypeDb, () => { }, ApiConstants.SubtypeMssql); - for (var j = 0; j < 10; j++) t.CaptureSpan("Span2", ApiConstants.TypeExternal, () => { }, ApiConstants.SubtypeHttp); - for (var j = 0; j < 10; j++) t.CaptureSpan("Span2", ApiConstants.TypeDb, () => { }, ApiConstants.SubtypeMssql); + for (var j = 0; j < 10; j++) + t.CaptureSpan("Span1", ApiConstants.TypeDb, () => { }, ApiConstants.SubtypeMssql); + for (var j = 0; j < 10; j++) + t.CaptureSpan("Span2", ApiConstants.TypeExternal, () => { }, ApiConstants.SubtypeHttp); + for (var j = 0; j < 10; j++) + t.CaptureSpan("Span2", ApiConstants.TypeDb, () => { }, ApiConstants.SubtypeMssql); }); } } @@ -663,7 +667,8 @@ public void BreakdownLogTest() { var t = agent.TracerInternal.StartTransactionInternal("test", "request"); - for (var i = 0; i < 5000; i++) t.CaptureSpan("foo", $"bar-{rnd.Next().ToString()}", () => { }); + for (var i = 0; i < 5000; i++) + t.CaptureSpan("foo", $"bar-{rnd.Next().ToString()}", () => { }); t.End(); } } @@ -675,7 +680,8 @@ public void BreakdownLogTest() breakdownMetricsProvider.GetSamples().Count().Should().Be(1000); var t2 = agent.TracerInternal.StartTransactionInternal("test", "request"); - for (var i = 0; i < 5000; i++) t2.CaptureSpan("foo", $"bar-{rnd.Next().ToString()}", () => { }); + for (var i = 0; i < 5000; i++) + t2.CaptureSpan("foo", $"bar-{rnd.Next().ToString()}", () => { }); t2.End(); // After BreakdownMetricsProvider.GetSamples() the warning is logged again @@ -691,7 +697,8 @@ public void BreakdownLogTest() private async Task TimeStampTest() { var (agent, breakdownMetricsProvider) = SetUpAgent(); - using (agent) agent.Tracer.CaptureTransaction("test", "test", () => { }); + using (agent) + agent.Tracer.CaptureTransaction("test", "test", () => { }); await Task.Delay(500); var timeStampBeforeReporting = TimeUtils.TimestampNow(); diff --git a/test/Elastic.Apm.Tests/Cloud/AwsCloudMetadataProviderTests.cs b/test/Elastic.Apm.Tests/Cloud/AwsCloudMetadataProviderTests.cs index a7a05bcd3..1322bce92 100644 --- a/test/Elastic.Apm.Tests/Cloud/AwsCloudMetadataProviderTests.cs +++ b/test/Elastic.Apm.Tests/Cloud/AwsCloudMetadataProviderTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; using Elastic.Apm.Cloud; using Elastic.Apm.Tests.Utilities; diff --git a/test/Elastic.Apm.Tests/Cloud/AzureAppServiceMetadataProviderTests.cs b/test/Elastic.Apm.Tests/Cloud/AzureAppServiceMetadataProviderTests.cs index b220723b9..2ae63d769 100644 --- a/test/Elastic.Apm.Tests/Cloud/AzureAppServiceMetadataProviderTests.cs +++ b/test/Elastic.Apm.Tests/Cloud/AzureAppServiceMetadataProviderTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections; using System.Threading.Tasks; using Elastic.Apm.Cloud; diff --git a/test/Elastic.Apm.Tests/Cloud/AzureCloudMetadataProviderTests.cs b/test/Elastic.Apm.Tests/Cloud/AzureCloudMetadataProviderTests.cs index 902345ec2..9fed39e90 100644 --- a/test/Elastic.Apm.Tests/Cloud/AzureCloudMetadataProviderTests.cs +++ b/test/Elastic.Apm.Tests/Cloud/AzureCloudMetadataProviderTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; using Elastic.Apm.Cloud; using Elastic.Apm.Tests.Utilities; diff --git a/test/Elastic.Apm.Tests/Cloud/AzureFunctionsMetadataProviderTests.cs b/test/Elastic.Apm.Tests/Cloud/AzureFunctionsMetadataProviderTests.cs index a05d3ed0e..27c8632c8 100644 --- a/test/Elastic.Apm.Tests/Cloud/AzureFunctionsMetadataProviderTests.cs +++ b/test/Elastic.Apm.Tests/Cloud/AzureFunctionsMetadataProviderTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections; using System.Threading.Tasks; using Elastic.Apm.Cloud; diff --git a/test/Elastic.Apm.Tests/Cloud/CloudMetadataProviderCollectionTests.cs b/test/Elastic.Apm.Tests/Cloud/CloudMetadataProviderCollectionTests.cs index bfd852402..410ffde31 100644 --- a/test/Elastic.Apm.Tests/Cloud/CloudMetadataProviderCollectionTests.cs +++ b/test/Elastic.Apm.Tests/Cloud/CloudMetadataProviderCollectionTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Linq; using Elastic.Apm.Cloud; using Elastic.Apm.Features; diff --git a/test/Elastic.Apm.Tests/Cloud/GcpCloudMetadataProviderTests.cs b/test/Elastic.Apm.Tests/Cloud/GcpCloudMetadataProviderTests.cs index 20247f51a..956f87e84 100644 --- a/test/Elastic.Apm.Tests/Cloud/GcpCloudMetadataProviderTests.cs +++ b/test/Elastic.Apm.Tests/Cloud/GcpCloudMetadataProviderTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; using Elastic.Apm.Cloud; using Elastic.Apm.Tests.Utilities; diff --git a/test/Elastic.Apm.Tests/Config/ConfigTests.cs b/test/Elastic.Apm.Tests/Config/ConfigTests.cs index 129928572..4af2b5877 100644 --- a/test/Elastic.Apm.Tests/Config/ConfigTests.cs +++ b/test/Elastic.Apm.Tests/Config/ConfigTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests/Config/ConfigurationLoggingPreambleTests.cs b/test/Elastic.Apm.Tests/Config/ConfigurationLoggingPreambleTests.cs index 060e2a6a5..a6b142623 100644 --- a/test/Elastic.Apm.Tests/Config/ConfigurationLoggingPreambleTests.cs +++ b/test/Elastic.Apm.Tests/Config/ConfigurationLoggingPreambleTests.cs @@ -22,7 +22,8 @@ public void OptionLoggingInstructions_MustContainAll_IConfigurationReader_Proper { // Extra treatment required? var n = propertyName; - if (n.EndsWith("InMilliseconds")) n = propertyName.Replace("InMilliseconds", string.Empty); + if (n.EndsWith("InMilliseconds")) + n = propertyName.Replace("InMilliseconds", string.Empty); ConfigurationLogger.OptionLoggingInstructions.Should().Contain(i => i.Option.ToString() == n); } } @@ -65,8 +66,8 @@ public void PrintAgentLogPreamble_RedactsSensitiveInformation() { var configuration = new MockConfiguration( secretToken: "42", - serverUrl:$"http://abc:def@localhost:8123", - serverUrls:$"http://ghi:jkl@localhost:8124,http://mno:pqr@localhost:8125" + serverUrl: $"http://abc:def@localhost:8123", + serverUrls: $"http://ghi:jkl@localhost:8124,http://mno:pqr@localhost:8125" ); var logger = new TestLogger(LogLevel.Information); ConfigurationLogger.PrintAgentLogPreamble(logger, configuration); diff --git a/test/Elastic.Apm.Tests/DiagnosticSource/DiagnosticListenerTests.cs b/test/Elastic.Apm.Tests/DiagnosticSource/DiagnosticListenerTests.cs index f4e413c10..f13898be7 100644 --- a/test/Elastic.Apm.Tests/DiagnosticSource/DiagnosticListenerTests.cs +++ b/test/Elastic.Apm.Tests/DiagnosticSource/DiagnosticListenerTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/test/Elastic.Apm.Tests/DistributedTracing/TraceStateTests.cs b/test/Elastic.Apm.Tests/DistributedTracing/TraceStateTests.cs index fd4e787d8..66a1dafcd 100644 --- a/test/Elastic.Apm.Tests/DistributedTracing/TraceStateTests.cs +++ b/test/Elastic.Apm.Tests/DistributedTracing/TraceStateTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Globalization; using Elastic.Apm.DistributedTracing; using FluentAssertions; @@ -24,16 +24,16 @@ public void New_TraceState_Should_Have_Null_Header_And_SampleRate() } [Theory] - [InlineData(0,"one=two", null)] - [InlineData(7,"one=two", "one=two")] - [InlineData(20,"one=two_three=four", "one=two,three=four")] // no overflow - [InlineData(20,"one=two_three=four_five=six_seven=eight", "one=two,three=four")] // overflow after 'four' - [InlineData(20,"one=two,three=four_five=six,seven=eight", "one=two,three=four")] // overflow within 2cnd header - [InlineData(20,"one=two_three=four_five=six,seven=eight", "one=two,three=four")] // overflow within first header - [InlineData(20,"one=two_three=four,X,five=six_seven=eight,nine=ten", "one=two,three=four,X")] // empty entry kept as-is - [InlineData(20,"one=two_three=four,five=six,seven=eight_nine=ten", "one=two,three=four")] // multiple overflow values - [InlineData(18,"one=two_three=four,five=six,seven=eight_nine=ten", "one=two,three=four")] // cutoff on separator - [InlineData(17,"one=two_three=four,five=six,seven=eight_nine=ten,eleven-twelve", "one=two,nine=ten")] // just fits + [InlineData(0, "one=two", null)] + [InlineData(7, "one=two", "one=two")] + [InlineData(20, "one=two_three=four", "one=two,three=four")] // no overflow + [InlineData(20, "one=two_three=four_five=six_seven=eight", "one=two,three=four")] // overflow after 'four' + [InlineData(20, "one=two,three=four_five=six,seven=eight", "one=two,three=four")] // overflow within 2cnd header + [InlineData(20, "one=two_three=four_five=six,seven=eight", "one=two,three=four")] // overflow within first header + [InlineData(20, "one=two_three=four,X,five=six_seven=eight,nine=ten", "one=two,three=four,X")] // empty entry kept as-is + [InlineData(20, "one=two_three=four,five=six,seven=eight_nine=ten", "one=two,three=four")] // multiple overflow values + [InlineData(18, "one=two_three=four,five=six,seven=eight_nine=ten", "one=two,three=four")] // cutoff on separator + [InlineData(17, "one=two_three=four,five=six,seven=eight_nine=ten,eleven-twelve", "one=two,nine=ten")] // just fits public void Header_Should_Be_Limited_By_SizeLimit(int limit, string headers, string expected) { static string ReplaceSpaces(string s) => s?.Replace('X', ' '); @@ -43,9 +43,9 @@ public void Header_Should_Be_Limited_By_SizeLimit(int limit, string headers, str foreach (var h in headers.Split('_')) _traceState.AddTextHeader(ReplaceSpaces(h)); - _traceState.ToTextHeader().Should().Be(ReplaceSpaces(expected)); - - // none of those values should have a sample rate set + _traceState.ToTextHeader().Should().Be(ReplaceSpaces(expected)); + + // none of those values should have a sample rate set _traceState.SampleRate.Should().BeNull(); } diff --git a/test/Elastic.Apm.Tests/DroppedSpansStatsTests.cs b/test/Elastic.Apm.Tests/DroppedSpansStatsTests.cs index 825286029..db0cfa96b 100644 --- a/test/Elastic.Apm.Tests/DroppedSpansStatsTests.cs +++ b/test/Elastic.Apm.Tests/DroppedSpansStatsTests.cs @@ -32,8 +32,8 @@ private static IEnumerable Helper_CreateSpanWithDuration(strin { var payloadSender = new MockPayloadSender(); using (var agent = - new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(exitSpanMinDuration: exitSpanMinDuration), - payloadSender: payloadSender))) + new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(exitSpanMinDuration: exitSpanMinDuration), + payloadSender: payloadSender))) { agent.Tracer.CaptureTransaction("transaction", "type", transaction => { diff --git a/test/Elastic.Apm.Tests/ErrorTests.cs b/test/Elastic.Apm.Tests/ErrorTests.cs index 4e1f83918..47040ca00 100644 --- a/test/Elastic.Apm.Tests/ErrorTests.cs +++ b/test/Elastic.Apm.Tests/ErrorTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -32,7 +32,8 @@ public void ChangeTransactionContextAfterError() { t.Context.Request = new Request("GET", new Url { Full = "http://localhost", Protocol = "http", Search = "abc" }) { - Body = "abc", Headers = new Dictionary { { "header1", "headerValue" } } + Body = "abc", + Headers = new Dictionary { { "header1", "headerValue" } } }; t.Context.Response = new Response { StatusCode = 404, Finished = false }; @@ -180,7 +181,7 @@ public void ErrorContextSanitizerFilterDoesNotThrowWhenTransactionNotSampled() var config = new MockConfiguration(transactionSampleRate: "0", serverUrl: localServer.Uri, flushInterval: "0"); var logger = new InMemoryBlockingLogger(LogLevel.Warning); var payloadSender = new PayloadSenderV2(logger, config, - Service.GetDefaultService(config, logger), new Api.System(),MockApmServerInfo.Version710); + Service.GetDefaultService(config, logger), new Api.System(), MockApmServerInfo.Version710); using var agent = new ApmAgent(new AgentComponents(payloadSender: payloadSender, configurationReader: config)); agent.Tracer.CaptureTransaction("Test", "Test", t => diff --git a/test/Elastic.Apm.Tests/ExitSpanMinDurationTests.cs b/test/Elastic.Apm.Tests/ExitSpanMinDurationTests.cs index cd0523967..7753315e5 100644 --- a/test/Elastic.Apm.Tests/ExitSpanMinDurationTests.cs +++ b/test/Elastic.Apm.Tests/ExitSpanMinDurationTests.cs @@ -21,9 +21,9 @@ public void FastExitSpanTest() configuration: new MockConfiguration(exitSpanMinDuration: "100ms"))); agent.Tracer.CaptureTransaction("foo", "bar", t => { - t.CaptureSpan("span1", "test", () => Thread.Sleep(150), isExitSpan:true); - t.CaptureSpan("span2", "test", () => { }, isExitSpan:true); - t.CaptureSpan("span3", "test", () => Thread.Sleep(150), isExitSpan:true); + t.CaptureSpan("span1", "test", () => Thread.Sleep(150), isExitSpan: true); + t.CaptureSpan("span2", "test", () => { }, isExitSpan: true); + t.CaptureSpan("span3", "test", () => Thread.Sleep(150), isExitSpan: true); //Fast, but not exit span t.CaptureSpan("span4", "test", () => { }); diff --git a/test/Elastic.Apm.Tests/HelpersTests/AgentSpinLockTests.cs b/test/Elastic.Apm.Tests/HelpersTests/AgentSpinLockTests.cs index d74cac944..99f9af7fa 100644 --- a/test/Elastic.Apm.Tests/HelpersTests/AgentSpinLockTests.cs +++ b/test/Elastic.Apm.Tests/HelpersTests/AgentSpinLockTests.cs @@ -121,13 +121,15 @@ internal void multiple_threads(ISpinLockForTest spinLock) { using (var acq = spinLock.TryAcquireWithDisposable()) { - if (!acq.IsAcquired) continue; + if (!acq.IsAcquired) + continue; ++mutexProtectedVar; } ++numberOfIncrements; - if (numberOfIncrements == expectedNumberOfIncrementsPerThread) return numberOfIncrements; + if (numberOfIncrements == expectedNumberOfIncrementsPerThread) + return numberOfIncrements; } }); @@ -150,7 +152,8 @@ internal AcquisitionForTest(ISpinLockForTest spinLockForTest, bool isAcquired) public void Dispose() { - if (IsAcquired) _spinLockForTest.Release(); + if (IsAcquired) + _spinLockForTest.Release(); } } @@ -173,7 +176,8 @@ internal class ThreadUnsafeSpinLockForTest : ISpinLockForTest public bool TryAcquire() { - if (_isLockHeld) return false; + if (_isLockHeld) + return false; // Force the worst case scenario giving other thread more chance to change _isLockHeld to true // while the current thread will still think that _isLockHeld is false after resuming from Thread.Yield() @@ -185,7 +189,8 @@ public bool TryAcquire() public void Release() { - if (_releaseOnNotAcquiredThrows && !_isLockHeld) throw new InvalidOperationException("Attempt to release lock that is not acquired"); + if (_releaseOnNotAcquiredThrows && !_isLockHeld) + throw new InvalidOperationException("Attempt to release lock that is not acquired"); _isLockHeld = false; } diff --git a/test/Elastic.Apm.Tests/HelpersTests/AgentTimeInstantTests.cs b/test/Elastic.Apm.Tests/HelpersTests/AgentTimeInstantTests.cs index 66e44e11d..0c6120d93 100644 --- a/test/Elastic.Apm.Tests/HelpersTests/AgentTimeInstantTests.cs +++ b/test/Elastic.Apm.Tests/HelpersTests/AgentTimeInstantTests.cs @@ -37,7 +37,8 @@ public static IEnumerable AgentTimeInstantSourceVariantsToTest() 1.Days() + 2.Hours() + 3.Minutes() + 4.Seconds() + 5.Milliseconds() }; - foreach (var timeSpan in longTimeSpans) yield return new[] { (object)new MockAgentTimer(), timeSpan }; + foreach (var timeSpan in longTimeSpans) + yield return new[] { (object)new MockAgentTimer(), timeSpan }; } public static IEnumerable IncompatibleAgentTimeInstantSources() @@ -161,7 +162,8 @@ internal void operations_on_Instants_from_different_agentTimers_throw(IAgentTime .WithMessage("*illegal to perform operation op_LessThanOrEqual *"); // ReSharper disable once UnusedParameter.Local - void DummyNoopFunc(T _) { } + void DummyNoopFunc(T _) + { } } } } diff --git a/test/Elastic.Apm.Tests/HelpersTests/AgentTimerTests.cs b/test/Elastic.Apm.Tests/HelpersTests/AgentTimerTests.cs index ed024d3bc..2c45cd14c 100644 --- a/test/Elastic.Apm.Tests/HelpersTests/AgentTimerTests.cs +++ b/test/Elastic.Apm.Tests/HelpersTests/AgentTimerTests.cs @@ -220,7 +220,7 @@ private static void WaitForTaskCancelled(Task task) try { if (!task.IsCanceled) - Task.WaitAll(new [] { task }); + Task.WaitAll(new[] { task }); } catch { @@ -321,7 +321,8 @@ public void VerifyAwaitCompletedSuccessfully(Task awaitOrTimeoutTask, Task delay { awaitOrTimeoutTask.IsCompletedSuccessfully().Should().BeTrue(); - if (!_isVoid) ((Task)awaitOrTimeoutTask).Result.Should().Be(_resultValue); + if (!_isVoid) + ((Task)awaitOrTimeoutTask).Result.Should().Be(_resultValue); _taskToAwaitTcs.Task.IsCompletedSuccessfully().Should().BeTrue(); _taskToAwaitTcs.Task.Result.Should().Be(_resultValue); diff --git a/test/Elastic.Apm.Tests/HelpersTests/DbConnectionStringParserTests.cs b/test/Elastic.Apm.Tests/HelpersTests/DbConnectionStringParserTests.cs index a50435b40..6bd89e9d5 100644 --- a/test/Elastic.Apm.Tests/HelpersTests/DbConnectionStringParserTests.cs +++ b/test/Elastic.Apm.Tests/HelpersTests/DbConnectionStringParserTests.cs @@ -217,11 +217,11 @@ public void nested_value(string dbgDescription, string connectionString, string => TestImpl(LoggerBase, dbgDescription, connectionString, expectedHost, expectedPort); [Theory] - [InlineData(DbConnectionStringParser.MaxNestingDepth/2, true)] - [InlineData(DbConnectionStringParser.MaxNestingDepth-1, true)] + [InlineData(DbConnectionStringParser.MaxNestingDepth / 2, true)] + [InlineData(DbConnectionStringParser.MaxNestingDepth - 1, true)] [InlineData(DbConnectionStringParser.MaxNestingDepth, true)] - [InlineData(DbConnectionStringParser.MaxNestingDepth+1, false)] - [InlineData(DbConnectionStringParser.MaxNestingDepth*2, false)] + [InlineData(DbConnectionStringParser.MaxNestingDepth + 1, false)] + [InlineData(DbConnectionStringParser.MaxNestingDepth * 2, false)] public void nested_value_max_depth(int nestingDepth, bool isValid) { // @"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=172.21.25.186)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCLCDB)));User Id=SAJDDL; Direct=True;" @@ -248,9 +248,11 @@ string BuildString(int outerNestingDepth) string BuildNestedPart(int outerNestingDepth, string innerPart, char nestingKey) { var strBuilder = new StringBuilder(nestingDepth * 6); - for (var i = 0; i < outerNestingDepth; ++i) strBuilder.Append($"({nestingKey}{i+1}="); + for (var i = 0; i < outerNestingDepth; ++i) + strBuilder.Append($"({nestingKey}{i + 1}="); strBuilder.Append(innerPart); - for (var i = 0; i < outerNestingDepth; ++i) strBuilder.Append(')'); + for (var i = 0; i < outerNestingDepth; ++i) + strBuilder.Append(')'); return strBuilder.ToString(); } } diff --git a/test/Elastic.Apm.Tests/HelpersTests/DisposableHelperTests.cs b/test/Elastic.Apm.Tests/HelpersTests/DisposableHelperTests.cs index 25172a240..3b5f9e870 100644 --- a/test/Elastic.Apm.Tests/HelpersTests/DisposableHelperTests.cs +++ b/test/Elastic.Apm.Tests/HelpersTests/DisposableHelperTests.cs @@ -52,7 +52,8 @@ void DisposeAction() internal void calling_Dispose_again_while_previous_call_is_still_in_progress() { var mockLogger = new TestLogger(LogLevel.Trace); - using (new DummyClassReenteringDispose(mockLogger)) { } + using (new DummyClassReenteringDispose(mockLogger)) + { } mockLogger.Lines.Where(line => line.Contains("Critical") && line.Contains(string.Format(DisposableHelper.AnotherCallStillInProgressMsg, nameof(DummyClassReenteringDispose)))) .Should() diff --git a/test/Elastic.Apm.Tests/HelpersTests/TimeExtensionsTests.cs b/test/Elastic.Apm.Tests/HelpersTests/TimeExtensionsTests.cs index 1ae7bc811..25e38f687 100644 --- a/test/Elastic.Apm.Tests/HelpersTests/TimeExtensionsTests.cs +++ b/test/Elastic.Apm.Tests/HelpersTests/TimeExtensionsTests.cs @@ -139,7 +139,8 @@ public static IEnumerable GenTruncateToSecondsVariants() { yield return (timeSpan, expectedTruncatedTimeSpan); - if (timeSpan != TimeSpan.Zero) yield return (-timeSpan, -expectedTruncatedTimeSpan); + if (timeSpan != TimeSpan.Zero) + yield return (-timeSpan, -expectedTruncatedTimeSpan); } } @@ -200,7 +201,8 @@ public static IEnumerable GenToHmsInSecondsVariants() { yield return (timeSpan, hmsInSeconds); - if (timeSpan == TimeSpan.Zero) continue; + if (timeSpan == TimeSpan.Zero) + continue; if (timeSpan >= 1.Seconds()) yield return (-timeSpan, "-" + hmsInSeconds); diff --git a/test/Elastic.Apm.Tests/HelpersTests/UrlUtilsTests.cs b/test/Elastic.Apm.Tests/HelpersTests/UrlUtilsTests.cs index b0d64c860..2ec353385 100644 --- a/test/Elastic.Apm.Tests/HelpersTests/UrlUtilsTests.cs +++ b/test/Elastic.Apm.Tests/HelpersTests/UrlUtilsTests.cs @@ -38,7 +38,7 @@ public class UrlUtilsTests // ReSharper disable StringLiteralTypo [InlineData("http://München", "münchen", DefaultHttpPort)] [InlineData("http://Хост", "Хост", DefaultHttpPort)] // Host in Russian - // ReSharper restore StringLiteralTypo + // ReSharper restore StringLiteralTypo public void TryExtractDestinationInfo_valid_input(string inputUrl, string expectedHost, int? expectedPort) { var actualDestination = UrlUtils.ExtractDestination(new Uri(inputUrl), new NoopLogger()); diff --git a/test/Elastic.Apm.Tests/LabelTests.cs b/test/Elastic.Apm.Tests/LabelTests.cs index eaf8a6f00..59b399272 100644 --- a/test/Elastic.Apm.Tests/LabelTests.cs +++ b/test/Elastic.Apm.Tests/LabelTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests/LoggerTests.cs b/test/Elastic.Apm.Tests/LoggerTests.cs index c1f3f0522..1f123082d 100644 --- a/test/Elastic.Apm.Tests/LoggerTests.cs +++ b/test/Elastic.Apm.Tests/LoggerTests.cs @@ -400,7 +400,7 @@ public void PayloadSenderNoUserNamePwPrintedForServerUrl() inMemoryLogger.Lines.Should().HaveCountGreaterOrEqualTo(1); inMemoryLogger.Lines.Should().NotContain(n => n.Contains($"{userName}:{pw}")); - if(inMemoryLogger.Lines.Contains("localhost:8234")) + if (inMemoryLogger.Lines.Contains("localhost:8234")) inMemoryLogger.Lines.Should().Contain(n => n.Contains("http://[REDACTED]:[REDACTED]@localhost:8234")); } diff --git a/test/Elastic.Apm.Tests/Metrics/CgroupMetricsProviderTests.cs b/test/Elastic.Apm.Tests/Metrics/CgroupMetricsProviderTests.cs index ea408022e..5a846d1f9 100644 --- a/test/Elastic.Apm.Tests/Metrics/CgroupMetricsProviderTests.cs +++ b/test/Elastic.Apm.Tests/Metrics/CgroupMetricsProviderTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections.Generic; using System.IO; using System.Linq; @@ -31,10 +31,10 @@ public CgroupMetricsProviderTests() [Theory] [InlineData(964778496, "/proc/cgroup", "/proc/limited/memory", 7964778496)] - [InlineData(964778496, "/proc/cgroup2", "/proc/sys_cgroup2", 7964778496)] - // stat have different values to inactive_file and total_inactive_file - [InlineData(964778496, "/proc/cgroup2_only_0", "/proc/sys_cgroup2_unlimited", null)] - // stat have different values to inactive_file and total_inactive_file different order + [InlineData(964778496, "/proc/cgroup2", "/proc/sys_cgroup2", 7964778496)] + // stat have different values to inactive_file and total_inactive_file + [InlineData(964778496, "/proc/cgroup2_only_0", "/proc/sys_cgroup2_unlimited", null)] + // stat have different values to inactive_file and total_inactive_file different order [InlineData(964778496, "/proc/cgroup2_only_memory", "/proc/sys_cgroup2_unlimited_stat_different_order", null)] public void TestFreeCgroupMemory(double value, string selfCGroup, string sysFsGroup, double? memLimit) { @@ -87,7 +87,7 @@ public void TestCgroup2Regex(string testString, string expected) [DisabledTestFact("Sometimes fails in CI with `System.ArgumentNullException : Value cannot be null.`")] public void TestUnlimitedCgroup1() { - var cgroupMetrics = CreateUnlimitedSystemCgroupMetricsProvider("/proc/cgroup","/proc/unlimited/memory", "cgroup cgroup"); + var cgroupMetrics = CreateUnlimitedSystemCgroupMetricsProvider("/proc/cgroup", "/proc/unlimited/memory", "cgroup cgroup"); var samples = cgroupMetrics.GetSamples().ToList(); var memLimitSample = samples.First().Samples.SingleOrDefault(s => s.KeyValue.Key == SystemProcessCgroupMemoryMemLimitBytes); @@ -101,7 +101,7 @@ public void TestUnlimitedCgroup1() [DisabledTestFact("Flaky")] public void TestUnlimitedCgroup2() { - var cgroupMetrics = CreateUnlimitedSystemCgroupMetricsProvider("/proc/cgroup2","/proc/sys_cgroup2_unlimited", "cgroup2 cgroup"); + var cgroupMetrics = CreateUnlimitedSystemCgroupMetricsProvider("/proc/cgroup2", "/proc/sys_cgroup2_unlimited", "cgroup2 cgroup"); var samples = cgroupMetrics.GetSamples().ToList(); var memLimitSample = samples.First().Samples.SingleOrDefault(s => s.KeyValue.Key == SystemProcessCgroupMemoryMemLimitBytes); @@ -110,8 +110,8 @@ public void TestUnlimitedCgroup2() var memUsageSample = samples.First().Samples.SingleOrDefault(s => s.KeyValue.Key == SystemProcessCgroupMemoryMemUsageBytes); memUsageSample.Should().NotBeNull(); memUsageSample.KeyValue.Value.Should().Be(964778496); - } - + } + /// /// Makes sure that CGroup metrics collection exits with a log on non Linux OSs and only collects data on Linux. /// @@ -134,8 +134,8 @@ public void OsTest() logger.Lines.Where(line => line.Contains("detected a non Linux OS, therefore Cgroup metrics will not be reported")).Should().NotBeNullOrEmpty(); } - } - + } + /// /// Converts a test path into a path to a physical test file on disk /// diff --git a/test/Elastic.Apm.Tests/MetricsTests.cs b/test/Elastic.Apm.Tests/MetricsTests.cs index 14a9bc04f..4ff425da3 100644 --- a/test/Elastic.Apm.Tests/MetricsTests.cs +++ b/test/Elastic.Apm.Tests/MetricsTests.cs @@ -294,7 +294,7 @@ public void CollectAllMetrics_ShouldNotDisableProvider_WhenAnyValueIsSamplesIsVa public void GcMetricsCanBeDisabled() { var logger = new TestLogger(LogLevel.Trace); - var disableGc = new List() { {WildcardMatcher.ValueOf("clr.gc.*")} }; + var disableGc = new List() { { WildcardMatcher.ValueOf("clr.gc.*") } }; using var gcMetricsProvider = new GcMetricsProvider(logger, disableGc); gcMetricsProvider.IsEnabled(disableGc).Should().BeFalse(); } @@ -419,7 +419,8 @@ IEnumerable IMetricsProvider.GetSamples() internal class TestSystemTotalCpuProvider : SystemTotalCpuProvider { public TestSystemTotalCpuProvider(string procStatContent) : base(new NoopLogger(), - new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(procStatContent)))) { } + new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(procStatContent)))) + { } } } } diff --git a/test/Elastic.Apm.Tests/SamplerTests.cs b/test/Elastic.Apm.Tests/SamplerTests.cs index dc48e6688..c6e385cca 100644 --- a/test/Elastic.Apm.Tests/SamplerTests.cs +++ b/test/Elastic.Apm.Tests/SamplerTests.cs @@ -119,7 +119,8 @@ public void DistributionShouldBeUniform(double rate) var transaction = new Transaction(noopLogger, "test transaction name", "test transaction type", sampler, /* distributedTracingData: */ null, noopPayloadSender, configurationReader, currentExecutionSegmentsContainer, MockApmServerInfo.Version710, null); - if (transaction.IsSampled) ++sampledCount; + if (transaction.IsSampled) + ++sampledCount; // ReSharper disable once InvertIf if (i + 1 >= startCheckingAfter) diff --git a/test/Elastic.Apm.Tests/ServerCertificateTests.cs b/test/Elastic.Apm.Tests/ServerCertificateTests.cs index 5afe5da3d..0b271c79e 100644 --- a/test/Elastic.Apm.Tests/ServerCertificateTests.cs +++ b/test/Elastic.Apm.Tests/ServerCertificateTests.cs @@ -1,10 +1,10 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - -// depends on Mock APM server project TargetFramework - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +// depends on Mock APM server project TargetFramework + #if NET5_0_OR_GREATER using System; diff --git a/test/Elastic.Apm.Tests/ServiceResourceTests.cs b/test/Elastic.Apm.Tests/ServiceResourceTests.cs index 50439a181..37649e4af 100644 --- a/test/Elastic.Apm.Tests/ServiceResourceTests.cs +++ b/test/Elastic.Apm.Tests/ServiceResourceTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using Elastic.Apm.Api; using Elastic.Apm.Libraries.Newtonsoft.Json; @@ -29,8 +29,8 @@ public class ServiceResourceTest : IDisposable [JsonFileData("./TestResources/json-specs/service_resource_inference.json", typeof(Input))] public void TestServiceResourceInference(Input input) { - var span = CreateSpan(input.Span); - // auto-inference happens now + var span = CreateSpan(input.Span); + // auto-inference happens now span.End(); var targetType = span.Context?.Service?.Target?.Type; @@ -60,7 +60,8 @@ private ISpan CreateSpan(Span testDataSpan) { span.Context.Db = new Database { - Type = testDataSpan.Context.Db.Type, Instance = testDataSpan.Context.Db.Instance + Type = testDataSpan.Context.Db.Type, + Instance = testDataSpan.Context.Db.Instance }; } @@ -73,7 +74,8 @@ private ISpan CreateSpan(Span testDataSpan) }; } - if (testDataSpan.Context?.Http != null) span.Context.Http = new Http { Url = testDataSpan.Context.Http.Url }; + if (testDataSpan.Context?.Http != null) + span.Context.Http = new Http { Url = testDataSpan.Context.Http.Url }; if (testDataSpan.Context?.Service != null) { diff --git a/test/Elastic.Apm.Tests/SpanCompressionTests.cs b/test/Elastic.Apm.Tests/SpanCompressionTests.cs index bc0867422..a089a7b83 100644 --- a/test/Elastic.Apm.Tests/SpanCompressionTests.cs +++ b/test/Elastic.Apm.Tests/SpanCompressionTests.cs @@ -7,10 +7,10 @@ using System.Linq; using System.Threading; using Elastic.Apm.Api; +using Elastic.Apm.Model; using Elastic.Apm.Tests.Utilities; using FluentAssertions; using Xunit; -using Elastic.Apm.Model; namespace Elastic.Apm.Tests { @@ -74,7 +74,8 @@ public void NoCompositeOnPre80Versions() { var spanName = "Select * From Table"; var payloadSender = new MockPayloadSender(); - using (var agent = new ApmAgent(new TestAgentComponents(apmServerInfo: MockApmServerInfo.Version710, payloadSender: payloadSender))) Generate10DbCalls(agent, spanName, true, 2); + using (var agent = new ApmAgent(new TestAgentComponents(apmServerInfo: MockApmServerInfo.Version710, payloadSender: payloadSender))) + Generate10DbCalls(agent, spanName, true, 2); payloadSender.Transactions.Should().HaveCount(1); payloadSender.Spans.Should().HaveCount(10); @@ -280,7 +281,7 @@ public void CompressEligibleSpanAfterParenEnded() payloadSender.Spans.Count.Should().Be(11); payloadSender.Spans.Where(s => { - if(s is Span realSpan) + if (s is Span realSpan) return realSpan.Composite != null; return false; diff --git a/test/Elastic.Apm.Tests/SpanTests.cs b/test/Elastic.Apm.Tests/SpanTests.cs index 900337274..4df1ef105 100644 --- a/test/Elastic.Apm.Tests/SpanTests.cs +++ b/test/Elastic.Apm.Tests/SpanTests.cs @@ -1,7 +1,7 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Diagnostics; using Elastic.Apm.Config; @@ -16,113 +16,113 @@ public class SpanTests { [Fact] public void CaptureError_ShouldUseTransactionIdAsParent_WhenSpanDropped() - { - // Arrange + { + // Arrange var payloadSender = new MockPayloadSender(); - using (var agent = - new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(transactionMaxSpans: "0"), - payloadSender: payloadSender))) + using (var agent = + new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(transactionMaxSpans: "0"), + payloadSender: payloadSender))) { agent.Tracer.CaptureTransaction("transaction", "type", transaction => { transaction.CaptureSpan("parent", "type", span => - { - // Act + { + // Act span.CaptureError("Error message", "culprit", Array.Empty()); }); }); - } - - // Assert + } + + // Assert payloadSender.FirstError.ParentId.Should().Be(payloadSender.FirstTransaction.Id); } [Fact] public void CaptureException_ShouldUseTransactionIdAsParent_WhenSpanDropped() - { - // Arrange + { + // Arrange var payloadSender = new MockPayloadSender(); - using (var agent = - new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(transactionMaxSpans: "0"), - payloadSender: payloadSender))) + using (var agent = + new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(transactionMaxSpans: "0"), + payloadSender: payloadSender))) { agent.Tracer.CaptureTransaction("transaction", "type", transaction => { transaction.CaptureSpan("parent", "type", span => - { - // Act + { + // Act span.CaptureException(new Exception(), "culprit"); }); }); - } - - // Assert + } + + // Assert payloadSender.FirstError.ParentId.Should().Be(payloadSender.FirstTransaction.Id); } [Fact] public void CaptureError_ShouldUseTransactionIdAsParent_WhenSpanNonSampled() - { - // Arrange + { + // Arrange var payloadSender = new MockPayloadSender(); - using (var agent = - new ApmAgent(new TestAgentComponents( - configuration: new MockConfiguration(transactionSampleRate: "0"), payloadSender: payloadSender))) + using (var agent = + new ApmAgent(new TestAgentComponents( + configuration: new MockConfiguration(transactionSampleRate: "0"), payloadSender: payloadSender))) { agent.Tracer.CaptureTransaction("transaction", "type", transaction => { transaction.CaptureSpan("parent", "type", span => - { - // Act + { + // Act span.CaptureError("Error message", "culprit", Array.Empty()); }); }); - } - - // Assert + } + + // Assert payloadSender.FirstError.ParentId.Should().Be(payloadSender.FirstTransaction.Id); } [Fact] public void CaptureException_ShouldUseTransactionIdAsParent_WhenSpanNonSampled() - { - // Arrange + { + // Arrange var payloadSender = new MockPayloadSender(); - using (var agent = - new ApmAgent(new TestAgentComponents( - configuration: new MockConfiguration(transactionSampleRate: "0"), payloadSender: payloadSender))) + using (var agent = + new ApmAgent(new TestAgentComponents( + configuration: new MockConfiguration(transactionSampleRate: "0"), payloadSender: payloadSender))) { agent.Tracer.CaptureTransaction("transaction", "type", transaction => { transaction.CaptureSpan("parent", "type", span => - { - // Act + { + // Act span.CaptureException(new Exception(), "culprit"); }); }); - } - - // Assert + } + + // Assert payloadSender.FirstError.ParentId.Should().Be(payloadSender.FirstTransaction.Id); } [Fact] public void End_ShouldRestoreParentSpan_WhenTransactionIsNotSampled() - { - // Arrange + { + // Arrange var payloadSender = new MockPayloadSender(); - using (var agent = - new ApmAgent(new TestAgentComponents( - configuration: new MockConfiguration(transactionSampleRate: "0"), payloadSender: payloadSender))) + using (var agent = + new ApmAgent(new TestAgentComponents( + configuration: new MockConfiguration(transactionSampleRate: "0"), payloadSender: payloadSender))) { var transaction = agent.Tracer.StartTransaction("transaction", "type"); - var parentSpan = transaction.StartSpan("parent", "type"); - - // Act - parentSpan.CaptureSpan("span", "type", _ => { }); - - // Assert + var parentSpan = transaction.StartSpan("parent", "type"); + + // Act + parentSpan.CaptureSpan("span", "type", _ => { }); + + // Assert payloadSender.Spans.Count.Should().Be(0); agent.Tracer.CurrentSpan.Should().Be(parentSpan); } @@ -130,79 +130,79 @@ public void End_ShouldRestoreParentSpan_WhenTransactionIsNotSampled() [Fact] public void IsCaptureStackTraceOnEndEnabled_test_with_new_and_legacy_settings() - { - // Enabled by default if duration is met + { + // Enabled by default if duration is met Create_Span_ForCaptureStackTraceTest(new MockConfiguration()).Let(span => { span.Duration = ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds; span.IsCaptureStackTraceOnEndEnabled().Should().BeTrue(); - }); - - // Disabled if duration is too low. + }); + + // Disabled if duration is too low. Create_Span_ForCaptureStackTraceTest(new MockConfiguration()).Let(span => { span.Duration = ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds - 1; span.IsCaptureStackTraceOnEndEnabled().Should().BeFalse(); - }); - - // Disabled via "StackTraceLimit". + }); + + // Disabled via "StackTraceLimit". Create_Span_ForCaptureStackTraceTest(new MockConfiguration(stackTraceLimit: "0")).Let(span => { span.Duration = ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds; span.IsCaptureStackTraceOnEndEnabled().Should().BeFalse(); - }); - - // Disabled if a StackTrace is already present. + }); + + // Disabled if a StackTrace is already present. Create_Span_ForCaptureStackTraceTest(new MockConfiguration()).Let(span => { span.Duration = ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds; span.RawStackTrace = new StackTrace(); span.IsCaptureStackTraceOnEndEnabled().Should().BeFalse(); - }); - - // Enabled if duration is greater or equal + }); + + // Enabled if duration is greater or equal Create_Span_ForCaptureStackTraceTest(new MockConfiguration()).Let(span => { span.Duration = ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds; span.IsCaptureStackTraceOnEndEnabled().Should().BeTrue(); - }); - - // Disabled via "SpanStackTraceMinDurationInMilliseconds" + }); + + // Disabled via "SpanStackTraceMinDurationInMilliseconds" Create_Span_ForCaptureStackTraceTest(new MockConfiguration(spanStackTraceMinDurationInMilliseconds: "-1")).Let(span => { span.Duration = ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds; span.IsCaptureStackTraceOnEndEnabled().Should().BeFalse(); - }); - - // Disabled via legacy setting "SpanFramesMinDurationInMilliseconds" + }); + + // Disabled via legacy setting "SpanFramesMinDurationInMilliseconds" Create_Span_ForCaptureStackTraceTest(new MockConfiguration(spanFramesMinDurationInMilliseconds: "0")).Let(span => { span.Duration = ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds; span.IsCaptureStackTraceOnEndEnabled().Should().BeFalse(); - }); - - // Disabled: "SpanStackTraceMinDurationInMilliseconds" dominates legacy setting "SpanFramesMinDurationInMilliseconds" + }); + + // Disabled: "SpanStackTraceMinDurationInMilliseconds" dominates legacy setting "SpanFramesMinDurationInMilliseconds" Create_Span_ForCaptureStackTraceTest(new MockConfiguration(spanStackTraceMinDurationInMilliseconds: "-1", spanFramesMinDurationInMilliseconds: "1000ms")).Let(span => { span.Duration = ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds; span.IsCaptureStackTraceOnEndEnabled().Should().BeFalse(); - }); - - // Disabled: legacy setting "SpanFramesMinDurationInMilliseconds" still dominates over default value for "SpanStackTraceMinDurationInMilliseconds" + }); + + // Disabled: legacy setting "SpanFramesMinDurationInMilliseconds" still dominates over default value for "SpanStackTraceMinDurationInMilliseconds" Create_Span_ForCaptureStackTraceTest(new MockConfiguration(spanStackTraceMinDurationInMilliseconds: ConfigConsts.DefaultValues.SpanStackTraceMinDuration, spanFramesMinDurationInMilliseconds: "1s")).Let(span => { span.Duration = ConfigConsts.DefaultValues.SpanStackTraceMinDurationInMilliseconds; span.IsCaptureStackTraceOnEndEnabled().Should().BeFalse(); - }); - - // Enabled if duration exceeds set value + }); + + // Enabled if duration exceeds set value Create_Span_ForCaptureStackTraceTest(new MockConfiguration(spanStackTraceMinDurationInMilliseconds: "200ms")).Let(span => { span.Duration = 300; span.IsCaptureStackTraceOnEndEnabled().Should().BeTrue(); - }); - - // Enabled if duration exceeds set legacy value + }); + + // Enabled if duration exceeds set legacy value Create_Span_ForCaptureStackTraceTest(new MockConfiguration(spanFramesMinDurationInMilliseconds: "200ms")).Let(span => { span.Duration = 300; @@ -212,28 +212,28 @@ public void IsCaptureStackTraceOnEndEnabled_test_with_new_and_legacy_settings() [Fact] public void IsCaptureStackTraceOnStartEnabled_test_with_new_and_legacy_settings() - { - // Enabled by default + { + // Enabled by default Create_Span_ForCaptureStackTraceTest(new MockConfiguration()).IsCaptureStackTraceOnStartEnabled().Should() - .BeTrue(); - - // Disabled via "StackTraceLimit" + .BeTrue(); + + // Disabled via "StackTraceLimit" Create_Span_ForCaptureStackTraceTest(new MockConfiguration(stackTraceLimit: "0")) - .IsCaptureStackTraceOnStartEnabled().Should().BeFalse(); - - // Disabled via "SpanStackTraceMinDurationInMilliseconds" + .IsCaptureStackTraceOnStartEnabled().Should().BeFalse(); + + // Disabled via "SpanStackTraceMinDurationInMilliseconds" Create_Span_ForCaptureStackTraceTest(new MockConfiguration(spanStackTraceMinDurationInMilliseconds: "-1")) - .IsCaptureStackTraceOnStartEnabled().Should().BeFalse(); - - // Disabled via legacy setting "SpanFramesMinDurationInMilliseconds" + .IsCaptureStackTraceOnStartEnabled().Should().BeFalse(); + + // Disabled via legacy setting "SpanFramesMinDurationInMilliseconds" Create_Span_ForCaptureStackTraceTest(new MockConfiguration(spanFramesMinDurationInMilliseconds: "0")) - .IsCaptureStackTraceOnStartEnabled().Should().BeFalse(); - - // Disabled: "SpanStackTraceMinDurationInMilliseconds" dominates legacy setting "SpanFramesMinDurationInMilliseconds" + .IsCaptureStackTraceOnStartEnabled().Should().BeFalse(); + + // Disabled: "SpanStackTraceMinDurationInMilliseconds" dominates legacy setting "SpanFramesMinDurationInMilliseconds" Create_Span_ForCaptureStackTraceTest(new MockConfiguration(spanStackTraceMinDurationInMilliseconds: "-1", - spanFramesMinDurationInMilliseconds: "23ms")).IsCaptureStackTraceOnStartEnabled().Should().BeFalse(); - - // Disabled: legacy setting "SpanFramesMinDurationInMilliseconds" still dominates over default value for "SpanStackTraceMinDurationInMilliseconds" + spanFramesMinDurationInMilliseconds: "23ms")).IsCaptureStackTraceOnStartEnabled().Should().BeFalse(); + + // Disabled: legacy setting "SpanFramesMinDurationInMilliseconds" still dominates over default value for "SpanStackTraceMinDurationInMilliseconds" Create_Span_ForCaptureStackTraceTest(new MockConfiguration( spanStackTraceMinDurationInMilliseconds: ConfigConsts.DefaultValues.SpanStackTraceMinDuration, spanFramesMinDurationInMilliseconds: "23ms")).IsCaptureStackTraceOnStartEnabled().Should().BeTrue(); diff --git a/test/Elastic.Apm.Tests/SpecTests.cs b/test/Elastic.Apm.Tests/SpecTests.cs index ef6473720..eabcfc8dd 100644 --- a/test/Elastic.Apm.Tests/SpecTests.cs +++ b/test/Elastic.Apm.Tests/SpecTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.IO; @@ -26,20 +26,20 @@ public class SpecTests public SpecTests(ITestOutputHelper output) { var downloadDir = Directory.GetCurrentDirectory(); - var agentTypes = typeof(Agent).Assembly.GetTypes(); - - // classes and interfaces can define the spec... + var agentTypes = typeof(Agent).Assembly.GetTypes(); + + // classes and interfaces can define the spec... var specInterfaces = - (from type in agentTypes - where type.GetCustomAttribute() != null - select type).ToList(); - - // but the concrete implementations of spec types are what get serialized - // so they define the constraints such as max length, etc. + (from type in agentTypes + where type.GetCustomAttribute() != null + select type).ToList(); + + // but the concrete implementations of spec types are what get serialized + // so they define the constraints such as max length, etc. _specTypes = - (from type in agentTypes - where type.IsClass && specInterfaces.Any(i => i.IsAssignableFrom(type)) - select type).ToList(); + (from type in agentTypes + where type.IsClass && specInterfaces.Any(i => i.IsAssignableFrom(type)) + select type).ToList(); _validator = new Validator(); _output = output; diff --git a/test/Elastic.Apm.Tests/SystemInfoHelperTests.cs b/test/Elastic.Apm.Tests/SystemInfoHelperTests.cs index f05c664ac..204edfdb2 100644 --- a/test/Elastic.Apm.Tests/SystemInfoHelperTests.cs +++ b/test/Elastic.Apm.Tests/SystemInfoHelperTests.cs @@ -68,7 +68,7 @@ public struct CGroupTestData public string PodId; } -// Remove warning about unused test parameter "name" + // Remove warning about unused test parameter "name" #pragma warning disable xUnit1026 [Theory] [JsonFileData("./TestResources/json-specs/cgroup_parsing.json", typeof(CGroupTestData))] diff --git a/test/Elastic.Apm.Tests/TestHelpers/MultiThreadsTestUtilsTests.cs b/test/Elastic.Apm.Tests/TestHelpers/MultiThreadsTestUtilsTests.cs index a1ae9853e..b681fccea 100644 --- a/test/Elastic.Apm.Tests/TestHelpers/MultiThreadsTestUtilsTests.cs +++ b/test/Elastic.Apm.Tests/TestHelpers/MultiThreadsTestUtilsTests.cs @@ -35,7 +35,8 @@ public void thread_action_throws(int throwingThreadIndex) { MultiThreadsTestUtils.TestOnThreads(threadIndex => { - if (throwingThreadIndex == threadIndex) throw new DummyTestException(threadIndex.ToString()); + if (throwingThreadIndex == threadIndex) + throw new DummyTestException(threadIndex.ToString()); return null; }); diff --git a/test/Elastic.Apm.Tests/TestHelpers/TestingConfigTests.cs b/test/Elastic.Apm.Tests/TestHelpers/TestingConfigTests.cs index 945a26419..da61d7f22 100644 --- a/test/Elastic.Apm.Tests/TestHelpers/TestingConfigTests.cs +++ b/test/Elastic.Apm.Tests/TestHelpers/TestingConfigTests.cs @@ -65,7 +65,8 @@ public class TestingConfigTests } var invalidLogLevelStrings = new[] { "", "x", "some text", "with various \t white \n\t space" }; - foreach (var invalidLogLevelString in invalidLogLevelStrings) yield return (invalidLogLevelString, (object)null); + foreach (var invalidLogLevelString in invalidLogLevelStrings) + yield return (invalidLogLevelString, (object)null); string UppercaseLetterAt(string str, int index) { @@ -79,7 +80,8 @@ string UppercaseLetterAt(string str, int index) { foreach (var defaultValue in PossibleNullableIntDefaultValues) { - if (defaultValue == null) continue; + if (defaultValue == null) + continue; yield return (defaultValue.ToString(), (object)defaultValue); } diff --git a/test/Elastic.Apm.Tests/TransactionIgnoreUrlsTests.cs b/test/Elastic.Apm.Tests/TransactionIgnoreUrlsTests.cs index 164b80857..e22df241f 100644 --- a/test/Elastic.Apm.Tests/TransactionIgnoreUrlsTests.cs +++ b/test/Elastic.Apm.Tests/TransactionIgnoreUrlsTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/Elastic.Apm.Tests/UnsampledTransactionTests.cs b/test/Elastic.Apm.Tests/UnsampledTransactionTests.cs index 883fdc58c..64433b391 100644 --- a/test/Elastic.Apm.Tests/UnsampledTransactionTests.cs +++ b/test/Elastic.Apm.Tests/UnsampledTransactionTests.cs @@ -74,13 +74,13 @@ public void UnsampledTransactionWithCompressedSpanOnV8OrNewer() { var payloadSender = new MockPayloadSender(); using (var agent = new ApmAgent(new TestAgentComponents(apmServerInfo: MockApmServerInfo.Version80, payloadSender: payloadSender, - configuration: new MockConfiguration(transactionSampleRate: "0", exitSpanMinDuration:"0")))) + configuration: new MockConfiguration(transactionSampleRate: "0", exitSpanMinDuration: "0")))) { agent.Tracer.CaptureTransaction("foo", "bar", (t) => { for (var i = 0; i < 10; i++) { - var name = "Foo" + new Random().Next(); + var name = "Foo" + new Random().Next(); t.CaptureSpan(name, ApiConstants.TypeDb, (s) => { s.Context.Db = new Database() { Type = "mssql", Instance = "01" }; diff --git a/test/Elastic.Apm.Tests/WildcardMatcherTests.cs b/test/Elastic.Apm.Tests/WildcardMatcherTests.cs index e18a4be39..ac097e578 100644 --- a/test/Elastic.Apm.Tests/WildcardMatcherTests.cs +++ b/test/Elastic.Apm.Tests/WildcardMatcherTests.cs @@ -16,7 +16,7 @@ namespace Elastic.Apm.Tests { public class WildcardMatcherTests { -// Remove warning about unused test parameter "testCaseName" + // Remove warning about unused test parameter "testCaseName" #pragma warning disable xUnit1026 [Theory] [JsonFileData("./TestResources/json-specs/wildcard_matcher_tests.json")] diff --git a/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/AzureCosmosDbTestEnvironment.cs b/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/AzureCosmosDbTestEnvironment.cs index b0b60874e..acf450150 100644 --- a/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/AzureCosmosDbTestEnvironment.cs +++ b/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/AzureCosmosDbTestEnvironment.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.IO; @@ -18,8 +18,8 @@ namespace Elastic.Apm.Azure.CosmosDb.Tests public class AzureCosmosDbTestEnvironmentCollection : ICollectionFixture { - } - + } + /// /// A test environment for Azure CosmosDb that deploys and configures an Azure CosmosDb account /// in a given region and location @@ -37,9 +37,9 @@ public AzureCosmosDbTestEnvironment(IMessageSink messageSink) { var solutionRoot = SolutionPaths.Root; var terraformResourceDirectory = Path.Combine(solutionRoot, "build", "terraform", "azure", "cosmosdb"); - var credentials = AzureCredentials.Instance; - - // don't try to run terraform if not authenticated. + var credentials = AzureCredentials.Instance; + + // don't try to run terraform if not authenticated. if (credentials is Unauthenticated) return; diff --git a/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/DocumentItem.cs b/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/DocumentItem.cs index e770adb73..39f763e32 100644 --- a/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/DocumentItem.cs +++ b/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/DocumentItem.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Newtonsoft.Json; namespace Elastic.Apm.Azure.CosmosDb.Tests diff --git a/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/MicrosoftAzureCosmosTests.cs b/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/MicrosoftAzureCosmosTests.cs index efd374096..833a0f40b 100644 --- a/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/MicrosoftAzureCosmosTests.cs +++ b/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/MicrosoftAzureCosmosTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Threading.Tasks; using Elastic.Apm.Api; @@ -75,8 +75,9 @@ public async Task Capture_Span_When_List_Databases() await _agent.Tracer.CaptureTransaction("List CosmosDb Databases", ApiConstants.TypeDb, async () => { var iterator = _client.GetDatabaseQueryIterator(); - while(iterator.HasMoreResults) - foreach (var _ in await iterator.ReadNextAsync()) { } + while (iterator.HasMoreResults) + foreach (var _ in await iterator.ReadNextAsync()) + { } }); AssertSpan("List databases"); @@ -119,7 +120,7 @@ public async Task Capture_Span_When_List_Collections() await _agent.Tracer.CaptureTransaction("List CosmosDb Collections", ApiConstants.TypeDb, async () => { var iterator = db.GetContainerQueryIterator(); - while(iterator.HasMoreResults) + while (iterator.HasMoreResults) { foreach (var _ in await iterator.ReadNextAsync()) { @@ -225,7 +226,7 @@ private void AssertSpan(string action, string db = null, int count = 1) span.Type.Should().Be(ApiConstants.TypeDb); span.Subtype.Should().Be(ApiConstants.SubTypeCosmosDb); - if(!string.IsNullOrEmpty(db)) + if (!string.IsNullOrEmpty(db)) span.Context.Destination.Service.Resource.Should().Be($"{ApiConstants.SubTypeCosmosDb}/{db}"); else span.Context.Destination.Service.Resource.Should().Be(ApiConstants.SubTypeCosmosDb); diff --git a/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/MicrosoftAzureDocumentDbTests.cs b/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/MicrosoftAzureDocumentDbTests.cs index 28e5177b2..6aa2c96f4 100644 --- a/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/MicrosoftAzureDocumentDbTests.cs +++ b/test/azure/Elastic.Apm.Azure.CosmosDb.Tests/MicrosoftAzureDocumentDbTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; @@ -72,7 +72,7 @@ public async Task Capture_Span_When_List_Databases() await _agent.Tracer.CaptureTransaction("List CosmosDb Databases", ApiConstants.TypeDb, async () => { var response = await _client.ReadDatabaseFeedAsync(); - foreach(var db in response) + foreach (var db in response) { } }); @@ -117,7 +117,8 @@ public async Task Capture_Span_When_List_Collections() await _agent.Tracer.CaptureTransaction("List CosmosDb Collections", ApiConstants.TypeDb, async () => { var response = await _client.ReadDocumentCollectionFeedAsync(db.AltLink); - foreach (var collection in response) { } + foreach (var collection in response) + { } }); AssertSpan($"List collections {db.Id}", db.Id); @@ -179,9 +180,11 @@ private async Task CreateCollectionAsync(Microsoft.Azure.Doc var containerId = RandomName(); var containerResponse = await _client.CreateDocumentCollectionAsync( db.AltLink, - new DocumentCollection { + new DocumentCollection + { Id = containerId, - PartitionKey = new PartitionKeyDefinition{ Paths = new Collection{ "/PartitionKey" } } }); + PartitionKey = new PartitionKeyDefinition { Paths = new Collection { "/PartitionKey" } } + }); return containerResponse.Resource; } diff --git a/test/azure/Elastic.Apm.Azure.Functions.Tests/AzureFunctionsTests.cs b/test/azure/Elastic.Apm.Azure.Functions.Tests/AzureFunctionsTests.cs index 6f79306cc..d6f4398a8 100644 --- a/test/azure/Elastic.Apm.Azure.Functions.Tests/AzureFunctionsTests.cs +++ b/test/azure/Elastic.Apm.Azure.Functions.Tests/AzureFunctionsTests.cs @@ -1,7 +1,7 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Net.Http; using System.Threading.Tasks; diff --git a/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/Azure/QueueScope.cs b/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/Azure/QueueScope.cs index 7fd18c3b6..0e3424e0d 100644 --- a/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/Azure/QueueScope.cs +++ b/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/Azure/QueueScope.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Threading.Tasks; using Azure.Messaging.ServiceBus.Administration; @@ -20,8 +20,8 @@ private QueueScope(ServiceBusAdministrationClient adminClient, string queueName, _adminClient = adminClient; QueueName = queueName; _properties = properties; - } - + } + public static async Task CreateWithQueue(ServiceBusAdministrationClient adminClient) { var queueName = Guid.NewGuid().ToString("D"); diff --git a/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/Azure/TopicScope.cs b/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/Azure/TopicScope.cs index 7f931caf8..9789e7b43 100644 --- a/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/Azure/TopicScope.cs +++ b/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/Azure/TopicScope.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Threading.Tasks; using Azure.Messaging.ServiceBus.Administration; diff --git a/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/AzureMessagingServiceBusDiagnosticListenerTests.cs b/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/AzureMessagingServiceBusDiagnosticListenerTests.cs index 31b57b098..50bdc7b42 100644 --- a/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/AzureMessagingServiceBusDiagnosticListenerTests.cs +++ b/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/AzureMessagingServiceBusDiagnosticListenerTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Threading.Tasks; using Azure.Messaging.ServiceBus; diff --git a/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/MicrosoftAzureServiceBusDiagnosticListenerTests.cs b/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/MicrosoftAzureServiceBusDiagnosticListenerTests.cs index f39d496b1..86ec23c92 100644 --- a/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/MicrosoftAzureServiceBusDiagnosticListenerTests.cs +++ b/test/azure/Elastic.Apm.Azure.ServiceBus.Tests/MicrosoftAzureServiceBusDiagnosticListenerTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Text; using System.Threading.Tasks; diff --git a/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureBlobStorageDiagnosticListenerTests.cs b/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureBlobStorageDiagnosticListenerTests.cs index 51f6015b8..fe07d9e2c 100644 --- a/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureBlobStorageDiagnosticListenerTests.cs +++ b/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureBlobStorageDiagnosticListenerTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Text; using System.Threading.Tasks; @@ -15,7 +15,7 @@ namespace Elastic.Apm.Azure.Storage.Tests public class AzureBlobStorageDiagnosticListenerTests : BlobStorageTestsBase { public AzureBlobStorageDiagnosticListenerTests(AzureStorageTestEnvironment environment, ITestOutputHelper output) - :base (environment, output) + : base(environment, output) { } @@ -223,8 +223,8 @@ public async Task Capture_Span_When_Get_Blobs() await Agent.Tracer.CaptureTransaction("Get Blobs", ApiConstants.TypeStorage, async () => { var asyncPageable = scope.ContainerClient.GetBlobsAsync(); - await foreach (var blob in asyncPageable) - // ReSharper disable once Xunit.XunitTestWithConsoleOutput + await foreach (var blob in asyncPageable) + // ReSharper disable once Xunit.XunitTestWithConsoleOutput Console.WriteLine(blob.Name); }); diff --git a/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureFileShareStorageDiagnosticListenerTests.cs b/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureFileShareStorageDiagnosticListenerTests.cs index 9c82eee2c..6b0e68cdb 100644 --- a/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureFileShareStorageDiagnosticListenerTests.cs +++ b/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureFileShareStorageDiagnosticListenerTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Text; using System.Threading.Tasks; diff --git a/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureQueueStorageDiagnosticListenerTests.cs b/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureQueueStorageDiagnosticListenerTests.cs index 1a700fd2f..c63092702 100644 --- a/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureQueueStorageDiagnosticListenerTests.cs +++ b/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureQueueStorageDiagnosticListenerTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using Azure.Storage.Queues; using Elastic.Apm.Api; diff --git a/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureStorageTestEnvironment.cs b/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureStorageTestEnvironment.cs index fae5cadae..8ac37be5a 100644 --- a/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureStorageTestEnvironment.cs +++ b/test/azure/Elastic.Apm.Azure.Storage.Tests/AzureStorageTestEnvironment.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.IO; @@ -18,8 +18,8 @@ namespace Elastic.Apm.Azure.Storage.Tests public class AzureStorageTestEnvironmentCollection : ICollectionFixture { - } - + } + /// /// A test environment for Azure Storage that deploys and configures an Azure Storage account /// in a given region and location @@ -37,9 +37,9 @@ public AzureStorageTestEnvironment(IMessageSink messageSink) { var solutionRoot = SolutionPaths.Root; var terraformResourceDirectory = Path.Combine(solutionRoot, "build", "terraform", "azure", "storage"); - var credentials = AzureCredentials.Instance; - - // don't try to run terraform if not authenticated. + var credentials = AzureCredentials.Instance; + + // don't try to run terraform if not authenticated. if (credentials is Unauthenticated) return; @@ -98,8 +98,8 @@ public void Dispose() _terraform?.Destroy(_variables); } catch - { - // ignore if there's a problem destroying. The exception will be logged, and in CI, we'll let the cleanup tasks handle + { + // ignore if there's a problem destroying. The exception will be logged, and in CI, we'll let the cleanup tasks handle } } } diff --git a/test/azure/Elastic.Apm.Azure.Storage.Tests/BlobContainerScope.cs b/test/azure/Elastic.Apm.Azure.Storage.Tests/BlobContainerScope.cs index ac05f9f43..abafc27cf 100644 --- a/test/azure/Elastic.Apm.Azure.Storage.Tests/BlobContainerScope.cs +++ b/test/azure/Elastic.Apm.Azure.Storage.Tests/BlobContainerScope.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Threading.Tasks; using Azure.Storage.Blobs; diff --git a/test/azure/Elastic.Apm.Azure.Storage.Tests/BlobStorageTestsBase.cs b/test/azure/Elastic.Apm.Azure.Storage.Tests/BlobStorageTestsBase.cs index 2e62b24b0..a471edd1b 100644 --- a/test/azure/Elastic.Apm.Azure.Storage.Tests/BlobStorageTestsBase.cs +++ b/test/azure/Elastic.Apm.Azure.Storage.Tests/BlobStorageTestsBase.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using Elastic.Apm.Api; using Elastic.Apm.Logging; diff --git a/test/azure/Elastic.Apm.Azure.Storage.Tests/FileShareScope.cs b/test/azure/Elastic.Apm.Azure.Storage.Tests/FileShareScope.cs index 4fe117117..ae6da0b7e 100644 --- a/test/azure/Elastic.Apm.Azure.Storage.Tests/FileShareScope.cs +++ b/test/azure/Elastic.Apm.Azure.Storage.Tests/FileShareScope.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Threading.Tasks; using Azure.Storage.Files.Shares; diff --git a/test/azure/Elastic.Apm.Azure.Storage.Tests/MicrosoftAzureBlobStorageTracerTests.cs b/test/azure/Elastic.Apm.Azure.Storage.Tests/MicrosoftAzureBlobStorageTracerTests.cs index 7063fd5a0..5a0bdf324 100644 --- a/test/azure/Elastic.Apm.Azure.Storage.Tests/MicrosoftAzureBlobStorageTracerTests.cs +++ b/test/azure/Elastic.Apm.Azure.Storage.Tests/MicrosoftAzureBlobStorageTracerTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.IO; using System.Text; @@ -22,7 +22,7 @@ public class MicrosoftAzureBlobStorageTracerTests : BlobStorageTestsBase private readonly CloudStorageAccount _account; public MicrosoftAzureBlobStorageTracerTests(AzureStorageTestEnvironment environment, ITestOutputHelper output) - :base(environment, output) => + : base(environment, output) => _account = CloudStorageAccount.Parse(Environment.StorageAccountConnectionString); [AzureCredentialsFact] @@ -145,8 +145,8 @@ public async Task Capture_Span_When_Copy_From_Uri() var containerReference = client.GetContainerReference(scope.ContainerName); var sourceBlobReference = containerReference.GetBlockBlobReference(sourceBlobName); - await using var stream = new MemoryStream(Encoding.UTF8.GetBytes("block blob")); - await sourceBlobReference.UploadFromStreamAsync(stream); + await using var stream = new MemoryStream(Encoding.UTF8.GetBytes("block blob")); + await sourceBlobReference.UploadFromStreamAsync(stream); var destinationBlobName = Guid.NewGuid().ToString(); diff --git a/test/iis/AspNetFullFrameworkSampleApp/ActionFilters/RedirectIfAuthenticatedAttribute.cs b/test/iis/AspNetFullFrameworkSampleApp/ActionFilters/RedirectIfAuthenticatedAttribute.cs index 74956b31b..fa2e091c7 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/ActionFilters/RedirectIfAuthenticatedAttribute.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/ActionFilters/RedirectIfAuthenticatedAttribute.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Web.Mvc; namespace AspNetFullFrameworkSampleApp.ActionFilters -{ +{ /// /// Redirects an authenticated user from an action intended for an unauthenticated user. /// diff --git a/test/iis/AspNetFullFrameworkSampleApp/App_Start/ApmLoggerToNLog.cs b/test/iis/AspNetFullFrameworkSampleApp/App_Start/ApmLoggerToNLog.cs index eff9b7e5d..ccdc331a7 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/App_Start/ApmLoggerToNLog.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/App_Start/ApmLoggerToNLog.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using Elastic.Apm.Logging; using NLog; -using NLogLevel = NLog.LogLevel; using ApmLogLevel = Elastic.Apm.Logging.LogLevel; +using NLogLevel = NLog.LogLevel; namespace AspNetFullFrameworkSampleApp { @@ -17,7 +17,7 @@ internal class ApmLoggerToNLog : IApmLogger public bool IsEnabled(ApmLogLevel level) => _logger.Value.IsEnabled(ConvertLevel(level)); public ApmLoggerToNLog() - :this(string.Empty) + : this(string.Empty) { } @@ -42,14 +42,22 @@ private static NLogLevel ConvertLevel(ApmLogLevel apmLogLevel) { switch (apmLogLevel) { - case ApmLogLevel.Trace: return NLogLevel.Trace; - case ApmLogLevel.Debug: return NLogLevel.Debug; - case ApmLogLevel.Information: return NLogLevel.Info; - case ApmLogLevel.Warning: return NLogLevel.Warn; - case ApmLogLevel.Error: return NLogLevel.Error; - case ApmLogLevel.Critical: return NLogLevel.Fatal; - case ApmLogLevel.None: return NLogLevel.Off; - default: return NLogLevel.Info; + case ApmLogLevel.Trace: + return NLogLevel.Trace; + case ApmLogLevel.Debug: + return NLogLevel.Debug; + case ApmLogLevel.Information: + return NLogLevel.Info; + case ApmLogLevel.Warning: + return NLogLevel.Warn; + case ApmLogLevel.Error: + return NLogLevel.Error; + case ApmLogLevel.Critical: + return NLogLevel.Fatal; + case ApmLogLevel.None: + return NLogLevel.Off; + default: + return NLogLevel.Info; } } } diff --git a/test/iis/AspNetFullFrameworkSampleApp/App_Start/BundleConfig.cs b/test/iis/AspNetFullFrameworkSampleApp/App_Start/BundleConfig.cs index 8aa98b5a4..ae5f0bd78 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/App_Start/BundleConfig.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/App_Start/BundleConfig.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/iis/AspNetFullFrameworkSampleApp/App_Start/FilterConfig.cs b/test/iis/AspNetFullFrameworkSampleApp/App_Start/FilterConfig.cs index d265014de..7c82d1e9c 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/App_Start/FilterConfig.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/App_Start/FilterConfig.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/iis/AspNetFullFrameworkSampleApp/App_Start/LoggingConfig.cs b/test/iis/AspNetFullFrameworkSampleApp/App_Start/LoggingConfig.cs index 6b2ec90af..544914d45 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/App_Start/LoggingConfig.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/App_Start/LoggingConfig.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -40,15 +40,18 @@ public static void SetupLogging() }; var logFileEnvVarValue = Environment.GetEnvironmentVariable(LogFileEnvVarName); - if (logFileEnvVarValue != null) logTargets.Add(new FileTarget { FileName = logFileEnvVarValue, DeleteOldFileOnStartup = true }); + if (logFileEnvVarValue != null) + logTargets.Add(new FileTarget { FileName = logFileEnvVarValue, DeleteOldFileOnStartup = true }); - foreach (var logTarget in logTargets) logTarget.Layout = layout; + foreach (var logTarget in logTargets) + logTarget.Layout = layout; // ReSharper disable once CoVariantArrayConversion config.AddRule(LogLevel.Trace, LogLevel.Fatal, new SplitGroupTarget(logTargets.ToArray())); InternalLogger.LogToConsole = true; - if (logFileEnvVarValue != null) InternalLogger.LogFile = logFileEnvVarValue; + if (logFileEnvVarValue != null) + InternalLogger.LogFile = logFileEnvVarValue; InternalLogger.LogLevel = LogLevel.Info; InternalLogger.LogWriter = new StringWriter(); @@ -82,7 +85,8 @@ protected override void Write(LogEventInfo logEvent) private static string PrefixEveryLine(string input, string prefix = "") { // We treat empty input as a special case because StringReader doesn't return it as an empty line - if (input.Length == 0) return prefix; + if (input.Length == 0) + return prefix; var resultBuilder = new StringBuilder(input.Length); using (var stringReader = new StringReader(input)) @@ -105,7 +109,8 @@ private static string PrefixEveryLine(string input, string prefix = "") foreach (var endOfLineSeq in EndOfLineCharSequences) { - if (!input.EndsWith(endOfLineSeq)) continue; + if (!input.EndsWith(endOfLineSeq)) + continue; resultBuilder.Append(endOfLineSeq); break; diff --git a/test/iis/AspNetFullFrameworkSampleApp/App_Start/RouteConfig.cs b/test/iis/AspNetFullFrameworkSampleApp/App_Start/RouteConfig.cs index d06629673..5118b31b7 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/App_Start/RouteConfig.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/App_Start/RouteConfig.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/iis/AspNetFullFrameworkSampleApp/App_Start/Startup.cs b/test/iis/AspNetFullFrameworkSampleApp/App_Start/Startup.cs index 9697943dc..22cc76a67 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/App_Start/Startup.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/App_Start/Startup.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using AspNetFullFrameworkSampleApp.Models; using AspNetFullFrameworkSampleApp.Services.Auth; @@ -17,19 +17,19 @@ namespace AspNetFullFrameworkSampleApp { public class Startup { - public void Configuration(IAppBuilder app) => ConfigureAuth(app); - - // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864 - public void ConfigureAuth(IAppBuilder app) => - // Enable the application to use a cookie to store information for the signed in user + public void Configuration(IAppBuilder app) => ConfigureAuth(app); + + // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864 + public void ConfigureAuth(IAppBuilder app) => + // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider - { - // Enables the application to validate the security stamp when the user logs in. - // This is a security feature which is used when you change a password or add an external login to your account. + { + // Enables the application to validate the security stamp when the user logs in. + // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity( TimeSpan.FromMinutes(30), (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)) diff --git a/test/iis/AspNetFullFrameworkSampleApp/App_Start/WebApiConfig.cs b/test/iis/AspNetFullFrameworkSampleApp/App_Start/WebApiConfig.cs index 92cfbbb33..47c6a1e4d 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/App_Start/WebApiConfig.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/App_Start/WebApiConfig.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Linq; using System.Web; using System.Web.Http; @@ -14,13 +14,13 @@ namespace AspNetFullFrameworkSampleApp public static class WebApiConfig { public static void Register(HttpConfiguration configuration) - { - // remove xml support + { + // remove xml support var appXmlType = configuration.Formatters.XmlFormatter.SupportedMediaTypes .FirstOrDefault(t => t.MediaType == "application/xml"); - configuration.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); - - // don't buffer multipart data to web api + configuration.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); + + // don't buffer multipart data to web api configuration.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferMultipartPolicySelector()); } } diff --git a/test/iis/AspNetFullFrameworkSampleApp/Areas/MyArea/Controllers/HomeController.cs b/test/iis/AspNetFullFrameworkSampleApp/Areas/MyArea/Controllers/HomeController.cs index a494cfcdd..32bc830e9 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Areas/MyArea/Controllers/HomeController.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Areas/MyArea/Controllers/HomeController.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Web.Mvc; namespace AspNetFullFrameworkSampleApp.Areas.MyArea.Controllers diff --git a/test/iis/AspNetFullFrameworkSampleApp/Areas/MyArea/MyAreaRegistration.cs b/test/iis/AspNetFullFrameworkSampleApp/Areas/MyArea/MyAreaRegistration.cs index 51db63a7b..2c967d04a 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Areas/MyArea/MyAreaRegistration.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Areas/MyArea/MyAreaRegistration.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Web.Mvc; namespace AspNetFullFrameworkSampleApp.Areas.MyArea diff --git a/test/iis/AspNetFullFrameworkSampleApp/Asmx/Health.asmx.cs b/test/iis/AspNetFullFrameworkSampleApp/Asmx/Health.asmx.cs index 4c29a7869..630c80181 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Asmx/Health.asmx.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Asmx/Health.asmx.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/iis/AspNetFullFrameworkSampleApp/Bootstrap/AlertStatus.cs b/test/iis/AspNetFullFrameworkSampleApp/Bootstrap/AlertStatus.cs index 3de3aff57..30d9f6ed5 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Bootstrap/AlertStatus.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Bootstrap/AlertStatus.cs @@ -7,4 +7,4 @@ public enum AlertStatus Danger, Warning } -} \ No newline at end of file +} diff --git a/test/iis/AspNetFullFrameworkSampleApp/Controllers/AccountController.cs b/test/iis/AspNetFullFrameworkSampleApp/Controllers/AccountController.cs index 6650ff145..1e717fe3d 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Controllers/AccountController.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Controllers/AccountController.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; using System.Web; using System.Web.Mvc; @@ -24,9 +24,9 @@ public class AccountController : ControllerBase private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; - private IAuthenticationManager AuthenticationManager => HttpContext.GetOwinContext().Authentication; - - // TODO: dependency injection over service creation... + private IAuthenticationManager AuthenticationManager => HttpContext.GetOwinContext().Authentication; + + // TODO: dependency injection over service creation... private ApplicationSignInManager SignInManager => _signInManager ?? new ApplicationSignInManager(UserManager, HttpContext.GetOwinContext().Authentication); @@ -48,10 +48,10 @@ public ActionResult Login(string returnUrl) public async Task Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) - return View(model); - - // This doesn't count login failures towards account lockout - // To enable password failures to trigger account lockout, change to shouldLockout: true + return View(model); + + // This doesn't count login failures towards account lockout + // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); switch (result) { @@ -77,11 +77,11 @@ public async Task Register(RegisterViewModel model) var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { - var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); - // ReSharper disable once PossibleNullReferenceException - var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code }, Request.Url.Scheme); - - // IMPORTANT: this would normally be sent as an email to confirm, but for simplicity, will be rendered on the next page + var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); + // ReSharper disable once PossibleNullReferenceException + var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code }, Request.Url.Scheme); + + // IMPORTANT: this would normally be sent as an email to confirm, but for simplicity, will be rendered on the next page AddAlert(new SuccessAlert( "Account created", "You can now log in. Please confirm your account by clicking here")); @@ -115,27 +115,27 @@ public async Task ForgotPassword(ForgotPasswordViewModel model) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null || !await UserManager.IsEmailConfirmedAsync(user.Id)) - { - // Don't reveal that the user does not exist or is not confirmed + { + // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action( "ResetPassword", - "Account", - // ReSharper disable once PossibleNullReferenceException - new { userId = user.Id, code }, Request.Url.Scheme); - - // IMPORTANT: this would normally be sent as an email to confirm, but for simplicity, will be rendered on the next page + "Account", + // ReSharper disable once PossibleNullReferenceException + new { userId = user.Id, code }, Request.Url.Scheme); + + // IMPORTANT: this would normally be sent as an email to confirm, but for simplicity, will be rendered on the next page AddAlert(new SuccessAlert( "Password reset", "Please reset the password for your account by clicking here")); return RedirectToAction("ForgotPasswordConfirmation", "Account"); - } - - // If we got this far, something failed, redisplay form + } + + // If we got this far, something failed, redisplay form return View(model); } @@ -150,16 +150,18 @@ public async Task ForgotPassword(ForgotPasswordViewModel model) [RedirectIfAuthenticated] public async Task ResetPassword(ResetPasswordViewModel model) { - if (!ModelState.IsValid) return View(model); + if (!ModelState.IsValid) + return View(model); var user = await UserManager.FindByNameAsync(model.Email); if (user == null) - { - // Don't reveal that the user does not exist + { + // Don't reveal that the user does not exist return RedirectToAction("ResetPasswordConfirmation", "Account"); } var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); - if (result.Succeeded) return RedirectToAction("ResetPasswordConfirmation", "Account"); + if (result.Succeeded) + return RedirectToAction("ResetPasswordConfirmation", "Account"); AddErrors(result); return View(); @@ -193,12 +195,14 @@ protected override void Dispose(bool disposing) private void AddErrors(IdentityResult result) { - foreach (var error in result.Errors) ModelState.AddModelError("", error); + foreach (var error in result.Errors) + ModelState.AddModelError("", error); } private ActionResult RedirectToLocal(string returnUrl) { - if (Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl); + if (Url.IsLocalUrl(returnUrl)) + return Redirect(returnUrl); return RedirectToAction("Index", "Home"); } diff --git a/test/iis/AspNetFullFrameworkSampleApp/Controllers/AttributeRoutingWebApiController.cs b/test/iis/AspNetFullFrameworkSampleApp/Controllers/AttributeRoutingWebApiController.cs index e001bcf4d..fda101e7b 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Controllers/AttributeRoutingWebApiController.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Controllers/AttributeRoutingWebApiController.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Web.Http; namespace AspNetFullFrameworkSampleApp.Controllers diff --git a/test/iis/AspNetFullFrameworkSampleApp/Controllers/ControllerBase.cs b/test/iis/AspNetFullFrameworkSampleApp/Controllers/ControllerBase.cs index 3477eca20..7c8fee251 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Controllers/ControllerBase.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Controllers/ControllerBase.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.IO; using System.Web.Mvc; using AspNetFullFrameworkSampleApp.Bootstrap; diff --git a/test/iis/AspNetFullFrameworkSampleApp/Controllers/DatabaseController.cs b/test/iis/AspNetFullFrameworkSampleApp/Controllers/DatabaseController.cs index cba726b9a..3a305166c 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Controllers/DatabaseController.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Controllers/DatabaseController.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections.Generic; using System.Data.Entity; using System.Linq; @@ -16,12 +16,12 @@ using Newtonsoft.Json; namespace AspNetFullFrameworkSampleApp.Controllers -{ +{ /// /// Demonstrates database functionality /// public class DatabaseController : ControllerBase - { + { /// /// List the sample data in the database /// @@ -33,8 +33,8 @@ public ActionResult Index() samples = context.Set().ToList(); return View(samples); - } - + } + /// /// Allows sample data to be inserted into the database /// @@ -57,9 +57,9 @@ public async Task Create(CreateSampleDataViewModel model) AddAlert(new SuccessAlert("Sample added", $"{changes} sample was saved to the database")); return RedirectToAction("Index"); - } - - // TODO: make this a web api controller action + } + + // TODO: make this a web api controller action /// /// Generates the given count of sample data, and calls the bulk action to insert into the database /// @@ -93,9 +93,9 @@ public async Task Generate(int count) var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); return Stream(responseStream, contentType, (int)response.StatusCode); - } - - // TODO: make this a web api controller action + } + + // TODO: make this a web api controller action /// /// Bulk inserts sample data into the database /// diff --git a/test/iis/AspNetFullFrameworkSampleApp/Controllers/DiagnosticsController.cs b/test/iis/AspNetFullFrameworkSampleApp/Controllers/DiagnosticsController.cs index 09d37066d..afd2c98fc 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Controllers/DiagnosticsController.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Controllers/DiagnosticsController.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -41,7 +41,8 @@ public ActionResult Index() } var inMemoryLogContentBuilder = new StringBuilder(); - foreach (var line in LoggingConfig.LogMemoryTarget.Logs) inMemoryLogContentBuilder.AppendLine(line); + foreach (var line in LoggingConfig.LogMemoryTarget.Logs) + inMemoryLogContentBuilder.AppendLine(line); model.InMemoryLogContent = inMemoryLogContentBuilder.ToString(); model.LoggingSubsystemInternalLogContent = InternalLogger.LogWriter?.ToString(); diff --git a/test/iis/AspNetFullFrameworkSampleApp/Controllers/HomeController.cs b/test/iis/AspNetFullFrameworkSampleApp/Controllers/HomeController.cs index c438a5c3d..8cef39af5 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Controllers/HomeController.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Controllers/HomeController.cs @@ -136,7 +136,8 @@ internal static async Task CustomSpanThrowsInternal() bool doCaptureSpan = true ) { - if (!doCaptureSpan || Agent.Tracer.CurrentTransaction == null) return func(); + if (!doCaptureSpan || Agent.Tracer.CurrentTransaction == null) + return func(); var currentExecutionSegment = Agent.Tracer.CurrentSpan ?? (IExecutionSegment)Agent.Tracer.CurrentTransaction; return currentExecutionSegment.CaptureSpan(spanName, spanType, func, subType, action); @@ -301,14 +302,16 @@ void ConcurrentSpan(string branchId, ITransaction tx) var numberOfInserts = isContainedSpan ? 2 : 1; for (var j = 0; j < numberOfInserts; ++j) { - if (isContainedSpan) syncBarrier.SignalAndWait(); + if (isContainedSpan) + syncBarrier.SignalAndWait(); using (var dbCtx = new SampleDataDbContext( /* attachedState: */ isContainedSpan)) { var suffix = isContainedSpan ? j == 0 ? ".before" : ".after" : ""; dbCtx.Set().Add(new SampleData { Name = $"{branchId}.{i}{suffix}" }); dbCtx.SaveChanges(); } - if (isContainedSpan) syncBarrier.SignalAndWait(); + if (isContainedSpan) + syncBarrier.SignalAndWait(); } } }); @@ -345,7 +348,8 @@ public ActionResult GenNSpans() private string GetQueryStringValue(string key, string defaultValue) { var values = HttpContext.Request.QueryString.GetValues(key); - if (values == null || values.Length == 0) return defaultValue; + if (values == null || values.Length == 0) + return defaultValue; if (values.Length > 1) throw new ArgumentException($"{key} should appear in query string at most once", key); @@ -394,11 +398,14 @@ private class ConcurrentDbTestDbCommandInterceptor : IDbCommandInterceptor private void ProcessCommandEvent(DbCommandInterceptionContext interceptionContext) { - if (!(interceptionContext.DbContexts.SingleOrDefault() is SampleDataDbContext sampleDataDbContext)) return; - if (sampleDataDbContext.AttachedState == null) return; + if (!(interceptionContext.DbContexts.SingleOrDefault() is SampleDataDbContext sampleDataDbContext)) + return; + if (sampleDataDbContext.AttachedState == null) + return; var isContainedSpan = (bool)sampleDataDbContext.AttachedState; - if (isContainedSpan) return; + if (isContainedSpan) + return; // Wait for the first/second contained span's start _syncBarrier.SignalAndWait(); diff --git a/test/iis/AspNetFullFrameworkSampleApp/Controllers/WebApiController.cs b/test/iis/AspNetFullFrameworkSampleApp/Controllers/WebApiController.cs index 58158275b..aaef3d5b1 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Controllers/WebApiController.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Controllers/WebApiController.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Net.Http; using System.Text; using System.Threading.Tasks; @@ -21,7 +21,7 @@ public async Task Post() { var multipart = await Request.Content.ReadAsMultipartAsync(); var result = new StringBuilder(); - foreach(var content in multipart.Contents) + foreach (var content in multipart.Contents) result.Append(await content.ReadAsStringAsync()); return Ok(result.ToString()); diff --git a/test/iis/AspNetFullFrameworkSampleApp/Data/SampleDataDbContext.cs b/test/iis/AspNetFullFrameworkSampleApp/Data/SampleDataDbContext.cs index 97fcaecdb..f5ea13c56 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Data/SampleDataDbContext.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Data/SampleDataDbContext.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/iis/AspNetFullFrameworkSampleApp/Extensions/TempDataExtensions.cs b/test/iis/AspNetFullFrameworkSampleApp/Extensions/TempDataExtensions.cs index 519f313f7..f92f81eb9 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Extensions/TempDataExtensions.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Extensions/TempDataExtensions.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Web.Mvc; namespace AspNetFullFrameworkSampleApp.Extensions diff --git a/test/iis/AspNetFullFrameworkSampleApp/Global.asax.cs b/test/iis/AspNetFullFrameworkSampleApp/Global.asax.cs index 56b3a7473..886d7ddcc 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Global.asax.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Global.asax.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -26,9 +26,9 @@ protected void Application_Start() var logger = LogManager.GetCurrentClassLogger(); logger.Info("Current process ID: {ProcessID}, ELASTIC_APM_SERVER_URLS: {ELASTIC_APM_SERVER_URLS}", - Process.GetCurrentProcess().Id, Environment.GetEnvironmentVariable("ELASTIC_APM_SERVER_URLS")); - - // Web API setup + Process.GetCurrentProcess().Id, Environment.GetEnvironmentVariable("ELASTIC_APM_SERVER_URLS")); + + // Web API setup HttpBatchHandler batchHandler = new DefaultHttpBatchHandler(GlobalConfiguration.DefaultServer) { ExecutionOrder = BatchExecutionOrder.NonSequential @@ -49,13 +49,15 @@ protected void Application_Start() protected void Application_BeginRequest(object sender, EventArgs e) { - if (Response.HeadersWritten) return; + if (Response.HeadersWritten) + return; Response.AddOnSendingHeaders(httpContext => { // ReSharper disable once ConstantConditionalAccessQualifier var responseHeaders = httpContext?.Response?.Headers; - if (responseHeaders == null) return; + if (responseHeaders == null) + return; AddHeaderIfNotPresent(responseHeaders, Consts.ElasticApmServerUrlsResponseHeaderName, Agent.Config.ServerUrl.ToString()); AddHeaderIfNotPresent(responseHeaders, Consts.ProcessIdResponseHeaderName, Process.GetCurrentProcess().Id.ToString()); @@ -64,7 +66,8 @@ protected void Application_BeginRequest(object sender, EventArgs e) void AddHeaderIfNotPresent(NameValueCollection responseHeaders, string headerName, string headerValue) { var alreadyExistingValues = responseHeaders.GetValues(headerName); - if (alreadyExistingValues != null && alreadyExistingValues.Length > 0) return; + if (alreadyExistingValues != null && alreadyExistingValues.Length > 0) + return; responseHeaders.Add(headerName, headerValue); } diff --git a/test/iis/AspNetFullFrameworkSampleApp/Models/ApplicationUser.cs b/test/iis/AspNetFullFrameworkSampleApp/Models/ApplicationUser.cs index b42ba8111..0533bb156 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Models/ApplicationUser.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Models/ApplicationUser.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Microsoft.AspNet.Identity.EntityFramework; namespace AspNetFullFrameworkSampleApp.Models -{ +{ /// /// A user of this application /// diff --git a/test/iis/AspNetFullFrameworkSampleApp/Models/CreateSampleDataViewModel.cs b/test/iis/AspNetFullFrameworkSampleApp/Models/CreateSampleDataViewModel.cs index c7a7a719d..5f37b6d3a 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Models/CreateSampleDataViewModel.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Models/CreateSampleDataViewModel.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.ComponentModel.DataAnnotations; namespace AspNetFullFrameworkSampleApp.Models diff --git a/test/iis/AspNetFullFrameworkSampleApp/Models/ForgotPasswordViewModel.cs b/test/iis/AspNetFullFrameworkSampleApp/Models/ForgotPasswordViewModel.cs index 73d40b819..3086d89e5 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Models/ForgotPasswordViewModel.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Models/ForgotPasswordViewModel.cs @@ -1,17 +1,17 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.ComponentModel.DataAnnotations; namespace AspNetFullFrameworkSampleApp.Models { - public class ForgotPasswordViewModel - { - [Required] - [EmailAddress] - [Display(Name = "Email")] - public string Email { get; set; } - } + public class ForgotPasswordViewModel + { + [Required] + [EmailAddress] + [Display(Name = "Email")] + public string Email { get; set; } + } } diff --git a/test/iis/AspNetFullFrameworkSampleApp/Models/LoginViewModel.cs b/test/iis/AspNetFullFrameworkSampleApp/Models/LoginViewModel.cs index 5a43c3e1c..e68ca372e 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Models/LoginViewModel.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Models/LoginViewModel.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.ComponentModel.DataAnnotations; namespace AspNetFullFrameworkSampleApp.Models diff --git a/test/iis/AspNetFullFrameworkSampleApp/Models/RegisterViewModel.cs b/test/iis/AspNetFullFrameworkSampleApp/Models/RegisterViewModel.cs index 98f8fb67e..6e177a625 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Models/RegisterViewModel.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Models/RegisterViewModel.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.ComponentModel.DataAnnotations; namespace AspNetFullFrameworkSampleApp.Models diff --git a/test/iis/AspNetFullFrameworkSampleApp/Models/ResetPasswordViewModel.cs b/test/iis/AspNetFullFrameworkSampleApp/Models/ResetPasswordViewModel.cs index 270f85fb2..c6b009e74 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Models/ResetPasswordViewModel.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Models/ResetPasswordViewModel.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.ComponentModel.DataAnnotations; namespace AspNetFullFrameworkSampleApp.Models diff --git a/test/iis/AspNetFullFrameworkSampleApp/Mvc/JsonNetValueProviderFactory.cs b/test/iis/AspNetFullFrameworkSampleApp/Mvc/JsonNetValueProviderFactory.cs index 6a0db2dff..4abe13ecd 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Mvc/JsonNetValueProviderFactory.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Mvc/JsonNetValueProviderFactory.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - -// https://gist.github.com/rorymurphy/db0b02e8267960a0881a -// This is a slightly modified ValueProviderFactory based almost entirely on Microsoft's JsonValueProviderFactory. -// That file is licensed under the Apache 2.0 license, but I am leaving the copyright statement below nonetheless. -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +// https://gist.github.com/rorymurphy/db0b02e8267960a0881a +// This is a slightly modified ValueProviderFactory based almost entirely on Microsoft's JsonValueProviderFactory. +// That file is licensed under the Apache 2.0 license, but I am leaving the copyright statement below nonetheless. +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + using System; using System.Collections; using System.Collections.Generic; @@ -19,43 +19,43 @@ using Newtonsoft.Json.Converters; namespace AspNetFullFrameworkSampleApp.Mvc -{ +{ /// /// A value provider factory for application/json requests that uses /// Json.NET to deserialize the request stream and provide the /// value to subsequent steps. /// - public sealed class JsonNetValueProviderFactory : ValueProviderFactory - { + public sealed class JsonNetValueProviderFactory : ValueProviderFactory + { private static readonly JsonSerializer Serializer = new JsonSerializer { Converters = { new ExpandoObjectConverter() } - }; - - private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value) - { + }; + + private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value) + { switch (value) { - case IDictionary d: - { - foreach (var entry in d) - AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value); - return; - } - case IList l: - { - for (var i = 0; i < l.Count; i++) - AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]); - return; - } + case IDictionary d: + { + foreach (var entry in d) + AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value); + return; + } + case IList l: + { + for (var i = 0; i < l.Count; i++) + AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]); + return; + } default: backingStore.Add(prefix, value); break; } - } - - private static object GetDeserializedObject(ControllerContext controllerContext) - { + } + + private static object GetDeserializedObject(ControllerContext controllerContext) + { var request = controllerContext.HttpContext.Request; if (!request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) return null; @@ -67,8 +67,8 @@ private static object GetDeserializedObject(ControllerContext controllerContext) if (string.IsNullOrEmpty(bodyText)) return null; - object jsonData; - using (var reader = new StringReader(bodyText)) + object jsonData; + using (var reader = new StringReader(bodyText)) using (var jsonTextReader = new JsonTextReader(reader)) { jsonTextReader.Read(); @@ -78,53 +78,55 @@ private static object GetDeserializedObject(ControllerContext controllerContext) jsonData = Serializer.Deserialize(jsonTextReader); } - return jsonData; - } - - public override IValueProvider GetValueProvider(ControllerContext controllerContext) - { - if (controllerContext == null) + return jsonData; + } + + public override IValueProvider GetValueProvider(ControllerContext controllerContext) + { + if (controllerContext == null) throw new ArgumentNullException(nameof(controllerContext)); - var jsonData = GetDeserializedObject(controllerContext); - if (jsonData == null) return null; - - var backingStore = new Dictionary(StringComparer.OrdinalIgnoreCase); - var backingStoreWrapper = new EntryLimitedDictionary(backingStore); - AddToBackingStore(backingStoreWrapper, string.Empty, jsonData); - return new DictionaryValueProvider(backingStore, CultureInfo.CurrentCulture); - } + var jsonData = GetDeserializedObject(controllerContext); + if (jsonData == null) + return null; - private static string MakeArrayKey(string prefix, int index) => + var backingStore = new Dictionary(StringComparer.OrdinalIgnoreCase); + var backingStoreWrapper = new EntryLimitedDictionary(backingStore); + AddToBackingStore(backingStoreWrapper, string.Empty, jsonData); + return new DictionaryValueProvider(backingStore, CultureInfo.CurrentCulture); + } + + private static string MakeArrayKey(string prefix, int index) => prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]"; private static string MakePropertyKey(string prefix, string propertyName) => string.IsNullOrEmpty(prefix) ? propertyName : prefix + "." + propertyName; - private class EntryLimitedDictionary - { - private static readonly int MaximumDepth = GetMaximumDepth(); - private readonly IDictionary _innerDictionary; - private int _itemCount; - - public EntryLimitedDictionary(IDictionary innerDictionary) => + private class EntryLimitedDictionary + { + private static readonly int MaximumDepth = GetMaximumDepth(); + private readonly IDictionary _innerDictionary; + private int _itemCount; + + public EntryLimitedDictionary(IDictionary innerDictionary) => _innerDictionary = innerDictionary; - public void Add(string key, object value) - { - if (++_itemCount > MaximumDepth) + public void Add(string key, object value) + { + if (++_itemCount > MaximumDepth) throw new InvalidOperationException("Request too large"); - _innerDictionary.Add(key, value); - } - - private static int GetMaximumDepth() - { - var appSettings = System.Configuration.ConfigurationManager.AppSettings; + _innerDictionary.Add(key, value); + } + + private static int GetMaximumDepth() + { + var appSettings = System.Configuration.ConfigurationManager.AppSettings; var valueArray = appSettings?.GetValues("aspnet:MaxJsonDeserializerMembers"); - if (valueArray == null || valueArray.Length <= 0) return 1000; + if (valueArray == null || valueArray.Length <= 0) + return 1000; return int.TryParse(valueArray[0], out var result) ? result : 1000; - } - } - } + } + } + } } diff --git a/test/iis/AspNetFullFrameworkSampleApp/Mvc/StreamResult.cs b/test/iis/AspNetFullFrameworkSampleApp/Mvc/StreamResult.cs index f5c0727d2..1ccdd3dd5 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Mvc/StreamResult.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Mvc/StreamResult.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.IO; using System.Web.Mvc; diff --git a/test/iis/AspNetFullFrameworkSampleApp/Properties/AssemblyInfo.cs b/test/iis/AspNetFullFrameworkSampleApp/Properties/AssemblyInfo.cs index 149c11ea5..895951630 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Properties/AssemblyInfo.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationSignInManager.cs b/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationSignInManager.cs index 796518d3e..c1926316c 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationSignInManager.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationSignInManager.cs @@ -1,14 +1,14 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using AspNetFullFrameworkSampleApp.Models; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; namespace AspNetFullFrameworkSampleApp.Services.Auth -{ +{ /// /// ASP.NET Identity sign in manager for this application /// diff --git a/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationUserClaimsIdentityFactory.cs b/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationUserClaimsIdentityFactory.cs index 686f9f650..c1501a6ae 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationUserClaimsIdentityFactory.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationUserClaimsIdentityFactory.cs @@ -1,15 +1,15 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Security.Claims; using System.Threading.Tasks; using AspNetFullFrameworkSampleApp.Models; using Microsoft.AspNet.Identity; namespace AspNetFullFrameworkSampleApp.Services.Auth -{ +{ /// /// ASP.NET Identity factory for creating for users of this application /// @@ -17,9 +17,9 @@ public class ApplicationUserClaimsIdentityFactory : ClaimsIdentityFactory CreateAsync(UserManager manager, ApplicationUser user, string authenticationType) { - var claimsIdentity = await base.CreateAsync(manager, user, authenticationType); - - // Add the email claim + var claimsIdentity = await base.CreateAsync(manager, user, authenticationType); + + // Add the email claim claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, user.Email)); return claimsIdentity; diff --git a/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationUserManager.cs b/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationUserManager.cs index 97ec3af0f..7b4746780 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationUserManager.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Services/Auth/ApplicationUserManager.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using AspNetFullFrameworkSampleApp.Models; using Microsoft.AspNet.Identity; @@ -10,7 +10,7 @@ using Microsoft.Owin.Security.DataProtection; namespace AspNetFullFrameworkSampleApp.Services.Auth -{ +{ /// /// ASP.NET Identity user manager for this application /// diff --git a/test/iis/AspNetFullFrameworkSampleApp/Webforms.aspx.cs b/test/iis/AspNetFullFrameworkSampleApp/Webforms.aspx.cs index dcb77a474..c44a43e37 100644 --- a/test/iis/AspNetFullFrameworkSampleApp/Webforms.aspx.cs +++ b/test/iis/AspNetFullFrameworkSampleApp/Webforms.aspx.cs @@ -1,6 +1,6 @@ using System; -using System.Web.UI; using System.Web.Mvc; +using System.Web.UI; using AspNetFullFrameworkSampleApp.Controllers; namespace AspNetFullFrameworkSampleApp @@ -13,9 +13,9 @@ protected void Page_Load(object sender, EventArgs e) { Title = RouteData.RouteHandler == null ? nameof(Webforms) - : RoutedWebforms; - - // create a Html helper to use to render links to MVC actions + : RoutedWebforms; + + // create a Html helper to use to render links to MVC actions var controllerContext = new ControllerContext(Request.RequestContext, new HomeController()); Html = new HtmlHelper( new ViewContext( diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/BodyCapturingTests.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/BodyCapturingTests.cs index f2881ce20..3cf80b85f 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/BodyCapturingTests.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/BodyCapturingTests.cs @@ -2,15 +2,15 @@ // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -using Elastic.Apm.Helpers; -using Elastic.Apm.Tests.Utilities; -using FluentAssertions; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; +using Elastic.Apm.Helpers; +using Elastic.Apm.Tests.Utilities; +using FluentAssertions; using Xunit; using Xunit.Abstractions; @@ -56,7 +56,8 @@ public async Task TextData_RequestBody_IsCaptured_And_Truncated() var pathData = SampleAppUrlPaths.HomePage; var textFragment = "just plain text ... "; var sb = new StringBuilder(); - for (var i = 0; i < RequestBodyStreamHelper.RequestBodyMaxLength; i++) sb.Append(textFragment); + for (var i = 0; i < RequestBodyStreamHelper.RequestBodyMaxLength; i++) + sb.Append(textFragment); var content = new StringContent(sb.ToString(), Encoding.UTF8, "text/plain"); await SendGetRequestToSampleAppAndVerifyResponse(pathData.Uri, pathData.StatusCode, httpContent: content); @@ -156,7 +157,8 @@ public async Task MultipartFormData_RequestBody_IsCaptured(string httpMethod) var data = $"just some test data in the file"; var bytes = Encoding.UTF8.GetBytes(data); - using (var stream = new FileStream(tempFile.Path, FileMode.OpenOrCreate, FileAccess.Write)) stream.Write(bytes); + using (var stream = new FileStream(tempFile.Path, FileMode.OpenOrCreate, FileAccess.Write)) + stream.Write(bytes); var content = new MultipartFormDataContent { { new StreamContent(new FileStream(tempFile.Path, FileMode.Open, FileAccess.Read)), "file", "file" } diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/CaptureUserTests.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/CaptureUserTests.cs index 424842f4c..aaf42d6a2 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/CaptureUserTests.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/CaptureUserTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Linq; using System.Threading.Tasks; using AngleSharp; @@ -27,9 +27,9 @@ public async Task User_Should_Contain_Id_And_Email_When_Using_Authenticated_Clai .WithDefaultLoader() .WithDefaultCookies(); - var context = BrowsingContext.New(config); - - // register a user + var context = BrowsingContext.New(config); + + // register a user var registerUri = Consts.SampleApp.CreateUrl("/Account/Register"); var document = await context.OpenAsync(registerUri); var form = document.QuerySelector("#registerForm"); @@ -40,9 +40,9 @@ public async Task User_Should_Contain_Id_And_Email_When_Using_Authenticated_Clai Email = email, Password = password, ConfirmPassword = password - }); - - // now login + }); + + // now login var loginUri = Consts.SampleApp.CreateUrl("/Account/Login"); document = await context.OpenAsync(loginUri); form = document.QuerySelector("#loginForm"); @@ -50,12 +50,12 @@ public async Task User_Should_Contain_Id_And_Email_When_Using_Authenticated_Clai { Email = email, Password = password, - }); - - // get the home page with the logged in user - await context.OpenAsync(Consts.SampleApp.CreateUrl("/")); - - // verify that the user id and email are captured. + }); + + // get the home page with the logged in user + await context.OpenAsync(Consts.SampleApp.CreateUrl("/")); + + // verify that the user id and email are captured. await WaitAndCustomVerifyReceivedData(received => { received.Transactions.Count.Should().BeGreaterThan(0); @@ -66,9 +66,9 @@ public async Task User_Should_Contain_Id_And_Email_When_Using_Authenticated_Clai transaction.Context.User.Should().NotBeNull(); transaction.Context.User.UserName.Should().Be(email); - transaction.Context.User.Email.Should().Be(email); - - // id is autogenerated in SQLite so we don't know what it'll be, only that it's populated + transaction.Context.User.Email.Should().Be(email); + + // id is autogenerated in SQLite so we don't know what it'll be, only that it's populated transaction.Context.User.Id.Should().NotBeNullOrEmpty(); }); } diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/CentralConfigTests.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/CentralConfigTests.cs index f903e6591..8b7171ebf 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/CentralConfigTests.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/CentralConfigTests.cs @@ -61,53 +61,53 @@ public MaxSpansAndSampleRateTests(ITestOutputHelper xUnitOutputHelper) : base(xU switch (CurrentXunitTest.TestCase.TestMethod.Method.Name) { case nameof(MaxSpans_valid_value): - { - CurrentXunitTest.TestCase.TestMethodArguments.Length.Should().Be(1); - var transactionMaxSpansLocalConfig = (int?)CurrentXunitTest.TestCase.TestMethodArguments[0]; - if (transactionMaxSpansLocalConfig.HasValue) - EnvVarsToSetForSampleAppPool[TransactionMaxSpans.ToEnvironmentVariable()] = transactionMaxSpansLocalConfig.ToString(); - break; - } + { + CurrentXunitTest.TestCase.TestMethodArguments.Length.Should().Be(1); + var transactionMaxSpansLocalConfig = (int?)CurrentXunitTest.TestCase.TestMethodArguments[0]; + if (transactionMaxSpansLocalConfig.HasValue) + EnvVarsToSetForSampleAppPool[TransactionMaxSpans.ToEnvironmentVariable()] = transactionMaxSpansLocalConfig.ToString(); + break; + } case nameof(SampleRate_valid_value): - { - CurrentXunitTest.TestCase.TestMethodArguments.Length.Should().Be(1); - var transactionSampleRateLocalConfig = (bool?)CurrentXunitTest.TestCase.TestMethodArguments[0]; - if (transactionSampleRateLocalConfig.HasValue) { - EnvVarsToSetForSampleAppPool[TransactionSampleRate.ToEnvironmentVariable()] = - transactionSampleRateLocalConfig.Value ? "1" : "0"; + CurrentXunitTest.TestCase.TestMethodArguments.Length.Should().Be(1); + var transactionSampleRateLocalConfig = (bool?)CurrentXunitTest.TestCase.TestMethodArguments[0]; + if (transactionSampleRateLocalConfig.HasValue) + { + EnvVarsToSetForSampleAppPool[TransactionSampleRate.ToEnvironmentVariable()] = + transactionSampleRateLocalConfig.Value ? "1" : "0"; + } + break; } - break; - } case nameof(Combination_of_both_options): - { - CurrentXunitTest.TestCase.TestMethodArguments.Length.Should().Be(2); - var transactionMaxSpansLocalConfig = (int?)CurrentXunitTest.TestCase.TestMethodArguments[0]; - var transactionSampleRateLocalConfig = (bool?)CurrentXunitTest.TestCase.TestMethodArguments[1]; - if (transactionMaxSpansLocalConfig.HasValue) - EnvVarsToSetForSampleAppPool[TransactionMaxSpans.ToEnvironmentVariable()] = transactionMaxSpansLocalConfig.ToString(); - if (transactionSampleRateLocalConfig.HasValue) { - EnvVarsToSetForSampleAppPool[TransactionSampleRate.ToEnvironmentVariable()] = - transactionSampleRateLocalConfig.Value ? "1" : "0"; + CurrentXunitTest.TestCase.TestMethodArguments.Length.Should().Be(2); + var transactionMaxSpansLocalConfig = (int?)CurrentXunitTest.TestCase.TestMethodArguments[0]; + var transactionSampleRateLocalConfig = (bool?)CurrentXunitTest.TestCase.TestMethodArguments[1]; + if (transactionMaxSpansLocalConfig.HasValue) + EnvVarsToSetForSampleAppPool[TransactionMaxSpans.ToEnvironmentVariable()] = transactionMaxSpansLocalConfig.ToString(); + if (transactionSampleRateLocalConfig.HasValue) + { + EnvVarsToSetForSampleAppPool[TransactionSampleRate.ToEnvironmentVariable()] = + transactionSampleRateLocalConfig.Value ? "1" : "0"; + } + break; } - break; - } case nameof(SampleRate_invalid_value): - { - EnvVarsToSetForSampleAppPool[TransactionSampleRate.ToEnvironmentVariable()] = "0"; - break; - } + { + EnvVarsToSetForSampleAppPool[TransactionSampleRate.ToEnvironmentVariable()] = "0"; + break; + } case nameof(MaxSpans_invalid_value): - { - EnvVarsToSetForSampleAppPool[TransactionMaxSpans.ToEnvironmentVariable()] = - MaxSpansLocalConfigForInvalidValueTest.ToString(); - break; - } + { + EnvVarsToSetForSampleAppPool[TransactionMaxSpans.ToEnvironmentVariable()] = + MaxSpansLocalConfigForInvalidValueTest.ToString(); + break; + } } } @@ -265,7 +265,8 @@ async Task SendRequestAssertReceivedData(int maxSpans, bool isSampled, int spans // Relies on srcPageData.TransactionsCount.Should().Be(1); AssertReceivedDataSampledStatus(receivedData, isSampled, pageData.SpansCount); - if (isSampled) receivedData.Transactions.First().SpanCount.Dropped.Should().Be(spansToExecCount - pageData.SpansCount); + if (isSampled) + receivedData.Transactions.First().SpanCount.Dropped.Should().Be(spansToExecCount - pageData.SpansCount); for (var i = 0; i < receivedData.Spans.Count; i++) { @@ -305,7 +306,8 @@ internal ConfigStateC(IApmLogger logger) { lock (_lock) { - if (waitUntilNextRequest.HasValue) _waitUntilNextRequest = waitUntilNextRequest.Value; + if (waitUntilNextRequest.HasValue) + _waitUntilNextRequest = waitUntilNextRequest.Value; // ReSharper disable once UseDeconstructionOnParameter optionsToUpdate.ForEach(optToUpdate => { diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/HttpContextCurrentExecutionSegmentsContainerTests.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/HttpContextCurrentExecutionSegmentsContainerTests.cs index 66b87db8f..d2d07f582 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/HttpContextCurrentExecutionSegmentsContainerTests.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/HttpContextCurrentExecutionSegmentsContainerTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Globalization; @@ -32,9 +32,9 @@ public async Task Transaction_And_Spans_Captured_When_Large_Request() .Select(i => new CreateSampleDataViewModel { Name = $"Sample {i}" }); var json = JsonConvert.SerializeObject(samples); - var bytes = Encoding.UTF8.GetByteCount(json); - - // larger than 20Kb + var bytes = Encoding.UTF8.GetByteCount(json); + + // larger than 20Kb bytes.Should().BeGreaterThan(20_000); var content = new StringContent(json, Encoding.UTF8, "application/json"); @@ -95,9 +95,9 @@ static HttpRequestMessage CreateMessage(int i) var count = 9; var messages = Enumerable.Range(1, count) .Select(i => CreateMessage(i)) - .ToList(); - - // infinite timespan + .ToList(); + + // infinite timespan var client = new HttpClient { Timeout = TimeSpan.FromMilliseconds(-1) }; var tasks = new List>(messages.Count); @@ -129,9 +129,9 @@ static HttpRequestMessage CreateMessage(int i) .Where(t => t.Name == "GET Home/About") .ToList(); - aboutTransactions.Should().HaveCount(count); - - // assert that each aboutTransaction is a child of a span associated with a contactTransaction + aboutTransactions.Should().HaveCount(count); + + // assert that each aboutTransaction is a child of a span associated with a contactTransaction foreach (var contactTransaction in contactTransactions) { contactTransaction.ParentId.Should().BeNull(); diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/IisAdministration.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/IisAdministration.cs index e65f39a83..a45d90d0b 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/IisAdministration.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/IisAdministration.cs @@ -192,7 +192,8 @@ internal void DisposeSampleApp() { using var serverManager = new ServerManager(); var existingAppPool = serverManager.ApplicationPools[SampleApp.AppPoolName]; - if (existingAppPool != null) ChangeAppPoolStateTo(existingAppPool, ObjectState.Stopped); + if (existingAppPool != null) + ChangeAppPoolStateTo(existingAppPool, ObjectState.Stopped); var site = serverManager.Sites[SampleApp.SiteName]; var existingApp = site.Applications[SampleApp.RootUrlPath]; @@ -234,7 +235,8 @@ StartMode startMode SampleApp.AppPoolName, sampleAppShouldUseHighPrivilegedAccount); var applicationPool = serverManager.ApplicationPools[SampleApp.AppPoolName]; - if (applicationPool != null) serverManager.ApplicationPools.Remove(applicationPool); + if (applicationPool != null) + serverManager.ApplicationPools.Remove(applicationPool); applicationPool = serverManager.ApplicationPools.Add(SampleApp.AppPoolName); applicationPool.ManagedPipelineMode = ManagedPipelineMode.Integrated; @@ -289,7 +291,8 @@ private void AddSampleApp(ServerManager serverManager) _logger.Debug()?.Log("Adding application {IisApp}...", SampleApp.RootUrlPath); var site = serverManager.Sites[SampleApp.SiteName]; var application = site.Applications[SampleApp.RootUrlPath]; - if (application != null) site.Applications.Remove(application); + if (application != null) + site.Applications.Remove(application); var appPath = Path.Combine(SolutionRoot.FullName, SampleApp.SrcDirPathRelativeToSolutionRoot); application = site.Applications.Add(SampleApp.RootUrlPath, appPath); @@ -461,14 +464,16 @@ private void AddEnvVarsForSampleAppPool(ServerManager serverManager, Dictionary< { var o = element.GetAttributeValue(keyValues[i]); string value = null; - if (o != null) value = o.ToString(); + if (o != null) + value = o.ToString(); if (!string.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase)) { matches = false; break; } } - if (matches) return element; + if (matches) + return element; } } return null; @@ -506,7 +511,8 @@ internal void LogIisApplicationHostConfig() interestingLines.Add(line); } _logger.Debug()?.Log("Found {NumberOfLines} interesting lines in IIS config file `{FilePath}'", interestingLines.Count, filePath); - foreach (var line in interestingLines) _logger.Debug()?.Log("{Line}", TextUtils.Indent(line)); + foreach (var line in interestingLines) + _logger.Debug()?.Log("{Line}", TextUtils.Indent(line)); } } diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/LabelsTests.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/LabelsTests.cs index 9923a31b7..05e862b3f 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/LabelsTests.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/LabelsTests.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Xunit; diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/SampleRate0Tests.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/SampleRate0Tests.cs index e190be4b3..e8fd8fbe1 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/SampleRate0Tests.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/SampleRate0Tests.cs @@ -15,7 +15,8 @@ namespace Elastic.Apm.AspNetFullFramework.Tests public class SampleRate0Tests : TestsBase { public SampleRate0Tests(ITestOutputHelper xUnitOutputHelper) : base(xUnitOutputHelper, - envVarsToSetForSampleAppPool: new Dictionary { { TransactionSampleRate.ToEnvironmentVariable(), "0" } }) { } + envVarsToSetForSampleAppPool: new Dictionary { { TransactionSampleRate.ToEnvironmentVariable(), "0" } }) + { } [AspNetFullFrameworkTheory] [MemberData(nameof(AllSampleAppUrlPaths))] diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/Soap/SoapRequestTests.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/Soap/SoapRequestTests.cs index 7105f2d02..f2ac4c589 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/Soap/SoapRequestTests.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/Soap/SoapRequestTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Linq; using System.Net.Http; using System.Net.Http.Headers; @@ -18,8 +18,8 @@ namespace Elastic.Apm.AspNetFullFramework.Tests.Soap public class SoapRequestTests : TestsBase { public SoapRequestTests(ITestOutputHelper xUnitOutputHelper) - : base(xUnitOutputHelper) { } - + : base(xUnitOutputHelper) { } + /// /// Tests that the reading of the input stream to get the action name for a SOAP 1.2 request /// does not cause an exception to be thrown when the framework deserializes the input stream diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TestsBase.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TestsBase.cs index d43a6db14..460185d4b 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TestsBase.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TestsBase.cs @@ -83,7 +83,8 @@ public class TestsBase : LoggingTestBase, IAsyncLifetime EnvVarsToSetForSampleAppPool.TryAdd(ServerUrls.ToEnvironmentVariable(), BuildApmServerUrl(_mockApmServerPort)); EnvVarsToSetForSampleAppPool.TryAdd(SpanCompressionEnabled.ToEnvironmentVariable(), "false"); - if (_sampleAppLogEnabled) EnvVarsToSetForSampleAppPool.TryAdd(LoggingConfig.LogFileEnvVarName, _sampleAppLogFilePath); + if (_sampleAppLogEnabled) + EnvVarsToSetForSampleAppPool.TryAdd(LoggingConfig.LogFileEnvVarName, _sampleAppLogFilePath); EnvVarsToSetForSampleAppPool.TryAdd(FlushInterval.ToEnvironmentVariable(), "10ms"); } @@ -145,7 +146,7 @@ internal static class SampleAppUrlPaths new SampleAppUrlPathData("Asmx/Health.asmx", (int)HttpStatusCode.OK); internal static readonly SampleAppUrlPathData ChildHttpSpanWithResponseForbiddenPage = - new SampleAppUrlPathData(HomeController.ChildHttpSpanWithResponseForbiddenPath, 200, transactionsCount:2, spansCount: 1, errorsCount: 0); + new SampleAppUrlPathData(HomeController.ChildHttpSpanWithResponseForbiddenPath, 200, transactionsCount: 2, spansCount: 1, errorsCount: 0); /// @@ -229,7 +230,8 @@ public async Task DisposeAsync() ?.Log("Not tearing down IIS sample application and pool because {Reason}", TearDownPersistentDataReason); } - if (_startMockApmServer) await MockApmServer.StopAsync(); + if (_startMockApmServer) + await MockApmServer.StopAsync(); _logger.Info()?.Log("Finished test: {FullUnitTestName}", TestDisplayName); } @@ -496,16 +498,21 @@ private async Task PostTestFailureDiagnostics() private void FindReceivedDataWithTimestampEarlierThanTestStart() { - foreach (var error in MockApmServer.ReceivedData.Errors) AnalyzeDtoTimestamp(error.Timestamp, error); - foreach (var metricSet in MockApmServer.ReceivedData.Metrics) AnalyzeDtoTimestamp(metricSet.Timestamp, metricSet); - foreach (var span in MockApmServer.ReceivedData.Spans) AnalyzeDtoTimestamp(span.Timestamp, span); - foreach (var transaction in MockApmServer.ReceivedData.Transactions) AnalyzeDtoTimestamp(transaction.Timestamp, transaction); + foreach (var error in MockApmServer.ReceivedData.Errors) + AnalyzeDtoTimestamp(error.Timestamp, error); + foreach (var metricSet in MockApmServer.ReceivedData.Metrics) + AnalyzeDtoTimestamp(metricSet.Timestamp, metricSet); + foreach (var span in MockApmServer.ReceivedData.Spans) + AnalyzeDtoTimestamp(span.Timestamp, span); + foreach (var transaction in MockApmServer.ReceivedData.Transactions) + AnalyzeDtoTimestamp(transaction.Timestamp, transaction); void AnalyzeDtoTimestamp(long dtoTimestamp, object dto) { var dtoStartTime = TimeUtils.ToDateTime(dtoTimestamp); - if (_testStartTime <= dtoStartTime) return; + if (_testStartTime <= dtoStartTime) + return; _logger.Warning() ?.Log("The following DTO received from the agent has timestamp that is earlier than the current test start time. " + @@ -566,11 +573,16 @@ internal void VerifySpanNameTypeSubtypeAction(SpanDto span, string spanPrefix) private void FullFwAssertValid(ReceivedData receivedData) { - foreach (var error in receivedData.Errors) FullFwAssertValid(error); - foreach (var metadata in receivedData.Metadata) FullFwAssertValid(metadata); - foreach (var metricSet in receivedData.Metrics) FullFwAssertValid(metricSet); - foreach (var span in receivedData.Spans) FullFwAssertValid(span); - foreach (var transaction in receivedData.Transactions) FullFwAssertValid(transaction); + foreach (var error in receivedData.Errors) + FullFwAssertValid(error); + foreach (var metadata in receivedData.Metadata) + FullFwAssertValid(metadata); + foreach (var metricSet in receivedData.Metrics) + FullFwAssertValid(metricSet); + foreach (var span in receivedData.Spans) + FullFwAssertValid(span); + foreach (var transaction in receivedData.Transactions) + FullFwAssertValid(transaction); } private void FullFwAssertValid(MetadataDto metadata) @@ -624,7 +636,8 @@ private void FullFwAssertValid(ErrorDto error) { FullFwAssertValid((ITimestampedDto)error); error.Transaction.AssertValid(); - if (error.Context != null) FullFwAssertValid(error.Context, error); + if (error.Context != null) + FullFwAssertValid(error.Context, error); error.Culprit.NonEmptyAssertValid(); error.Exception.AssertValid(); } @@ -633,7 +646,8 @@ private void FullFwAssertValid(TransactionDto transaction) { transaction.Should().NotBeNull(); - if (transaction.Context != null) FullFwAssertValid(transaction.Context, transaction); + if (transaction.Context != null) + FullFwAssertValid(transaction.Context, transaction); transaction.Name.Should().NotBeNull(); TransactionResultFullFwAssertValid(transaction.Result); transaction.Type.Should().Be(ApiConstants.TypeRequest); @@ -645,7 +659,8 @@ private void FullFwAssertValid(ITimestampedDto timestampedDto) { timestampedDto.Should().NotBeNull(); - if (_sampleAppClientCallTiming != null) timestampedDto.ShouldOccurBetween(_sampleAppClientCallTiming); + if (_sampleAppClientCallTiming != null) + timestampedDto.ShouldOccurBetween(_sampleAppClientCallTiming); } private void FullFwAssertValid(ITimedDto timedDto) @@ -654,7 +669,8 @@ private void FullFwAssertValid(ITimedDto timedDto) timedDto.Duration.Should().BeGreaterOrEqualTo(0); - if (_sampleAppClientCallTiming != null) timedDto.ShouldOccurBetween(_sampleAppClientCallTiming); + if (_sampleAppClientCallTiming != null) + timedDto.ShouldOccurBetween(_sampleAppClientCallTiming); } private static void FullFwAssertValid(Url url) @@ -692,7 +708,8 @@ private void FullFwAssertValid(SpanDto span) span.Should().NotBeNull(); FullFwAssertValid((ITimedDto)span); - if (span.StackTrace != null) FullFwAssertValid(span.StackTrace); + if (span.StackTrace != null) + FullFwAssertValid(span.StackTrace); } private static void FullFwAssertValid(IEnumerable stackTrace) @@ -793,7 +810,8 @@ protected void AssertReceivedDataSampledStatus(ReceivedData receivedData, bool i if (isSampled) { transaction.Context.Should().NotBeNull(); - if (expectedSpanCount.HasValue) transaction.SpanCount.Started.Should().Be(expectedSpanCount.Value); + if (expectedSpanCount.HasValue) + transaction.SpanCount.Started.Should().Be(expectedSpanCount.Value); } else { diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TestsEnabledDetector.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TestsEnabledDetector.cs index eed4b0f24..d6f1785ce 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TestsEnabledDetector.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TestsEnabledDetector.cs @@ -31,7 +31,8 @@ internal static class TestsEnabledDetector private static string DetectReasonWhyTestsAreSkipped() { - if (!TestEnvironment.IsWindows) return $"{ReasonPrefix} OS is not Windows. {ReasonSuffix}"; + if (!TestEnvironment.IsWindows) + return $"{ReasonPrefix} OS is not Windows. {ReasonSuffix}"; if (!CheckIisVersion(out var reason)) return $"{ReasonPrefix} {reason}. {ReasonSuffix}"; diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TransactionIgnoreUrlsTest.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TransactionIgnoreUrlsTest.cs index 1d27faaea..879a00faa 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TransactionIgnoreUrlsTest.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TransactionIgnoreUrlsTest.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -21,7 +21,8 @@ public TransactionIgnoreUrlsTest(ITestOutputHelper xUnitOutputHelper) envVarsToSetForSampleAppPool: new Dictionary { { TransactionIgnoreUrls.ToEnvironmentVariable(), "/home" } - }) { } + }) + { } [AspNetFullFrameworkFact] public async Task Test() diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TransactionNameTests.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TransactionNameTests.cs index 5202d79d0..7bd1596be 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TransactionNameTests.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/TransactionNameTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Linq; using System.Net.Http; using System.Net.Http.Headers; diff --git a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/WebApiTests.cs b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/WebApiTests.cs index 694b2e24e..69e3f797b 100644 --- a/test/iis/Elastic.Apm.AspNetFullFramework.Tests/WebApiTests.cs +++ b/test/iis/Elastic.Apm.AspNetFullFramework.Tests/WebApiTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.IO; using System.Net.Http; using System.Threading.Tasks; @@ -16,9 +16,9 @@ namespace Elastic.Apm.AspNetFullFramework.Tests [Collection(Consts.AspNetFullFrameworkTestsCollection)] public class WebApiTests : TestsBase { - public WebApiTests(ITestOutputHelper xUnitOutputHelper) : base(xUnitOutputHelper) { } - - // https://github.com/elastic/apm-agent-dotnet/issues/1113 + public WebApiTests(ITestOutputHelper xUnitOutputHelper) : base(xUnitOutputHelper) { } + + // https://github.com/elastic/apm-agent-dotnet/issues/1113 [AspNetFullFrameworkFact] public async Task MultipartData_Should_Not_Throw() { diff --git a/test/instrumentations/Elastic.Apm.Docker.Tests/BasicDockerTests.cs b/test/instrumentations/Elastic.Apm.Docker.Tests/BasicDockerTests.cs index 5a234410b..4ab535d02 100644 --- a/test/instrumentations/Elastic.Apm.Docker.Tests/BasicDockerTests.cs +++ b/test/instrumentations/Elastic.Apm.Docker.Tests/BasicDockerTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/instrumentations/Elastic.Apm.Docker.Tests/ContainerIdCalculationTests.cs b/test/instrumentations/Elastic.Apm.Docker.Tests/ContainerIdCalculationTests.cs index eb1bf7b9a..43e673b76 100644 --- a/test/instrumentations/Elastic.Apm.Docker.Tests/ContainerIdCalculationTests.cs +++ b/test/instrumentations/Elastic.Apm.Docker.Tests/ContainerIdCalculationTests.cs @@ -37,7 +37,8 @@ public class ContainerIdCalculationTests "b15a5bdedd2e7645c3be271364324321b908314e4c77857bbfd32a041148c07f")] public void TestCGroupContent(string cGroupContent, string expectedContainerId) { - if (!File.Exists("/proc/self/cgroup")) return; //only run in Docker - this check can be improved + if (!File.Exists("/proc/self/cgroup")) + return; //only run in Docker - this check can be improved var noopLogger = new NoopLogger(); var systemInfoHelper = new TestSystemInfoHelper(noopLogger, cGroupContent); @@ -51,7 +52,8 @@ public void TestCGroupContent(string cGroupContent, string expectedContainerId) [Fact] public void TestCGroupContentWithInvalidData() { - if (!File.Exists("/proc/self/cgroup")) return; //only run in Docker - this check can be improved + if (!File.Exists("/proc/self/cgroup")) + return; //only run in Docker - this check can be improved var noopLogger = new NoopLogger(); var systemInfoHelper = new TestSystemInfoHelper(noopLogger, "asdf:invalid-dockerid:243543"); diff --git a/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/ElasticsearchFixture.cs b/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/ElasticsearchFixture.cs index 7ee821aa5..b5f418dcf 100644 --- a/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/ElasticsearchFixture.cs +++ b/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/ElasticsearchFixture.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; using Testcontainers.Elasticsearch; using Xunit; diff --git a/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/ElasticsearchTests.cs b/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/ElasticsearchTests.cs index f042a6202..a5f114b19 100644 --- a/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/ElasticsearchTests.cs +++ b/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/ElasticsearchTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Threading.Tasks; using Elastic.Apm.Api; @@ -31,7 +31,7 @@ public ElasticsearchTests(ElasticsearchFixture fixture) public async Task Elasticsearch_Span_Does_Not_Have_Http_Child_Span() { var payloadSender = new MockPayloadSender(); - using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender, configuration: new MockConfiguration(exitSpanMinDuration:"0", spanCompressionEnabled: "false")))) + using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender, configuration: new MockConfiguration(exitSpanMinDuration: "0", spanCompressionEnabled: "false")))) using (agent.Subscribe(new ElasticsearchDiagnosticsSubscriber(), new HttpDiagnosticsSubscriber())) { var searchResponse = await agent.Tracer.CaptureTransaction("Call Client", ApiConstants.ActionExec, diff --git a/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/TraceContextTests.cs b/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/TraceContextTests.cs index 9a6f7c466..150b4a4f7 100644 --- a/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/TraceContextTests.cs +++ b/test/instrumentations/Elastic.Apm.Elasticsearch.Tests/TraceContextTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using Elastic.Apm.Api; using Elastic.Apm.DiagnosticSource; @@ -32,7 +32,7 @@ public void Call_to_Elasticsearch_propagates_Trace_Context_when_HttpDiagnosticsS context.Response.StatusCode = 200; }); - using var agent = new ApmAgent(new TestAgentComponents(payloadSender: new MockPayloadSender(), configuration: new MockConfiguration(exitSpanMinDuration:"0", spanCompressionEnabled: "false"))); + using var agent = new ApmAgent(new TestAgentComponents(payloadSender: new MockPayloadSender(), configuration: new MockConfiguration(exitSpanMinDuration: "0", spanCompressionEnabled: "false"))); using var subscribe = agent.Subscribe(new ElasticsearchDiagnosticsSubscriber(), new HttpDiagnosticsSubscriber()); var client = new ElasticLowLevelClient(new ConnectionConfiguration(new Uri(localServer.Uri))); diff --git a/test/instrumentations/Elastic.Apm.EntityFrameworkCore.Tests/ExternalDbTests.cs b/test/instrumentations/Elastic.Apm.EntityFrameworkCore.Tests/ExternalDbTests.cs index 6bd7128eb..88ff2e755 100644 --- a/test/instrumentations/Elastic.Apm.EntityFrameworkCore.Tests/ExternalDbTests.cs +++ b/test/instrumentations/Elastic.Apm.EntityFrameworkCore.Tests/ExternalDbTests.cs @@ -73,7 +73,8 @@ public class ExternalDbTests : LoggingTestBase foreach (var externalDbType in PotentialExternalDbTypes) { var connectionDetails = GetConnectionDetails(externalDbType); - if (connectionDetails == null) continue; + if (connectionDetails == null) + continue; isAtLeastOneExternalDbConfigured = true; yield return (externalDbType, connectionDetails); } @@ -89,7 +90,8 @@ public class ExternalDbTests : LoggingTestBase [MemberData(nameof(ConfiguredExternalDbVariants))] public void Context_Destination_from_Db(ExternalDbType externalDbType, ConnectionDetails connectionDetails) { - if (connectionDetails == null) return; + if (connectionDetails == null) + return; var mockPayloadSender = new MockPayloadSender(); using (var agent = new ApmAgent(new AgentComponents(payloadSender: mockPayloadSender))) @@ -117,7 +119,8 @@ private static ConnectionDetails GetConnectionDetails(ExternalDbType externalDbT { var envVarName = "ELASTIC_APM_TESTS_" + externalDbType.EnvVarNameMiddlePart + "_" + envVarSuffixToConnectionProperty.Key; var envVarValue = Environment.GetEnvironmentVariable(envVarName); - if (envVarValue == null) return null; + if (envVarValue == null) + return null; envVarSuffixToConnectionProperty.Value(connectionDetails, envVarValue); } @@ -126,7 +129,7 @@ private static ConnectionDetails GetConnectionDetails(ExternalDbType externalDbT private static void ExecuteTestCrudSequence(Func dbContextFactory) { - using(var dbContext = dbContextFactory()) + using (var dbContext = dbContextFactory()) { dbContext.Database.EnsureDeleted(); dbContext.Database.EnsureCreated(); @@ -137,7 +140,7 @@ private static void ExecuteTestCrudSequence(Func dbContextFac // Publisher publisher; Book book1; - using(var dbContext = dbContextFactory()) + using (var dbContext = dbContextFactory()) { publisher = new Publisher { Name = "Mariner Books" }; dbContext.Publishers.Add(publisher); @@ -149,7 +152,7 @@ private static void ExecuteTestCrudSequence(Func dbContextFac // // Read data and verify // - using(var dbContext = dbContextFactory()) + using (var dbContext = dbContextFactory()) { var publishers = dbContext.Publishers; var books = dbContext.Books; @@ -167,7 +170,7 @@ private static void ExecuteTestCrudSequence(Func dbContextFac // Update some data // Book book2; - using(var dbContext = dbContextFactory()) + using (var dbContext = dbContextFactory()) { book2 = new Book { ISBN = "978-0547247762", Title = "The Sealed Letter", Publisher = dbContext.Publishers.First() }; dbContext.Books.Add(book2); @@ -177,7 +180,7 @@ private static void ExecuteTestCrudSequence(Func dbContextFac // // Read data and verify // - using(var dbContext = dbContextFactory()) + using (var dbContext = dbContextFactory()) { var publishers = dbContext.Publishers; var books = dbContext.Books; @@ -194,7 +197,7 @@ private static void ExecuteTestCrudSequence(Func dbContextFac // // Delete some data // - using(var dbContext = dbContextFactory()) + using (var dbContext = dbContextFactory()) { dbContext.Books.Remove(book1); dbContext.SaveChanges(); @@ -203,7 +206,7 @@ private static void ExecuteTestCrudSequence(Func dbContextFac // // Read data and verify // - using(var dbContext = dbContextFactory()) + using (var dbContext = dbContextFactory()) { var publishers = dbContext.Publishers; var books = dbContext.Books; diff --git a/test/instrumentations/Elastic.Apm.SqlClient.Tests/SqlServerCollection.cs b/test/instrumentations/Elastic.Apm.SqlClient.Tests/SqlServerCollection.cs index da0369229..eb69a8c94 100644 --- a/test/instrumentations/Elastic.Apm.SqlClient.Tests/SqlServerCollection.cs +++ b/test/instrumentations/Elastic.Apm.SqlClient.Tests/SqlServerCollection.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Xunit; namespace Elastic.Apm.SqlClient.Tests diff --git a/test/instrumentations/Elastic.Apm.SqlClient.Tests/SqlServerFixture.cs b/test/instrumentations/Elastic.Apm.SqlClient.Tests/SqlServerFixture.cs index d3740e9d7..0699d4185 100644 --- a/test/instrumentations/Elastic.Apm.SqlClient.Tests/SqlServerFixture.cs +++ b/test/instrumentations/Elastic.Apm.SqlClient.Tests/SqlServerFixture.cs @@ -1,15 +1,15 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; using Testcontainers.MsSql; using Xunit; namespace Elastic.Apm.SqlClient.Tests -{ - // ReSharper disable once ClassNeverInstantiated.Global - it's used as a generic parameter +{ + // ReSharper disable once ClassNeverInstantiated.Global - it's used as a generic parameter public sealed class SqlServerFixture : IAsyncLifetime { private readonly MsSqlContainer _container = new MsSqlBuilder().Build(); diff --git a/test/instrumentations/Elastic.Apm.StackExchange.Redis.Tests/ConnectionMultiplexerExtensionTests.cs b/test/instrumentations/Elastic.Apm.StackExchange.Redis.Tests/ConnectionMultiplexerExtensionTests.cs index 68c642900..080372149 100644 --- a/test/instrumentations/Elastic.Apm.StackExchange.Redis.Tests/ConnectionMultiplexerExtensionTests.cs +++ b/test/instrumentations/Elastic.Apm.StackExchange.Redis.Tests/ConnectionMultiplexerExtensionTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using Moq; using StackExchange.Redis; using StackExchange.Redis.Profiling; diff --git a/test/instrumentations/Elastic.Apm.StackExchange.Redis.Tests/ProfilingSessionTests.cs b/test/instrumentations/Elastic.Apm.StackExchange.Redis.Tests/ProfilingSessionTests.cs index eacd0228b..35e10cb93 100644 --- a/test/instrumentations/Elastic.Apm.StackExchange.Redis.Tests/ProfilingSessionTests.cs +++ b/test/instrumentations/Elastic.Apm.StackExchange.Redis.Tests/ProfilingSessionTests.cs @@ -1,16 +1,16 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Linq; using System.Threading.Tasks; using Elastic.Apm.Api; using Elastic.Apm.Tests.Utilities; using Elastic.Apm.Tests.Utilities.XUnit; -using StackExchange.Redis; using FluentAssertions; +using StackExchange.Redis; using Testcontainers.Redis; namespace Elastic.Apm.StackExchange.Redis.Tests @@ -51,10 +51,10 @@ public async Task Capture_Redis_Commands_On_Transaction() await database.StringSetAsync($"string{i}", i); await database.StringGetAsync($"string{i}"); await database.StringSetAsync($"string{i}", i); - await database.StringGetAsync($"string{i}"); - - // fire and forget commands may not end up being captured before transaction end is - // called and profiling session is finished + await database.StringGetAsync($"string{i}"); + + // fire and forget commands may not end up being captured before transaction end is + // called and profiling session is finished await database.StringSetAsync($"string{i}", i, flags: CommandFlags.FireAndForget); await database.StringGetAsync($"string{i}", CommandFlags.FireAndForget); }); @@ -102,17 +102,17 @@ public async Task Capture_Redis_Commands_On_Span() for (var i = 0; i < transactionCount; i++) { await agent.Tracer.CaptureTransaction($"transaction {i}", ApiConstants.TypeDb, async t => - { - // span 1 - await database.StringSetAsync($"string{i}", i); - - // span 2 - await database.StringGetAsync($"string{i}"); - - // span 3 + { + // span 1 + await database.StringSetAsync($"string{i}", i); + + // span 2 + await database.StringGetAsync($"string{i}"); + + // span 3 await t.CaptureSpan($"parent span {i}", ApiConstants.TypeDb, async () => - { - // spans 4,5,6,7 + { + // spans 4,5,6,7 await database.StringSetAsync($"string{i}", i); await database.StringGetAsync($"string{i}"); await database.StringSetAsync($"string{i}", i); diff --git a/test/instrumentations/Elastic.Clients.Elasticsearch.Tests/ElasticsearchTests.cs b/test/instrumentations/Elastic.Clients.Elasticsearch.Tests/ElasticsearchTests.cs index ed1aed660..355ff74ab 100644 --- a/test/instrumentations/Elastic.Clients.Elasticsearch.Tests/ElasticsearchTests.cs +++ b/test/instrumentations/Elastic.Clients.Elasticsearch.Tests/ElasticsearchTests.cs @@ -1,4 +1,4 @@ -using Elastic.Apm; +using Elastic.Apm; using Elastic.Apm.Api; using Elastic.Apm.DiagnosticSource; using Elastic.Apm.Elasticsearch; @@ -111,7 +111,8 @@ public async Task UpdateDocumentTest() var tweet = response.Source; tweet.Should().NotBeNull(); - if (tweet == null) return; + if (tweet == null) + return; var (payloadSender, apmAgent) = SetUpAgent(); @@ -195,7 +196,10 @@ private async Task IndexData() { var tweet = new Tweet { - Id = 1, User = "stevejgordon", PostDate = new DateTime(2009, 11, 15), Message = "Trying out the client, so far so good?" + Id = 1, + User = "stevejgordon", + PostDate = new DateTime(2009, 11, 15), + Message = "Trying out the client, so far so good?" }; var response = await _client.IndexAsync(tweet, request => request.Index("my-tweet-index")); diff --git a/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/GrpcTests.cs b/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/GrpcTests.cs index 6a768821c..23272cfff 100644 --- a/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/GrpcTests.cs +++ b/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/GrpcTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; diff --git a/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/SampleAppHostBuilder.cs b/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/SampleAppHostBuilder.cs index f96b788fa..679105e8f 100644 --- a/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/SampleAppHostBuilder.cs +++ b/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/SampleAppHostBuilder.cs @@ -1,4 +1,4 @@ -using Elastic.Apm.AspNetCore; +using Elastic.Apm.AspNetCore; using Elastic.Apm.Grpc.Tests.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -18,7 +18,8 @@ public void ConfigureServices(IServiceCollection services) // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { - if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); + if (env.IsDevelopment()) + app.UseDeveloperExceptionPage(); app.UseRouting(); diff --git a/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/Services/GreeterService.cs b/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/Services/GreeterService.cs index 46f7cdd53..fec07f55c 100644 --- a/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/Services/GreeterService.cs +++ b/test/instrumentations/grpc/Elastic.Apm.Grpc.Tests/Services/GreeterService.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Threading.Tasks; using Grpc.Core; @@ -12,8 +12,8 @@ namespace Elastic.Apm.Grpc.Tests.Services { public class GreeterService : Greeter.GreeterBase - { - // ReSharper disable once NotAccessedField.Local + { + // ReSharper disable once NotAccessedField.Local private readonly ILogger _logger; public GreeterService(ILogger logger) => _logger = logger; diff --git a/test/instrumentations/grpc/GrpcClientSample/Program.cs b/test/instrumentations/grpc/GrpcClientSample/Program.cs index 37e1ee57c..0feba772c 100644 --- a/test/instrumentations/grpc/GrpcClientSample/Program.cs +++ b/test/instrumentations/grpc/GrpcClientSample/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using Elastic.Apm; using Elastic.Apm.DiagnosticSource; diff --git a/test/instrumentations/grpc/GrpcServiceSample/Startup.cs b/test/instrumentations/grpc/GrpcServiceSample/Startup.cs index 16af8c914..25d59ca32 100644 --- a/test/instrumentations/grpc/GrpcServiceSample/Startup.cs +++ b/test/instrumentations/grpc/GrpcServiceSample/Startup.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -16,7 +16,8 @@ public void ConfigureServices(IServiceCollection services) // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { - if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); + if (env.IsDevelopment()) + app.UseDeveloperExceptionPage(); app.UseRouting(); diff --git a/test/integrations/Elastic.Apm.AspNetCore.Static.Tests/ConfigTests.cs b/test/integrations/Elastic.Apm.AspNetCore.Static.Tests/ConfigTests.cs index b5dd2f95f..e1f601e6c 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Static.Tests/ConfigTests.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Static.Tests/ConfigTests.cs @@ -43,14 +43,17 @@ public async Task AgentDisabledInAppConfig(bool withDiagnosticSourceOnly) using var localServer = LocalServer.Create("http://localhost:8200/", context => { - if (context.Request.HttpMethod != HttpMethod.Post.Method) return; + if (context.Request.HttpMethod != HttpMethod.Post.Method) + return; var body = new StreamReader(context.Request.InputStream).ReadToEnd(); - if (context.Request.HttpMethod.Equals(HttpMethod.Post.Method, StringComparison.OrdinalIgnoreCase)) return; + if (context.Request.HttpMethod.Equals(HttpMethod.Post.Method, StringComparison.OrdinalIgnoreCase)) + return; // In CI with parallel tests running we could have multiple tests running and some of them may send HTTP post to the default server url // So we only make the test fail, when the request body contains the sample app's url - if (body.ToLower().Contains("starttransactionwithagentapi")) defaultServerUrlConnectionMade = true; + if (body.ToLower().Contains("starttransactionwithagentapi")) + defaultServerUrlConnectionMade = true; }); var configReader = new ApmConfiguration(new ConfigurationBuilder() diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/AspNetCoreBasicTests.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/AspNetCoreBasicTests.cs index 3d8966697..6dc274ae5 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/AspNetCoreBasicTests.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/AspNetCoreBasicTests.cs @@ -161,7 +161,7 @@ public async Task HomeIndexTransactionWithEnabledFalse(bool withDiagnosticSource { _agent = new ApmAgent(new TestAgentComponents( _logger, - new MockConfiguration(_logger, enabled: "false", exitSpanMinDuration:"0"), _capturedPayload)); + new MockConfiguration(_logger, enabled: "false", exitSpanMinDuration: "0"), _capturedPayload)); _client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, _agent, _factory); @@ -381,7 +381,8 @@ public async Task HomeIndexAutoCapturedSpansAreChildrenOfControllerActionAsSpan( } var httpSpans = spans.Where(span => span.Context.Http != null); httpSpans.Should().NotBeEmpty(); - foreach (var httpSpan in httpSpans) httpSpan.ParentId.Should().Be(controllerActionSpan.Id); + foreach (var httpSpan in httpSpans) + httpSpan.ParentId.Should().Be(controllerActionSpan.Id); // ReSharper restore PossibleMultipleEnumeration } diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/AspNetCoreDiagnosticListenerTest.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/AspNetCoreDiagnosticListenerTest.cs index 7d444e0dc..d0dd798e0 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/AspNetCoreDiagnosticListenerTest.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/AspNetCoreDiagnosticListenerTest.cs @@ -43,7 +43,7 @@ public class AspNetCoreDiagnosticListenerTest : IClassFixturef__AnonymousType0`2[ Microsoft.AspNetCore.Http.HttpContext, System.Exception ]'.' var capturedPayload = new MockPayloadSender(); - using ( var agent = new ApmAgent(new TestAgentComponents(payloadSender: capturedPayload, configuration: new MockConfiguration(exitSpanMinDuration: "0"))) ) + using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: capturedPayload, configuration: new MockConfiguration(exitSpanMinDuration: "0")))) { // Based on Helper GetClient var builder = _factory @@ -159,7 +159,7 @@ public async Task CaptureDiagnosticAndHostingUnhandledExceptionEvent() n.ConfigureServices(Helper.ConfigureServices); }); - var client = builder.CreateClient(); + var client = builder.CreateClient(); // Hits case Microsoft.AspNetCore.Diagnostics.UnhandledException // Exception handled by UseDeveloperExceptionPage @@ -173,7 +173,7 @@ public async Task CaptureDiagnosticAndHostingUnhandledExceptionEvent() // Hits case Microsoft.AspNetCore.Hosting.UnhandledException Func act = async () => await client.GetAsync("/Home/TriggerError?skipUseDeveloperExceptionPage=true"); - ( await act.Should().ThrowAsync() ).WithMessage("This is a test exception!"); + (await act.Should().ThrowAsync()).WithMessage("This is a test exception!"); capturedPayload?.WaitForTransactions(); capturedPayload?.Transactions.Should().ContainSingle(); diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/BodyCapturingTests.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/BodyCapturingTests.cs index e3f94ae22..16858aba5 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/BodyCapturingTests.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/BodyCapturingTests.cs @@ -285,7 +285,9 @@ private static IEnumerable BuildOptionsTestVariants() { yield return new OptionsTestVariant { - CaptureBody = captureBody, CaptureBodyContentTypes = captureBodyContentTypes, IsSampled = isSampled + CaptureBody = captureBody, + CaptureBodyContentTypes = captureBodyContentTypes, + IsSampled = isSampled }; } } @@ -352,10 +354,13 @@ await BuildOptionsTestVariants() bool ShouldRequestBodyBeCaptured(IConfigurationReader configSnapshot, bool isError) { - if (!configSnapshot.CaptureBodyContentTypes.Contains(MyCustomContentType)) return false; + if (!configSnapshot.CaptureBodyContentTypes.Contains(MyCustomContentType)) + return false; - if (configSnapshot.CaptureBody.Equals(ConfigConsts.SupportedValues.CaptureBodyOff)) return false; - if (configSnapshot.CaptureBody.Equals(ConfigConsts.SupportedValues.CaptureBodyAll)) return true; + if (configSnapshot.CaptureBody.Equals(ConfigConsts.SupportedValues.CaptureBodyOff)) + return false; + if (configSnapshot.CaptureBody.Equals(ConfigConsts.SupportedValues.CaptureBodyAll)) + return true; return isError || configSnapshot.CaptureBody.Equals(ConfigConsts.SupportedValues.CaptureBodyTransactions); } @@ -385,7 +390,7 @@ async Task TestBodyCapture(string body, bool isError, bool shouldRequestBodyBeCa { capturedRequestBody = transaction.Context.Request.Body; - capturedRequestBody.Should().Be(shouldRequestBodyBeCaptured ? body : Elastic.Apm.Consts.Redacted); + capturedRequestBody.Should().Be(shouldRequestBodyBeCaptured ? body : Elastic.Apm.Consts.Redacted); } @@ -417,7 +422,8 @@ async Task TestBodyCapture(string body, bool isError, bool shouldRequestBodyBeCa private SutEnv StartSutEnv(IConfiguration startConfiguration = null) { - if (_sutEnv != null) return _sutEnv; + if (_sutEnv != null) + return _sutEnv; _sutEnv = new SutEnv(startConfiguration); return _sutEnv; @@ -454,7 +460,7 @@ internal SutEnv(IConfiguration startConfiguration = null) _taskForSampleApp = Program.CreateWebHostBuilder(null) .ConfigureServices(services => { - services.Configure(_ => { }); + services.Configure(_ => { }); Startup.ConfigureServicesExceptMvc(services); services.AddMvc() diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/CaptureUserTest.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/CaptureUserTest.cs index 2a395332f..78a2ae602 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/CaptureUserTest.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/CaptureUserTest.cs @@ -36,7 +36,7 @@ private void SetUpSut() var unused = Program.CreateWebHostBuilder(null) .Configure(app => { - _agent = new ApmAgent(new TestAgentComponents(payloadSender: _payloadSender, configuration: new MockConfiguration(exitSpanMinDuration:"0"))); + _agent = new ApmAgent(new TestAgentComponents(payloadSender: _payloadSender, configuration: new MockConfiguration(exitSpanMinDuration: "0"))); app.UseElasticApm(_agent, _agent.Logger); Startup.ConfigureAllExceptAgent(app); }) diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/DiagnosticListenerTests.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/DiagnosticListenerTests.cs index f84e5c07b..e7ff435c1 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/DiagnosticListenerTests.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/DiagnosticListenerTests.cs @@ -28,7 +28,7 @@ public class DiagnosticListenerTests : IClassFixture factory) { - _agent = new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(exitSpanMinDuration:"0"))); + _agent = new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(exitSpanMinDuration: "0"))); _capturedPayload = _agent.PayloadSender as MockPayloadSender; //This registers the middleware without activating any listeners, diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/FailedRequestTests.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/FailedRequestTests.cs index fdb0a8dce..68fa4afee 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/FailedRequestTests.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/FailedRequestTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information @@ -30,7 +30,7 @@ public class FailedRequestTests : IAsyncLifetime public Task InitializeAsync() { - _agent1 = new ApmAgent(new TestAgentComponents(payloadSender: _payloadSender1, configuration: new MockConfiguration(exitSpanMinDuration:"0"))); + _agent1 = new ApmAgent(new TestAgentComponents(payloadSender: _payloadSender1, configuration: new MockConfiguration(exitSpanMinDuration: "0"))); _taskForApp1 = Program.CreateWebHostBuilder(null) .ConfigureServices(services => diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/SanitizeFieldNamesTests.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/SanitizeFieldNamesTests.cs index 92b088275..67910bf68 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/SanitizeFieldNamesTests.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/SanitizeFieldNamesTests.cs @@ -145,14 +145,16 @@ public static IEnumerable GetData(Tests test) if (Environment.Version.Major < 7) { var newItem = new List(); - foreach (var item in testDataItem) newItem.Add(item); + foreach (var item in testDataItem) + newItem.Add(item); newItem.Add(true); retVal.Add(newItem.ToArray()); } { var newItem = new List(); - foreach (var item in testDataItem) newItem.Add(item); + foreach (var item in testDataItem) + newItem.Add(item); newItem.Add(false); retVal.Add(newItem.ToArray()); @@ -194,7 +196,8 @@ public async Task CustomSanitizeFieldNameSettingWithHeaders(string sanitizeField { CreateAgent(useOnlyDiagnosticSource, sanitizeFieldNames); - foreach (var header in headerNames) _client.DefaultRequestHeaders.Add(header, "123"); + foreach (var header in headerNames) + _client.DefaultRequestHeaders.Add(header, "123"); await _client.GetAsync("/Home/SimplePage"); diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/TraceIdWithActivityTests.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/TraceIdWithActivityTests.cs index 3b8eed553..b226c5146 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/TraceIdWithActivityTests.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/TraceIdWithActivityTests.cs @@ -11,8 +11,8 @@ using Elastic.Apm.Tests.Utilities.XUnit; using FluentAssertions; using Microsoft.AspNetCore.Mvc.Testing; -using Xunit; using SampleAspNetCoreApp; +using Xunit; namespace Elastic.Apm.AspNetCore.Tests { diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/TransactionIgnoreUrlsTest.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/TransactionIgnoreUrlsTest.cs index 37a27af4d..4f48f9f69 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/TransactionIgnoreUrlsTest.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/TransactionIgnoreUrlsTest.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/integrations/Elastic.Apm.AspNetCore.Tests/TransactionQueueTests.cs b/test/integrations/Elastic.Apm.AspNetCore.Tests/TransactionQueueTests.cs index c9b7b4f0b..ad2fd6574 100644 --- a/test/integrations/Elastic.Apm.AspNetCore.Tests/TransactionQueueTests.cs +++ b/test/integrations/Elastic.Apm.AspNetCore.Tests/TransactionQueueTests.cs @@ -33,7 +33,8 @@ public void WeakReferenceTest() GC.Collect(); Thread.Sleep(10); GC.Collect(); - foreach (var unused in listener.ProcessingRequests) { } + foreach (var unused in listener.ProcessingRequests) + { } listener.ProcessingRequests.Count().Should().Be(0); } diff --git a/test/integrations/Elastic.Apm.Extensions.Hosting.Tests/HostBuilderExtensionTests.cs b/test/integrations/Elastic.Apm.Extensions.Hosting.Tests/HostBuilderExtensionTests.cs index de95a0bff..5adcc5b4c 100644 --- a/test/integrations/Elastic.Apm.Extensions.Hosting.Tests/HostBuilderExtensionTests.cs +++ b/test/integrations/Elastic.Apm.Extensions.Hosting.Tests/HostBuilderExtensionTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using Elastic.Apm.DiagnosticSource; using FluentAssertions; diff --git a/test/integrations/Elastic.Apm.Extensions.Logging.Tests/CaptureApmErrorsTests.cs b/test/integrations/Elastic.Apm.Extensions.Logging.Tests/CaptureApmErrorsTests.cs index 64aa62f4e..cae863cab 100644 --- a/test/integrations/Elastic.Apm.Extensions.Logging.Tests/CaptureApmErrorsTests.cs +++ b/test/integrations/Elastic.Apm.Extensions.Logging.Tests/CaptureApmErrorsTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/integrations/Elastic.Apm.StaticExplicitInitialization.Tests/StaticImplicitInitializationTests.cs b/test/integrations/Elastic.Apm.StaticExplicitInitialization.Tests/StaticImplicitInitializationTests.cs index 89f1541d2..04f11cad1 100644 --- a/test/integrations/Elastic.Apm.StaticExplicitInitialization.Tests/StaticImplicitInitializationTests.cs +++ b/test/integrations/Elastic.Apm.StaticExplicitInitialization.Tests/StaticImplicitInitializationTests.cs @@ -1,4 +1,4 @@ -using Elastic.Apm.Logging; +using Elastic.Apm.Logging; using Elastic.Apm.Tests.Utilities; using FluentAssertions; using Xunit; diff --git a/test/integrations/Elastic.Apm.StaticImplicitInitialization.Tests/ImplicitInitializationTests.cs b/test/integrations/Elastic.Apm.StaticImplicitInitialization.Tests/ImplicitInitializationTests.cs index 5dae16894..0b2d67c89 100644 --- a/test/integrations/Elastic.Apm.StaticImplicitInitialization.Tests/ImplicitInitializationTests.cs +++ b/test/integrations/Elastic.Apm.StaticImplicitInitialization.Tests/ImplicitInitializationTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/integrations/applications/SampleAspNetCoreApp/Areas/MyArea/Controllers/HomeController.cs b/test/integrations/applications/SampleAspNetCoreApp/Areas/MyArea/Controllers/HomeController.cs index 915b99db4..b989ac75b 100644 --- a/test/integrations/applications/SampleAspNetCoreApp/Areas/MyArea/Controllers/HomeController.cs +++ b/test/integrations/applications/SampleAspNetCoreApp/Areas/MyArea/Controllers/HomeController.cs @@ -1,16 +1,16 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Microsoft.AspNetCore.Mvc; namespace SampleAspNetCoreApp.Areas.MyArea.Controllers { [Area("MyArea")] public class HomeController : Controller - { - // GET + { + // GET public IActionResult Index() => View(); } } diff --git a/test/integrations/applications/SampleAspNetCoreApp/Areas/MyOtherArea/Controllers/HomeController.cs b/test/integrations/applications/SampleAspNetCoreApp/Areas/MyOtherArea/Controllers/HomeController.cs index b96810cbb..d9d6cb56b 100644 --- a/test/integrations/applications/SampleAspNetCoreApp/Areas/MyOtherArea/Controllers/HomeController.cs +++ b/test/integrations/applications/SampleAspNetCoreApp/Areas/MyOtherArea/Controllers/HomeController.cs @@ -1,16 +1,16 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Microsoft.AspNetCore.Mvc; namespace SampleAspNetCoreApp.Areas.MyOtherArea.Controllers { [Area("MyOtherArea")] public class HomeController : Controller - { - // GET + { + // GET public IActionResult Index() => View(); } } diff --git a/test/integrations/applications/SampleAspNetCoreApp/Controllers/HomeController.cs b/test/integrations/applications/SampleAspNetCoreApp/Controllers/HomeController.cs index 1b4dfac37..e701b6ed7 100644 --- a/test/integrations/applications/SampleAspNetCoreApp/Controllers/HomeController.cs +++ b/test/integrations/applications/SampleAspNetCoreApp/Controllers/HomeController.cs @@ -1,7 +1,7 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Diagnostics; @@ -41,9 +41,9 @@ private bool GetCaptureControllerActionAsSpanFromQueryString() throw new ArgumentException($"{captureControllerActionAsSpanQueryStringKey} query string key should have at most one value" + $", instead it's values: {captureControllerActionAsSpanQueryStringValues}", captureControllerActionAsSpanQueryStringKey); - } - - // ReSharper disable once SimplifyConditionalTernaryExpression + } + + // ReSharper disable once SimplifyConditionalTernaryExpression return captureControllerActionAsSpanQueryStringValues.Count == 0 ? false : bool.Parse(captureControllerActionAsSpanQueryStringValues[0]); } @@ -72,8 +72,8 @@ private bool GetCaptureControllerActionAsSpanFromQueryString() } return View(model); - }); - + }); + /// /// In order to test if relationship between spans is maintained correctly by the agent, /// this method has the ability to start a span by passing `captureControllerActionAsSpan` = `true` to it. @@ -83,8 +83,8 @@ private bool GetCaptureControllerActionAsSpanFromQueryString() [HttpPost] public Task AddSampleData(IFormCollection formFields) { - var captureControllerActionAsSpanAsString = formFields["captureControllerActionAsSpan"]; - // ReSharper disable once SimplifyConditionalTernaryExpression + var captureControllerActionAsSpanAsString = formFields["captureControllerActionAsSpan"]; + // ReSharper disable once SimplifyConditionalTernaryExpression var captureControllerActionAsSpan = string.IsNullOrEmpty(captureControllerActionAsSpanAsString) ? false : bool.Parse(captureControllerActionAsSpanAsString); @@ -105,7 +105,8 @@ public Task AddSampleData(IFormCollection formFields) private static Task SafeCaptureSpan(bool captureControllerActionAsSpan, string spanName, string spanType, Func> spanBody) { - if (!captureControllerActionAsSpan || Agent.Tracer.CurrentTransaction == null) return spanBody(); + if (!captureControllerActionAsSpan || Agent.Tracer.CurrentTransaction == null) + return spanBody(); return (Agent.Tracer.CurrentSpan ?? (IExecutionSegment)Agent.Tracer.CurrentTransaction).CaptureSpan(spanName, spanType, spanBody); } @@ -142,8 +143,8 @@ public async Task ChartPage() { var csvDataReader = new CsvDataReader($"Data{Path.DirectorySeparatorChar}HistoricalData"); - var historicalData = - // ReSharper disable once StringLiteralTypo + var historicalData = + // ReSharper disable once StringLiteralTypo await Agent.Tracer.CurrentTransaction.CaptureSpan("ReadData", "csvRead", async () => await csvDataReader.GetHistoricalQuotes("ESTC")); return View(historicalData); @@ -164,11 +165,12 @@ public async Task FailingOutGoingHttpCall() public IActionResult TriggerError() { - if (Agent.Tracer.CurrentTransaction != null) Agent.Tracer.CurrentTransaction.SetLabel("foo", "bar"); + if (Agent.Tracer.CurrentTransaction != null) + Agent.Tracer.CurrentTransaction.SetLabel("foo", "bar"); throw new Exception("This is a test exception!"); - } - - //Used as test for optional route parameters + } + + //Used as test for optional route parameters public IActionResult Sample(int id) => Ok(id); [HttpPost] @@ -191,7 +193,8 @@ public async Task Stream() public IActionResult TransactionWithCustomName() { - if (Agent.Tracer.CurrentTransaction != null) Agent.Tracer.CurrentTransaction.Name = "custom"; + if (Agent.Tracer.CurrentTransaction != null) + Agent.Tracer.CurrentTransaction.Name = "custom"; return Ok(); } @@ -203,7 +206,8 @@ public IActionResult TransactionWithDbCallAndCustomSpan() var model = _sampleDataContext.SampleTable.Select(item => item.Name).ToList(); var str = string.Join(",", model.ToArray()); - if (Agent.Tracer.CurrentTransaction != null) Agent.Tracer.CurrentTransaction.CaptureSpan("SampleSpan", "PerfBenchmark", () => { }); + if (Agent.Tracer.CurrentTransaction != null) + Agent.Tracer.CurrentTransaction.CaptureSpan("SampleSpan", "PerfBenchmark", () => { }); return Ok(str); } @@ -219,8 +223,8 @@ public async Task VeryAsyncCall() { await T1(); return Ok(); - } - + } + /// /// Used for testing the agent with `enabled=false` through appsettings.json /// @@ -230,7 +234,8 @@ public IActionResult StartTransactionWithAgentApi() var isTransactionWithValidTraceIdCreated = false; Agent.Tracer.CaptureTransaction("a", "b", t => { - if (!string.IsNullOrEmpty(t.TraceId)) isTransactionWithValidTraceIdCreated = true; + if (!string.IsNullOrEmpty(t.TraceId)) + isTransactionWithValidTraceIdCreated = true; }); return Ok(isTransactionWithValidTraceIdCreated); } @@ -262,16 +267,16 @@ private async Task T3() [HttpPost] [Route("api/Home/PostError")] - public ActionResult PostError() => throw new Exception("This is a post method test exception!"); - + public ActionResult PostError() => throw new Exception("This is a post method test exception!"); + /// /// Test for: https://github.com/elastic/apm-agent-dotnet/issues/460 /// /// A parameter with a little bit more complex data type coming through the request body /// HTTP200 if the parameter is available in the method (aka not null), HTTP500 otherwise [HttpPost("api/Home/Send")] - public IActionResult Send([FromBody] BaseReportFilter filter) => filter == null ? StatusCode(500) : Ok(); - + public IActionResult Send([FromBody] BaseReportFilter filter) => filter == null ? StatusCode(500) : Ok(); + /// /// A test case to make sure that setting manually is not overwritten by auto instrumentation. /// @@ -286,8 +291,8 @@ public ActionResult SampleWithManuallySettingOutcome() [HttpGet] [Route("api/Home/ReturnNotFound/{id}")] - public ActionResult ReturnNotFound(int id) => NotFound(); - + public ActionResult ReturnNotFound(int id) => NotFound(); + /// /// From: https://github.com/elastic/apm-agent-dotnet/issues/1571#issuecomment-984520076 /// diff --git a/test/integrations/applications/SampleAspNetCoreApp/Data/SampleData.cs b/test/integrations/applications/SampleAspNetCoreApp/Data/SampleData.cs index 9655002f8..79518ccbc 100644 --- a/test/integrations/applications/SampleAspNetCoreApp/Data/SampleData.cs +++ b/test/integrations/applications/SampleAspNetCoreApp/Data/SampleData.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/integrations/applications/SampleAspNetCoreApp/Data/SampleDataContext.cs b/test/integrations/applications/SampleAspNetCoreApp/Data/SampleDataContext.cs index e4d1bd612..635412086 100644 --- a/test/integrations/applications/SampleAspNetCoreApp/Data/SampleDataContext.cs +++ b/test/integrations/applications/SampleAspNetCoreApp/Data/SampleDataContext.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/integrations/applications/SampleAspNetCoreApp/Migrations/20190402111620_InitDbWithAuthentication.cs b/test/integrations/applications/SampleAspNetCoreApp/Migrations/20190402111620_InitDbWithAuthentication.cs index 84317480d..4b7417e2e 100644 --- a/test/integrations/applications/SampleAspNetCoreApp/Migrations/20190402111620_InitDbWithAuthentication.cs +++ b/test/integrations/applications/SampleAspNetCoreApp/Migrations/20190402111620_InitDbWithAuthentication.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/integrations/applications/SampleAspNetCoreApp/Program.cs b/test/integrations/applications/SampleAspNetCoreApp/Program.cs index 1909fbe93..7273ecfc6 100644 --- a/test/integrations/applications/SampleAspNetCoreApp/Program.cs +++ b/test/integrations/applications/SampleAspNetCoreApp/Program.cs @@ -1,7 +1,7 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; diff --git a/test/integrations/applications/SampleAspNetCoreApp/Startup.cs b/test/integrations/applications/SampleAspNetCoreApp/Startup.cs index bb3b2e198..c9fb25bf5 100644 --- a/test/integrations/applications/SampleAspNetCoreApp/Startup.cs +++ b/test/integrations/applications/SampleAspNetCoreApp/Startup.cs @@ -1,7 +1,7 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using Elastic.Apm.NetCoreAll; using Microsoft.AspNetCore.Builder; @@ -10,21 +10,21 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using SampleAspNetCoreApp.Data; +using SampleAspNetCoreApp.Data; #if NET5_0 using OpenTelemetry; using OpenTelemetry.Trace; #endif - + namespace SampleAspNetCoreApp { public class Startup { public Startup(IConfiguration configuration) => Configuration = configuration; - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ConfigureServicesExceptMvc(services); @@ -41,21 +41,21 @@ public static void ConfigureServicesExceptMvc(IServiceCollection services) .AddEntityFrameworkStores(); services.Configure(options => - { - // Password settings - // Not meant for production! To make testing/playing with the sample app we use very simple, - // but insecure settings + { + // Password settings + // Not meant for production! To make testing/playing with the sample app we use very simple, + // but insecure settings options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 5; }); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. #if NET6_0_OR_GREATER - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) #else public void Configure(IApplicationBuilder app, IHostingEnvironment env) #endif @@ -77,7 +77,7 @@ public static void ConfigureAllExceptAgent(IApplicationBuilder app) } public static void ConfigureRoutingAndMvc(IApplicationBuilder app) - { + { #if NETCOREAPP3_0 || NETCOREAPP3_1 || NET5_0_OR_GREATER app.UseRouting(); @@ -97,7 +97,7 @@ public static void ConfigureRoutingAndMvc(IApplicationBuilder app) "{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllers(); endpoints.MapRazorPages(); - }); + }); #else app.UseAuthentication(); diff --git a/test/integrations/applications/SampleAspNetCoreApp/Utils/CpuBurner.cs b/test/integrations/applications/SampleAspNetCoreApp/Utils/CpuBurner.cs index 08a496c64..f4c716e3f 100644 --- a/test/integrations/applications/SampleAspNetCoreApp/Utils/CpuBurner.cs +++ b/test/integrations/applications/SampleAspNetCoreApp/Utils/CpuBurner.cs @@ -28,7 +28,8 @@ public static void ConsumeMultipleCores(int threads, int percentage, Cancellatio // ReSharper disable once UnusedMethodReturnValue.Local private static long ConsumeSingleCore(int percentage, CancellationToken cancellationToken) { - if (percentage < 0 || percentage > 100) throw new ArgumentException(nameof(percentage)); + if (percentage < 0 || percentage > 100) + throw new ArgumentException(nameof(percentage)); var iterations = 0L; var watch = new Stopwatch(); @@ -39,7 +40,8 @@ private static long ConsumeSingleCore(int percentage, CancellationToken cancella // remaining percentage milliseconds. So 40% utilization means work 40ms and sleep 60ms if (watch.ElapsedMilliseconds > percentage) { - if (percentage != 100) Thread.Sleep(100 - percentage); + if (percentage != 100) + Thread.Sleep(100 - percentage); watch.Reset(); watch.Start(); diff --git a/test/integrations/applications/SampleConsoleNetCoreApp/HostedService.cs b/test/integrations/applications/SampleConsoleNetCoreApp/HostedService.cs index a5664e1a2..1db3ccde0 100644 --- a/test/integrations/applications/SampleConsoleNetCoreApp/HostedService.cs +++ b/test/integrations/applications/SampleConsoleNetCoreApp/HostedService.cs @@ -32,14 +32,16 @@ public class HostedService : IHostedService { _logger.LogError("Yet another sample error log"); - using (_logger.BeginScope("bar")) _logger.LogError("And a 3. sample error log"); + using (_logger.BeginScope("bar")) + _logger.LogError("And a 3. sample error log"); } using var fooScope = _logger.BeginScope("foo"); // Make sure Agent.Tracer.CurrentTransaction is not null var currentTransaction = Agent.Tracer.CurrentTransaction; - if (currentTransaction == null) throw new Exception("Agent.Tracer.CurrentTransaction returns null"); + if (currentTransaction == null) + throw new Exception("Agent.Tracer.CurrentTransaction returns null"); var httpClient = new HttpClient(); return await httpClient.GetAsync("https://elastic.co", cancellationToken); diff --git a/test/integrations/applications/SampleConsoleNetCoreApp/Program.cs b/test/integrations/applications/SampleConsoleNetCoreApp/Program.cs index 985944299..b51d0cae1 100644 --- a/test/integrations/applications/SampleConsoleNetCoreApp/Program.cs +++ b/test/integrations/applications/SampleConsoleNetCoreApp/Program.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using Elastic.Apm.DiagnosticSource; using Elastic.Apm.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; diff --git a/test/integrations/applications/WebApiSample/Controllers/ValuesController.cs b/test/integrations/applications/WebApiSample/Controllers/ValuesController.cs index 84d8c2253..e1cf65a9c 100644 --- a/test/integrations/applications/WebApiSample/Controllers/ValuesController.cs +++ b/test/integrations/applications/WebApiSample/Controllers/ValuesController.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/integrations/applications/WebApiSample/Program.cs b/test/integrations/applications/WebApiSample/Program.cs index 9fc9b5bac..18dd2a61c 100644 --- a/test/integrations/applications/WebApiSample/Program.cs +++ b/test/integrations/applications/WebApiSample/Program.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/integrations/applications/WebApiSample/Startup.cs b/test/integrations/applications/WebApiSample/Startup.cs index d9d5e5a40..7003f5185 100644 --- a/test/integrations/applications/WebApiSample/Startup.cs +++ b/test/integrations/applications/WebApiSample/Startup.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under one or more agreements. +// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/opentelemetry/Elastic.Apm.OpenTelemetry.Tests/OpenTelemetryTests.cs b/test/opentelemetry/Elastic.Apm.OpenTelemetry.Tests/OpenTelemetryTests.cs index 8121b316b..1537eb25d 100644 --- a/test/opentelemetry/Elastic.Apm.OpenTelemetry.Tests/OpenTelemetryTests.cs +++ b/test/opentelemetry/Elastic.Apm.OpenTelemetry.Tests/OpenTelemetryTests.cs @@ -5,12 +5,12 @@ using System.Diagnostics; using Elastic.Apm.Api; -using Xunit; +using Elastic.Apm.Model; using Elastic.Apm.Tests.Utilities; using Elastic.Apm.Tests.Utilities.XUnit; -using OpenTelemetrySample; using FluentAssertions; -using Elastic.Apm.Model; +using OpenTelemetrySample; +using Xunit; namespace Elastic.Apm.OpenTelemetry.Tests; @@ -38,7 +38,8 @@ public void MixApisTest1() private void AssertOnTraceIds(MockPayloadSender payloadSender) { - foreach (var span in payloadSender.Spans) span.TraceId.Should().Be(payloadSender.FirstTransaction.TraceId); + foreach (var span in payloadSender.Spans) + span.TraceId.Should().Be(payloadSender.FirstTransaction.TraceId); } [Fact] diff --git a/test/opentelemetry/OpenTelemetrySample/OTSamples.cs b/test/opentelemetry/OpenTelemetrySample/OTSamples.cs index 665e2e497..109566be6 100644 --- a/test/opentelemetry/OpenTelemetrySample/OTSamples.cs +++ b/test/opentelemetry/OpenTelemetrySample/OTSamples.cs @@ -79,22 +79,23 @@ public static void Sample4(ITracer tracer) { var src = new ActivitySource("Test"); - tracer.CaptureTransaction( nameof(Sample4), "test", _ => - { - Thread.Sleep(100); - using (src.StartActivity("foo")) - { - - tracer.CurrentSpan.CaptureSpan("ElasticApmSpan", "test", () => Thread.Sleep(50)); - Thread.Sleep(150); - } - }); + tracer.CaptureTransaction(nameof(Sample4), "test", _ => + { + Thread.Sleep(100); + using (src.StartActivity("foo")) + { + + tracer.CurrentSpan.CaptureSpan("ElasticApmSpan", "test", () => Thread.Sleep(50)); + Thread.Sleep(150); + } + }); } public static void OneSpanWithAttributes() { var src = new ActivitySource("Test"); - using (var activity = src.StartActivity("foo", ActivityKind.Server)) activity?.SetTag("foo", "bar"); + using (var activity = src.StartActivity("foo", ActivityKind.Server)) + activity?.SetTag("foo", "bar"); } public static void TwoSpansWithAttributes() @@ -103,7 +104,8 @@ public static void TwoSpansWithAttributes() using (var activity1 = src.StartActivity("foo", ActivityKind.Server)) { activity1?.SetTag("foo1", "bar1"); - using (var activity2 = src.StartActivity("bar", ActivityKind.Internal)) activity2?.SetTag("foo2", "bar2"); + using (var activity2 = src.StartActivity("bar", ActivityKind.Internal)) + activity2?.SetTag("foo2", "bar2"); } } @@ -113,10 +115,14 @@ public static void SpanKindSample() using (var _ = src.StartActivity("SpanKindSample", ActivityKind.Server)) { - using (var activity = src.StartActivity("httpSpan", ActivityKind.Client)) activity?.SetTag("http.url", "http://foo.bar"); - using (var activity = src.StartActivity("dbSpan", ActivityKind.Client)) activity?.SetTag("db.system", "mysql"); - using (var activity = src.StartActivity("grpcSpan", ActivityKind.Client)) activity?.SetTag("rpc.system", "grpc"); - using (var activity = src.StartActivity("messagingSpan", ActivityKind.Client)) activity?.SetTag("messaging.system", "rabbitmq"); + using (var activity = src.StartActivity("httpSpan", ActivityKind.Client)) + activity?.SetTag("http.url", "http://foo.bar"); + using (var activity = src.StartActivity("dbSpan", ActivityKind.Client)) + activity?.SetTag("db.system", "mysql"); + using (var activity = src.StartActivity("grpcSpan", ActivityKind.Client)) + activity?.SetTag("rpc.system", "grpc"); + using (var activity = src.StartActivity("messagingSpan", ActivityKind.Client)) + activity?.SetTag("messaging.system", "rabbitmq"); } } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/AdoNetTestData.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/AdoNetTestData.cs index 44be91ca2..19399c0ed 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/AdoNetTestData.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/AdoNetTestData.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Collections; using System.Collections.Generic; @@ -17,8 +17,8 @@ public class AdoNetTestData : IEnumerable public const string OracleProviderSpanNameStart = "DECLARE"; public IEnumerator GetEnumerator() - { - // TODO: Add x64/x86 options. macOS and Linux do not support x86 + { + // TODO: Add x64/x86 options. macOS and Linux do not support x86 yield return new object[] { "net7.0" }; yield return new object[] { "net6.0" }; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/MySqlCommandTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/MySqlCommandTests.cs index c341bf14f..87e65b860 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/MySqlCommandTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/MySqlCommandTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; @@ -55,16 +55,16 @@ public async Task CaptureAutoInstrumentedSpans(string targetFramework) null, line => _output.WriteLine(line.Line), exception => _output.WriteLine($"{exception}")); - } - - // RunAllAsync transaction - // RunBaseTypesAsync transaction - apmServer.ReceivedData.Transactions.Should().HaveCount(2); - - // The first MySqlCommand on an opened MySqlConnection executes an additional - // command that the profiler instrumentation will create a span for. Since there - // are two connections opened, 1 for RunAllAsync and 1 for RunBaseTypesAsync, - // expect 2 additional spans + } + + // RunAllAsync transaction + // RunBaseTypesAsync transaction + apmServer.ReceivedData.Transactions.Should().HaveCount(2); + + // The first MySqlCommand on an opened MySqlConnection executes an additional + // command that the profiler instrumentation will create a span for. Since there + // are two connections opened, 1 for RunAllAsync and 1 for RunBaseTypesAsync, + // expect 2 additional spans apmServer.ReceivedData.Spans.Should().HaveCount(AdoNetTestData.DbRunnerExpectedTotalSpans + 2); var genericTransaction = apmServer.ReceivedData.Transactions.FirstOrDefault(t => t.Name == "RunAllAsync"); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/MySqlFixture.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/MySqlFixture.cs index 12827c6eb..a5b689c17 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/MySqlFixture.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/MySqlFixture.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; using Testcontainers.MySql; using Xunit; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/NpgSqlCommandTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/NpgSqlCommandTests.cs index 3f7734390..ce59bfe87 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/NpgSqlCommandTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/NpgSqlCommandTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; @@ -31,11 +31,11 @@ public NpgSqlCommandTests(PostgreSqlFixture fixture, ITestOutputHelper output) public static IEnumerable TestParameters { get - { - // use the version defined in NpgsqlSample - var npgSqlVersion = "5.0.7"; - - // TODO: Add x64/x86 options. macOS and Linux do not support x86 + { + // use the version defined in NpgsqlSample + var npgSqlVersion = "5.0.7"; + + // TODO: Add x64/x86 options. macOS and Linux do not support x86 yield return new object[] { "net7.0", npgSqlVersion }; if (TestEnvironment.IsWindows) diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqlCommandTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqlCommandTests.cs index 3a5d1c5e0..fcd46ad4a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqlCommandTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqlCommandTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqlServerFixture.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqlServerFixture.cs index d850cbe4e..22cb999d4 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqlServerFixture.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqlServerFixture.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; using Testcontainers.MsSql; using Xunit; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqliteCommandTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqliteCommandTests.cs index 7697740d6..e88820bd9 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqliteCommandTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/AdoNet/SqliteCommandTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; @@ -21,11 +21,11 @@ public class SqliteCommandTests public SqliteCommandTests(ITestOutputHelper output) => _output = output; - [DisabledTestFact("Sometimes fails in CI with `Expected apmServer.ReceivedData.Transactions to contain 2 item(s), but found 0.`")] - //[ClassData(typeof(AdoNetTestData))] + [DisabledTestFact("Sometimes fails in CI with `Expected apmServer.ReceivedData.Transactions to contain 2 item(s), but found 0.`")] + //[ClassData(typeof(AdoNetTestData))] public async Task CaptureAutoInstrumentedSpans() { - string targetFramework = null; // TODO: this is a parameter, but was moved due to DisabledTestFact + string targetFramework = null; // TODO: this is a parameter, but was moved due to DisabledTestFact var apmLogger = new InMemoryBlockingLogger(Elastic.Apm.Logging.LogLevel.Error); var apmServer = new MockApmServer(apmLogger, nameof(CaptureAutoInstrumentedSpans)); var port = apmServer.FindAvailablePortToListen(); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Continuations/TaskContinuationGeneratorTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Continuations/TaskContinuationGeneratorTests.cs index b83a577d3..4c0148e52 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Continuations/TaskContinuationGeneratorTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Continuations/TaskContinuationGeneratorTests.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Threading; using System.Threading.Tasks; @@ -39,13 +39,13 @@ async Task GetPreviousTask() [Fact] public async Task ExceptionTest() { - Exception ex = null; - - // Normal + Exception ex = null; + + // Normal ex = await Assert.ThrowsAsync(() => GetPreviousTask()); - Assert.Equal("Internal Test Exception", ex.Message); - - // Using the continuation + Assert.Equal("Internal Test Exception", ex.Message); + + // Using the continuation var tcg = new TaskContinuationGenerator(); ex = await Assert.ThrowsAsync(() => tcg.SetContinuation(this, GetPreviousTask(), null, CallTargetState.GetDefault())); Assert.Equal("Internal Test Exception", ex.Message); @@ -59,13 +59,13 @@ async Task GetPreviousTask() [Fact] public async Task CancelledTest() - { - // Normal + { + // Normal var task = GetPreviousTask(); await Assert.ThrowsAsync(() => task); - Assert.Equal(TaskStatus.Canceled, task.Status); - - // Using the continuation + Assert.Equal(TaskStatus.Canceled, task.Status); + + // Using the continuation var tcg = new TaskContinuationGenerator(); task = tcg.SetContinuation(this, GetPreviousTask(), null, CallTargetState.GetDefault()); await Assert.ThrowsAsync(() => task); @@ -104,13 +104,13 @@ async Task GetPreviousTask() [Fact] public async Task ExceptionGenericTest() { - Exception ex = null; - - // Normal + Exception ex = null; + + // Normal ex = await Assert.ThrowsAsync(() => GetPreviousTask()); - Assert.Equal("Internal Test Exception", ex.Message); - - // Using the continuation + Assert.Equal("Internal Test Exception", ex.Message); + + // Using the continuation var tcg = new TaskContinuationGenerator, bool>(); ex = await Assert.ThrowsAsync(() => tcg.SetContinuation(this, GetPreviousTask(), null, CallTargetState.GetDefault())); Assert.Equal("Internal Test Exception", ex.Message); @@ -124,13 +124,13 @@ async Task GetPreviousTask() [Fact] public async Task CancelledGenericTest() - { - // Normal + { + // Normal var task = GetPreviousTask(); await Assert.ThrowsAsync(() => task); - Assert.Equal(TaskStatus.Canceled, task.Status); - - // Using the continuation + Assert.Equal(TaskStatus.Canceled, task.Status); + + // Using the continuation var tcg = new TaskContinuationGenerator, bool>(); task = tcg.SetContinuation(this, GetPreviousTask(), null, CallTargetState.GetDefault()); await Assert.ThrowsAsync(() => task); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Continuations/ValueTaskContinuationGeneratorTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Continuations/ValueTaskContinuationGeneratorTests.cs index 68ed4b4a6..1e7dffc8e 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Continuations/ValueTaskContinuationGeneratorTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Continuations/ValueTaskContinuationGeneratorTests.cs @@ -1,12 +1,12 @@ -// Licensed to Elasticsearch B.V under the Apache 2.0 License. -// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under the Apache 2.0 License. +// Elasticsearch B.V licenses this file, including any modifications, to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + #if NET6_0_OR_GREATER using System; using System.Threading; @@ -39,13 +39,13 @@ async ValueTask GetPreviousTask() [Fact] public async Task ExceptionTest() { - Exception ex = null; - - // Normal + Exception ex = null; + + // Normal ex = await Assert.ThrowsAsync(() => GetPreviousTask().AsTask()); - Assert.Equal("Internal Test Exception", ex.Message); - - // Using the continuation + Assert.Equal("Internal Test Exception", ex.Message); + + // Using the continuation var tcg = new ValueTaskContinuationGenerator(); ex = await Assert.ThrowsAsync(() => tcg.SetContinuation(this, GetPreviousTask(), null, CallTargetState.GetDefault()).AsTask()); @@ -60,13 +60,13 @@ async ValueTask GetPreviousTask() [Fact] public async Task CancelledTest() - { - // Normal + { + // Normal var task = GetPreviousTask(); await Assert.ThrowsAsync(() => task.AsTask()); - Assert.True(task.IsCanceled); - - // Using the continuation + Assert.True(task.IsCanceled); + + // Using the continuation task = GetPreviousTask(); var tcg = new ValueTaskContinuationGenerator(); await Assert.ThrowsAsync(() => tcg.SetContinuation(this, task, null, CallTargetState.GetDefault()).AsTask()); @@ -108,13 +108,13 @@ async ValueTask GetPreviousTask() [Fact] public async Task ExceptionGenericTest() { - Exception ex = null; - - // Normal + Exception ex = null; + + // Normal ex = await Assert.ThrowsAsync(() => GetPreviousTask().AsTask()); - Assert.Equal("Internal Test Exception", ex.Message); - - // Using the continuation + Assert.Equal("Internal Test Exception", ex.Message); + + // Using the continuation var tcg = new ValueTaskContinuationGenerator, bool>(); ex = await Assert.ThrowsAsync(() => @@ -130,13 +130,13 @@ async ValueTask GetPreviousTask() [Fact] public async Task CancelledGenericTest() - { - // Normal + { + // Normal var task = GetPreviousTask(); await Assert.ThrowsAsync(() => task.AsTask()); - Assert.True(task.IsCanceled); - - // Using the continuation + Assert.True(task.IsCanceled); + + // Using the continuation task = GetPreviousTask(); var tcg = new ValueTaskContinuationGenerator, bool>(); @@ -172,5 +172,5 @@ public CustomCancellationException(CancellationToken token) : base(token) { } } } -} +} #endif diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckExplicitInterfaceTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckExplicitInterfaceTests.cs index bbff601ee..5ac7277e3 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckExplicitInterfaceTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckExplicitInterfaceTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; using FluentAssertions; using Xunit; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckIgnoreTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckIgnoreTests.cs index f029e50bd..b4bf781ba 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckIgnoreTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckIgnoreTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; using Xunit; @@ -23,8 +23,8 @@ public void NonPublicStructCopyTest() Assert.Equal((int)instance.Value, (int)copy.Value); Assert.Equal(ValuesDuckType.Third.ToString(), copy.GetValue()); Assert.Equal(ValuesDuckType.Third.ToString(), ((IGetValue)copy).GetValueProp); - } - + } + #if NET6_0_OR_GREATER [Fact] public void NonPublicStructInterfaceProxyTest() @@ -34,9 +34,9 @@ public void NonPublicStructInterfaceProxyTest() Assert.Equal((int)instance.Value, (int)proxy.Value); Assert.Equal(ValuesDuckType.Third.ToString(), proxy.GetValue()); Assert.Equal(ValuesDuckType.Third.ToString(), proxy.GetValueProp); - } + } #endif - + [Fact] public void NonPublicStructAbstractProxyTest() { @@ -67,10 +67,10 @@ public struct CopyStruct : IGetValue string IGetValue.GetValueProp => Value.ToString(); public string GetValue() => Value.ToString(); - } - + } + #if NETCOREAPP3_0_OR_GREATER - // Interface with a default implementation + // Interface with a default implementation public interface IPrivateStruct { ValuesDuckType Value { get; } @@ -80,9 +80,9 @@ public interface IPrivateStruct [DuckIgnore] public string GetValue() => Value.ToString(); - } + } #endif - + public abstract class AbstractPrivateProxy : IGetValue { public abstract ValuesDuckType Value { get; } @@ -124,17 +124,17 @@ public interface IGetValue } public enum ValuesDuckType - { + { /// /// First /// - First, - + First, + /// /// Second /// - Second, - + Second, + /// /// Third /// @@ -142,17 +142,17 @@ public enum ValuesDuckType } public enum Values - { + { /// /// First /// - First, - + First, + /// /// Second /// - Second, - + Second, + /// /// Third /// diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckIncludeTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckIncludeTests.cs index 551d6714c..13206c80a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckIncludeTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckIncludeTests.cs @@ -1,15 +1,15 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + #pragma warning disable SA1201 // Elements must appear in the correct order - + using Elastic.Apm.Profiler.Managed.DuckTyping; using FluentAssertions; using Xunit; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckTypeExtensionsTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckTypeExtensionsTests.cs index 308e6d049..968119cad 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckTypeExtensionsTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/DuckTypeExtensionsTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Threading.Tasks; using Elastic.Apm.Profiler.Managed.DuckTyping; using FluentAssertions; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/ExceptionsTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/ExceptionsTests.cs index 5a78d3097..5a77163e8 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/ExceptionsTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/ExceptionsTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Threading.Tasks; using Elastic.Apm.Profiler.Managed.DuckTyping; using Xunit; @@ -48,10 +48,10 @@ public string OnlySetter { set { } } - } - - // * - + } + + // * + [Fact] public void PropertyCantBeWrittenException() { @@ -71,10 +71,10 @@ public interface IPropertyCantBeWrittenException internal class PropertyCantBeWrittenExceptionClass { public string OnlyGetter { get; } - } - - // * - + } + + // * + [Fact] public void PropertyArgumentsLengthException() { @@ -119,10 +119,10 @@ internal class PropertyArgumentsLengthExceptionClass get => null; set { } } - } - - // * - + } + + // * + [Fact] public void FieldIsReadonlyException() { @@ -145,10 +145,10 @@ internal class FieldIsReadonlyExceptionClass private readonly string _name = string.Empty; public string AvoidCompileError => _name; - } - - // * - + } + + // * + [Fact] public void PropertyOrFieldNotFoundException() { @@ -212,8 +212,8 @@ public struct PropertyOrFieldNotFound2ExceptionStruct internal class PropertyOrFieldNotFoundExceptionClass { } - internal struct PropertyOrFieldNotFoundExceptionTargetStruct { } - + internal struct PropertyOrFieldNotFoundExceptionTargetStruct { } + #if NET452 // * [Fact] @@ -242,8 +242,8 @@ internal class TypeIsNotPublicExceptionClass public string Name { get; set; } } #endif - // * - + // * + [Fact] public void StructMembersCannotBeChangedException() { @@ -264,10 +264,10 @@ public interface IStructMembersCannotBeChangedException internal struct StructMembersCannotBeChangedExceptionStruct { public string Name { get; set; } - } - - // * - + } + + // * + [Fact] public void StructMembersCannotBeChanged2Exception() { @@ -287,14 +287,14 @@ public interface IStructMembersCannotBeChanged2Exception } internal struct StructMembersCannotBeChanged2ExceptionStruct - { + { #pragma warning disable 649 - public string Name; + public string Name; #pragma warning restore 649 - } - - // * - + } + + // * + [Fact] public void TargetMethodNotFoundException() { @@ -337,10 +337,10 @@ internal class TargetMethodNotFoundExceptionClass public void Add(string key, string value) { } public void AddGeneric(T value) { } - } - - // * - + } + + // * + [Fact] public void ProxyMethodParameterIsMissingException() { @@ -361,10 +361,10 @@ public interface IProxyMethodParameterIsMissingException internal class ProxyMethodParameterIsMissingExceptionClass { public void Add(string key, string value) { } - } - - // * - + } + + // * + [Fact] public void ProxyAndTargetMethodParameterSignatureMismatchException() { @@ -396,8 +396,8 @@ public interface IProxyAndTargetMethodParameterSignatureMismatch2Exception internal class ProxyAndTargetMethodParameterSignatureMismatchExceptionClass { public void Add(string key, string value) { } - } - + } + #if NET452 // * [Fact] @@ -423,8 +423,8 @@ internal class ProxyMethodsWithGenericParametersNotSupportedInNonPublicInstances } } #endif - // * - + // * + [Fact] public void TargetMethodAmbiguousMatchException() { @@ -448,19 +448,19 @@ internal class TargetMethodAmbiguousMatchExceptionClass public void Add(string key, Task value) { } public void Add(string key, string value) { } - } - - // * - + } + + // * + [Fact] public void ProxyTypeDefinitionIsNull() => Assert.Throws(() => { DuckType.Create(null, new object()); - }); - - // * - + }); + + // * + [Fact] public void TargetObjectInstanceIsNull() => Assert.Throws(() => @@ -468,10 +468,10 @@ internal class TargetMethodAmbiguousMatchExceptionClass DuckType.Create(typeof(ITargetObjectInstanceIsNull), null); }); - public interface ITargetObjectInstanceIsNull { } - - // * - + public interface ITargetObjectInstanceIsNull { } + + // * + [Fact] public void InvalidTypeConversionException() { @@ -491,10 +491,10 @@ public interface IInvalidTypeConversionException public class InvalidTypeConversionExceptionClass { public int Sum(int a, int b) => a + b; - } - - // * - + } + + // * + [Fact] public void ObjectInvalidTypeConversionException() { @@ -514,10 +514,10 @@ public interface IObjectInvalidTypeConversionException public class ObjectInvalidTypeConversionExceptionClass { public int Value => 42; - } - - // * - + } + + // * + [Fact] public void ObjectInvalidTypeConversion2Exception() { @@ -537,10 +537,10 @@ public interface IObjectInvalidTypeConversion2Exception public class ObjectInvalidTypeConversion2ExceptionClass { public string Value => "Hello world"; - } - - // * - + } + + // * + [Fact] public void ObjectInvalidTypeConversion3Exception() { @@ -559,11 +559,11 @@ public interface IObjectInvalidTypeConversion3Exception } public class ObjectInvalidTypeConversion3ExceptionClass - { + { #pragma warning disable 414 #pragma warning disable IDE0051 // Remove unused private members #pragma warning disable SA1306 // Field names must begin with lower-case letter - private readonly string Value = "Hello world"; + private readonly string Value = "Hello world"; #pragma warning restore SA1306 // Field names must begin with lower-case letter #pragma warning restore IDE0051 // Remove unused private members #pragma warning restore 414 diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureDuckType.cs index b91362bf3..d84f26066 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ReferenceType.ProxiesDefinitions @@ -24,10 +24,10 @@ public interface IObscureDuckType string ProtectedStaticReadonlyReferenceTypeField { get; } [Duck(Name = "_privateStaticReadonlyReferenceTypeField", Kind = DuckKind.Field)] - string PrivateStaticReadonlyReferenceTypeField { get; } - - // * - + string PrivateStaticReadonlyReferenceTypeField { get; } + + // * + [Duck(Name = "_publicStaticReferenceTypeField", Kind = DuckKind.Field)] string PublicStaticReferenceTypeField { get; set; } @@ -38,10 +38,10 @@ public interface IObscureDuckType string ProtectedStaticReferenceTypeField { get; set; } [Duck(Name = "_privateStaticReferenceTypeField", Kind = DuckKind.Field)] - string PrivateStaticReferenceTypeField { get; set; } - - // * - + string PrivateStaticReferenceTypeField { get; set; } + + // * + [Duck(Name = "_publicReadonlyReferenceTypeField", Kind = DuckKind.Field)] string PublicReadonlyReferenceTypeField { get; } @@ -52,10 +52,10 @@ public interface IObscureDuckType string ProtectedReadonlyReferenceTypeField { get; } [Duck(Name = "_privateReadonlyReferenceTypeField", Kind = DuckKind.Field)] - string PrivateReadonlyReferenceTypeField { get; } - - // * - + string PrivateReadonlyReferenceTypeField { get; } + + // * + [Duck(Name = "_publicReferenceTypeField", Kind = DuckKind.Field)] string PublicReferenceTypeField { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs index 2d3e4b3c6..78f9b3115 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ReferenceType.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs index 838d58a49..a1d6f4f87 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ReferenceType.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs index 60796c033..60f3213ec 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ReferenceType.ProxiesDefinitions @@ -24,10 +24,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract string ProtectedStaticReadonlyReferenceTypeField { get; } [Duck(Name = "_privateStaticReadonlyReferenceTypeField", Kind = DuckKind.Field)] - public abstract string PrivateStaticReadonlyReferenceTypeField { get; } - - // * - + public abstract string PrivateStaticReadonlyReferenceTypeField { get; } + + // * + [Duck(Name = "_publicStaticReferenceTypeField", Kind = DuckKind.Field)] public abstract string PublicStaticReferenceTypeField { get; set; } @@ -38,10 +38,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract string ProtectedStaticReferenceTypeField { get; set; } [Duck(Name = "_privateStaticReferenceTypeField", Kind = DuckKind.Field)] - public abstract string PrivateStaticReferenceTypeField { get; set; } - - // * - + public abstract string PrivateStaticReferenceTypeField { get; set; } + + // * + [Duck(Name = "_publicReadonlyReferenceTypeField", Kind = DuckKind.Field)] public abstract string PublicReadonlyReferenceTypeField { get; } @@ -52,10 +52,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract string ProtectedReadonlyReferenceTypeField { get; } [Duck(Name = "_privateReadonlyReferenceTypeField", Kind = DuckKind.Field)] - public abstract string PrivateReadonlyReferenceTypeField { get; } - - // * - + public abstract string PrivateReadonlyReferenceTypeField { get; } + + // * + [Duck(Name = "_publicReferenceTypeField", Kind = DuckKind.Field)] public abstract string PublicReferenceTypeField { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs index 9d6cfc635..c04c06efc 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ReferenceType.ProxiesDefinitions @@ -24,10 +24,10 @@ public class ObscureDuckTypeVirtualClass public virtual string ProtectedStaticReadonlyReferenceTypeField { get; } [Duck(Name = "_privateStaticReadonlyReferenceTypeField", Kind = DuckKind.Field)] - public virtual string PrivateStaticReadonlyReferenceTypeField { get; } - - // * - + public virtual string PrivateStaticReadonlyReferenceTypeField { get; } + + // * + [Duck(Name = "_publicStaticReferenceTypeField", Kind = DuckKind.Field)] public virtual string PublicStaticReferenceTypeField { get; set; } @@ -38,10 +38,10 @@ public class ObscureDuckTypeVirtualClass public virtual string ProtectedStaticReferenceTypeField { get; set; } [Duck(Name = "_privateStaticReferenceTypeField", Kind = DuckKind.Field)] - public virtual string PrivateStaticReferenceTypeField { get; set; } - - // * - + public virtual string PrivateStaticReferenceTypeField { get; set; } + + // * + [Duck(Name = "_publicReadonlyReferenceTypeField", Kind = DuckKind.Field)] public virtual string PublicReadonlyReferenceTypeField { get; } @@ -52,10 +52,10 @@ public class ObscureDuckTypeVirtualClass public virtual string ProtectedReadonlyReferenceTypeField { get; } [Duck(Name = "_privateReadonlyReferenceTypeField", Kind = DuckKind.Field)] - public virtual string PrivateReadonlyReferenceTypeField { get; } - - // * - + public virtual string PrivateReadonlyReferenceTypeField { get; } + + // * + [Duck(Name = "_publicReferenceTypeField", Kind = DuckKind.Field)] public virtual string PublicReferenceTypeField { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ReferenceTypeFieldTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ReferenceTypeFieldTests.cs index 7bad45240..ef0ff675a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ReferenceTypeFieldTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ReferenceType/ReferenceTypeFieldTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Collections.Generic; using Elastic.Apm.Profiler.Managed.DuckTyping; using Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ReferenceType.ProxiesDefinitions; @@ -46,24 +46,24 @@ public void StaticReadonlyFields(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * + var duckVirtual = obscureObject.DuckCast(); + + // * Assert.Equal("10", duckInterface.PublicStaticReadonlyReferenceTypeField); Assert.Equal("10", duckAbstract.PublicStaticReadonlyReferenceTypeField); - Assert.Equal("10", duckVirtual.PublicStaticReadonlyReferenceTypeField); - - // * + Assert.Equal("10", duckVirtual.PublicStaticReadonlyReferenceTypeField); + + // * Assert.Equal("11", duckInterface.InternalStaticReadonlyReferenceTypeField); Assert.Equal("11", duckAbstract.InternalStaticReadonlyReferenceTypeField); - Assert.Equal("11", duckVirtual.InternalStaticReadonlyReferenceTypeField); - - // * + Assert.Equal("11", duckVirtual.InternalStaticReadonlyReferenceTypeField); + + // * Assert.Equal("12", duckInterface.ProtectedStaticReadonlyReferenceTypeField); Assert.Equal("12", duckAbstract.ProtectedStaticReadonlyReferenceTypeField); - Assert.Equal("12", duckVirtual.ProtectedStaticReadonlyReferenceTypeField); - - // * + Assert.Equal("12", duckVirtual.ProtectedStaticReadonlyReferenceTypeField); + + // * Assert.Equal("13", duckInterface.PrivateStaticReadonlyReferenceTypeField); Assert.Equal("13", duckAbstract.PrivateStaticReadonlyReferenceTypeField); Assert.Equal("13", duckVirtual.PrivateStaticReadonlyReferenceTypeField); @@ -94,10 +94,10 @@ public void StaticFields(object obscureObject) duckVirtual.PublicStaticReferenceTypeField = "60"; Assert.Equal("60", duckInterface.PublicStaticReferenceTypeField); Assert.Equal("60", duckAbstract.PublicStaticReferenceTypeField); - Assert.Equal("60", duckVirtual.PublicStaticReferenceTypeField); - - // * - + Assert.Equal("60", duckVirtual.PublicStaticReferenceTypeField); + + // * + Assert.Equal("21", duckInterface.InternalStaticReferenceTypeField); Assert.Equal("21", duckAbstract.InternalStaticReferenceTypeField); Assert.Equal("21", duckVirtual.InternalStaticReferenceTypeField); @@ -115,10 +115,10 @@ public void StaticFields(object obscureObject) duckVirtual.InternalStaticReferenceTypeField = "60"; Assert.Equal("60", duckInterface.InternalStaticReferenceTypeField); Assert.Equal("60", duckAbstract.InternalStaticReferenceTypeField); - Assert.Equal("60", duckVirtual.InternalStaticReferenceTypeField); - - // * - + Assert.Equal("60", duckVirtual.InternalStaticReferenceTypeField); + + // * + Assert.Equal("22", duckInterface.ProtectedStaticReferenceTypeField); Assert.Equal("22", duckAbstract.ProtectedStaticReferenceTypeField); Assert.Equal("22", duckVirtual.ProtectedStaticReferenceTypeField); @@ -136,10 +136,10 @@ public void StaticFields(object obscureObject) duckVirtual.ProtectedStaticReferenceTypeField = "60"; Assert.Equal("60", duckInterface.ProtectedStaticReferenceTypeField); Assert.Equal("60", duckAbstract.ProtectedStaticReferenceTypeField); - Assert.Equal("60", duckVirtual.ProtectedStaticReferenceTypeField); - - // * - + Assert.Equal("60", duckVirtual.ProtectedStaticReferenceTypeField); + + // * + Assert.Equal("23", duckInterface.PrivateStaticReferenceTypeField); Assert.Equal("23", duckAbstract.PrivateStaticReferenceTypeField); Assert.Equal("23", duckVirtual.PrivateStaticReferenceTypeField); @@ -166,24 +166,24 @@ public void ReadonlyFields(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * + var duckVirtual = obscureObject.DuckCast(); + + // * Assert.Equal("30", duckInterface.PublicReadonlyReferenceTypeField); Assert.Equal("30", duckAbstract.PublicReadonlyReferenceTypeField); - Assert.Equal("30", duckVirtual.PublicReadonlyReferenceTypeField); - - // * + Assert.Equal("30", duckVirtual.PublicReadonlyReferenceTypeField); + + // * Assert.Equal("31", duckInterface.InternalReadonlyReferenceTypeField); Assert.Equal("31", duckAbstract.InternalReadonlyReferenceTypeField); - Assert.Equal("31", duckVirtual.InternalReadonlyReferenceTypeField); - - // * + Assert.Equal("31", duckVirtual.InternalReadonlyReferenceTypeField); + + // * Assert.Equal("32", duckInterface.ProtectedReadonlyReferenceTypeField); Assert.Equal("32", duckAbstract.ProtectedReadonlyReferenceTypeField); - Assert.Equal("32", duckVirtual.ProtectedReadonlyReferenceTypeField); - - // * + Assert.Equal("32", duckVirtual.ProtectedReadonlyReferenceTypeField); + + // * Assert.Equal("33", duckInterface.PrivateReadonlyReferenceTypeField); Assert.Equal("33", duckAbstract.PrivateReadonlyReferenceTypeField); Assert.Equal("33", duckVirtual.PrivateReadonlyReferenceTypeField); @@ -214,10 +214,10 @@ public void Fields(object obscureObject) duckVirtual.PublicReferenceTypeField = "60"; Assert.Equal("60", duckInterface.PublicReferenceTypeField); Assert.Equal("60", duckAbstract.PublicReferenceTypeField); - Assert.Equal("60", duckVirtual.PublicReferenceTypeField); - - // * - + Assert.Equal("60", duckVirtual.PublicReferenceTypeField); + + // * + Assert.Equal("41", duckInterface.InternalReferenceTypeField); Assert.Equal("41", duckAbstract.InternalReferenceTypeField); Assert.Equal("41", duckVirtual.InternalReferenceTypeField); @@ -235,10 +235,10 @@ public void Fields(object obscureObject) duckVirtual.InternalReferenceTypeField = "60"; Assert.Equal("60", duckInterface.InternalReferenceTypeField); Assert.Equal("60", duckAbstract.InternalReferenceTypeField); - Assert.Equal("60", duckVirtual.InternalReferenceTypeField); - - // * - + Assert.Equal("60", duckVirtual.InternalReferenceTypeField); + + // * + Assert.Equal("42", duckInterface.ProtectedReferenceTypeField); Assert.Equal("42", duckAbstract.ProtectedReferenceTypeField); Assert.Equal("42", duckVirtual.ProtectedReferenceTypeField); @@ -256,10 +256,10 @@ public void Fields(object obscureObject) duckVirtual.ProtectedReferenceTypeField = "60"; Assert.Equal("60", duckInterface.ProtectedReferenceTypeField); Assert.Equal("60", duckAbstract.ProtectedReferenceTypeField); - Assert.Equal("60", duckVirtual.ProtectedReferenceTypeField); - - // * - + Assert.Equal("60", duckVirtual.ProtectedReferenceTypeField); + + // * + Assert.Equal("43", duckInterface.PrivateReferenceTypeField); Assert.Equal("43", duckAbstract.PrivateReferenceTypeField); Assert.Equal("43", duckVirtual.PrivateReferenceTypeField); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IDummyFieldObject.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IDummyFieldObject.cs index 9d80c3b79..1522dc035 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IDummyFieldObject.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IDummyFieldObject.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.TypeChaining.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureDuckType.cs index 06a1182b4..d93420b3d 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.TypeChaining.ProxiesDefinitions @@ -24,10 +24,10 @@ public interface IObscureDuckType IDummyFieldObject ProtectedStaticReadonlySelfTypeField { get; } [Duck(Name = "_privateStaticReadonlySelfTypeField", Kind = DuckKind.Field)] - IDummyFieldObject PrivateStaticReadonlySelfTypeField { get; } - - // * - + IDummyFieldObject PrivateStaticReadonlySelfTypeField { get; } + + // * + [Duck(Name = "_publicStaticSelfTypeField", Kind = DuckKind.Field)] IDummyFieldObject PublicStaticSelfTypeField { get; set; } @@ -38,10 +38,10 @@ public interface IObscureDuckType IDummyFieldObject ProtectedStaticSelfTypeField { get; set; } [Duck(Name = "_privateStaticSelfTypeField", Kind = DuckKind.Field)] - IDummyFieldObject PrivateStaticSelfTypeField { get; set; } - - // * - + IDummyFieldObject PrivateStaticSelfTypeField { get; set; } + + // * + [Duck(Name = "_publicReadonlySelfTypeField", Kind = DuckKind.Field)] IDummyFieldObject PublicReadonlySelfTypeField { get; } @@ -52,10 +52,10 @@ public interface IObscureDuckType IDummyFieldObject ProtectedReadonlySelfTypeField { get; } [Duck(Name = "_privateReadonlySelfTypeField", Kind = DuckKind.Field)] - IDummyFieldObject PrivateReadonlySelfTypeField { get; } - - // * - + IDummyFieldObject PrivateReadonlySelfTypeField { get; } + + // * + [Duck(Name = "_publicSelfTypeField", Kind = DuckKind.Field)] IDummyFieldObject PublicSelfTypeField { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs index 3a6957770..f472f2b8e 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.TypeChaining.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs index 543656f0f..032c3f4df 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.TypeChaining.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs index 9779281ea..380f54837 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.TypeChaining.ProxiesDefinitions @@ -24,10 +24,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract IDummyFieldObject ProtectedStaticReadonlySelfTypeField { get; } [Duck(Name = "_privateStaticReadonlySelfTypeField", Kind = DuckKind.Field)] - public abstract IDummyFieldObject PrivateStaticReadonlySelfTypeField { get; } - - // * - + public abstract IDummyFieldObject PrivateStaticReadonlySelfTypeField { get; } + + // * + [Duck(Name = "_publicStaticSelfTypeField", Kind = DuckKind.Field)] public abstract IDummyFieldObject PublicStaticSelfTypeField { get; set; } @@ -38,10 +38,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract IDummyFieldObject ProtectedStaticSelfTypeField { get; set; } [Duck(Name = "_privateStaticSelfTypeField", Kind = DuckKind.Field)] - public abstract IDummyFieldObject PrivateStaticSelfTypeField { get; set; } - - // * - + public abstract IDummyFieldObject PrivateStaticSelfTypeField { get; set; } + + // * + [Duck(Name = "_publicReadonlySelfTypeField", Kind = DuckKind.Field)] public abstract IDummyFieldObject PublicReadonlySelfTypeField { get; } @@ -52,10 +52,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract IDummyFieldObject ProtectedReadonlySelfTypeField { get; } [Duck(Name = "_privateReadonlySelfTypeField", Kind = DuckKind.Field)] - public abstract IDummyFieldObject PrivateReadonlySelfTypeField { get; } - - // * - + public abstract IDummyFieldObject PrivateReadonlySelfTypeField { get; } + + // * + [Duck(Name = "_publicSelfTypeField", Kind = DuckKind.Field)] public abstract IDummyFieldObject PublicSelfTypeField { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs index a343ba92e..440bc3153 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.TypeChaining.ProxiesDefinitions @@ -24,10 +24,10 @@ public class ObscureDuckTypeVirtualClass public virtual IDummyFieldObject ProtectedStaticReadonlySelfTypeField { get; } [Duck(Name = "_privateStaticReadonlySelfTypeField", Kind = DuckKind.Field)] - public virtual IDummyFieldObject PrivateStaticReadonlySelfTypeField { get; } - - // * - + public virtual IDummyFieldObject PrivateStaticReadonlySelfTypeField { get; } + + // * + [Duck(Name = "_publicStaticSelfTypeField", Kind = DuckKind.Field)] public virtual IDummyFieldObject PublicStaticSelfTypeField { get; set; } @@ -38,10 +38,10 @@ public class ObscureDuckTypeVirtualClass public virtual IDummyFieldObject ProtectedStaticSelfTypeField { get; set; } [Duck(Name = "_privateStaticSelfTypeField", Kind = DuckKind.Field)] - public virtual IDummyFieldObject PrivateStaticSelfTypeField { get; set; } - - // * - + public virtual IDummyFieldObject PrivateStaticSelfTypeField { get; set; } + + // * + [Duck(Name = "_publicReadonlySelfTypeField", Kind = DuckKind.Field)] public virtual IDummyFieldObject PublicReadonlySelfTypeField { get; } @@ -52,10 +52,10 @@ public class ObscureDuckTypeVirtualClass public virtual IDummyFieldObject ProtectedReadonlySelfTypeField { get; } [Duck(Name = "_privateReadonlySelfTypeField", Kind = DuckKind.Field)] - public virtual IDummyFieldObject PrivateReadonlySelfTypeField { get; } - - // * - + public virtual IDummyFieldObject PrivateReadonlySelfTypeField { get; } + + // * + [Duck(Name = "_publicSelfTypeField", Kind = DuckKind.Field)] public virtual IDummyFieldObject PublicSelfTypeField { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/TypeChainingFieldTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/TypeChainingFieldTests.cs index 042f2ddab..43e83a749 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/TypeChainingFieldTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/TypeChaining/TypeChainingFieldTests.cs @@ -1,20 +1,20 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Collections.Generic; using Elastic.Apm.Profiler.Managed.DuckTyping; using Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.TypeChaining.ProxiesDefinitions; -using Xunit; - +using Xunit; + #pragma warning disable SA1201 // Elements must appear in the correct order - + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.TypeChaining { public class TypeChainingFieldTests @@ -48,40 +48,40 @@ public void StaticReadonlyFields(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * - + var duckVirtual = obscureObject.DuckCast(); + + // * + Assert.Equal(42, duckInterface.PublicStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.PublicStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckVirtual.PublicStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.PublicStaticReadonlySelfTypeField).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.PublicStaticReadonlySelfTypeField).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.PublicStaticReadonlySelfTypeField).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.PublicStaticReadonlySelfTypeField).Instance); + + // * + Assert.Equal(42, duckInterface.InternalStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.InternalStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckVirtual.InternalStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.InternalStaticReadonlySelfTypeField).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.InternalStaticReadonlySelfTypeField).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.InternalStaticReadonlySelfTypeField).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.InternalStaticReadonlySelfTypeField).Instance); + + // * + Assert.Equal(42, duckInterface.ProtectedStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.ProtectedStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckVirtual.ProtectedStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.ProtectedStaticReadonlySelfTypeField).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.ProtectedStaticReadonlySelfTypeField).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.ProtectedStaticReadonlySelfTypeField).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.ProtectedStaticReadonlySelfTypeField).Instance); + + // * + Assert.Equal(42, duckInterface.PrivateStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.PrivateStaticReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckVirtual.PrivateStaticReadonlySelfTypeField.MagicNumber); @@ -99,33 +99,33 @@ public void StaticFields(object obscureObject) var duckAbstract = obscureObject.DuckCast(); var duckVirtual = obscureObject.DuckCast(); - IDummyFieldObject newDummy = null; - - // * + IDummyFieldObject newDummy = null; + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 42 }).DuckCast(); duckInterface.PublicStaticSelfTypeField = newDummy; Assert.Equal(42, duckInterface.PublicStaticSelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.PublicStaticSelfTypeField.MagicNumber); - Assert.Equal(42, duckVirtual.PublicStaticSelfTypeField.MagicNumber); - - // * + Assert.Equal(42, duckVirtual.PublicStaticSelfTypeField.MagicNumber); + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 52 }).DuckCast(); duckInterface.InternalStaticSelfTypeField = newDummy; Assert.Equal(52, duckInterface.InternalStaticSelfTypeField.MagicNumber); Assert.Equal(52, duckAbstract.InternalStaticSelfTypeField.MagicNumber); - Assert.Equal(52, duckVirtual.InternalStaticSelfTypeField.MagicNumber); - - // * + Assert.Equal(52, duckVirtual.InternalStaticSelfTypeField.MagicNumber); + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 62 }).DuckCast(); duckAbstract.ProtectedStaticSelfTypeField = newDummy; Assert.Equal(62, duckInterface.ProtectedStaticSelfTypeField.MagicNumber); Assert.Equal(62, duckAbstract.ProtectedStaticSelfTypeField.MagicNumber); - Assert.Equal(62, duckVirtual.ProtectedStaticSelfTypeField.MagicNumber); - - // * + Assert.Equal(62, duckVirtual.ProtectedStaticSelfTypeField.MagicNumber); + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 72 }).DuckCast(); duckAbstract.PrivateStaticSelfTypeField = newDummy; @@ -140,40 +140,40 @@ public void ReadonlyFields(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * - + var duckVirtual = obscureObject.DuckCast(); + + // * + Assert.Equal(42, duckInterface.PublicReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.PublicReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckVirtual.PublicReadonlySelfTypeField.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.PublicReadonlySelfTypeField).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.PublicReadonlySelfTypeField).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.PublicReadonlySelfTypeField).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.PublicReadonlySelfTypeField).Instance); + + // * + Assert.Equal(42, duckInterface.InternalReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.InternalReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckVirtual.InternalReadonlySelfTypeField.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.InternalReadonlySelfTypeField).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.InternalReadonlySelfTypeField).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.InternalReadonlySelfTypeField).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.InternalReadonlySelfTypeField).Instance); + + // * + Assert.Equal(42, duckInterface.ProtectedReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.ProtectedReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckVirtual.ProtectedReadonlySelfTypeField.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.ProtectedReadonlySelfTypeField).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.ProtectedReadonlySelfTypeField).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.ProtectedReadonlySelfTypeField).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.ProtectedReadonlySelfTypeField).Instance); + + // * + Assert.Equal(42, duckInterface.PrivateReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.PrivateReadonlySelfTypeField.MagicNumber); Assert.Equal(42, duckVirtual.PrivateReadonlySelfTypeField.MagicNumber); @@ -191,33 +191,33 @@ public void Fields(object obscureObject) var duckAbstract = obscureObject.DuckCast(); var duckVirtual = obscureObject.DuckCast(); - IDummyFieldObject newDummy = null; - - // * + IDummyFieldObject newDummy = null; + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 42 }).DuckCast(); duckInterface.PublicSelfTypeField = newDummy; Assert.Equal(42, duckInterface.PublicSelfTypeField.MagicNumber); Assert.Equal(42, duckAbstract.PublicSelfTypeField.MagicNumber); - Assert.Equal(42, duckVirtual.PublicSelfTypeField.MagicNumber); - - // * + Assert.Equal(42, duckVirtual.PublicSelfTypeField.MagicNumber); + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 52 }).DuckCast(); duckInterface.InternalSelfTypeField = newDummy; Assert.Equal(52, duckInterface.InternalSelfTypeField.MagicNumber); Assert.Equal(52, duckAbstract.InternalSelfTypeField.MagicNumber); - Assert.Equal(52, duckVirtual.InternalSelfTypeField.MagicNumber); - - // * + Assert.Equal(52, duckVirtual.InternalSelfTypeField.MagicNumber); + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 62 }).DuckCast(); duckInterface.ProtectedSelfTypeField = newDummy; Assert.Equal(62, duckInterface.ProtectedSelfTypeField.MagicNumber); Assert.Equal(62, duckAbstract.ProtectedSelfTypeField.MagicNumber); - Assert.Equal(62, duckVirtual.ProtectedSelfTypeField.MagicNumber); - - // * + Assert.Equal(62, duckVirtual.ProtectedSelfTypeField.MagicNumber); + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 72 }).DuckCast(); duckInterface.PrivateSelfTypeField = newDummy; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureDuckType.cs index 599a0ed04..ecb0ad990 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ValueType.ProxiesDefinitions @@ -24,10 +24,10 @@ public interface IObscureDuckType int ProtectedStaticReadonlyValueTypeField { get; } [Duck(Name = "_privateStaticReadonlyValueTypeField", Kind = DuckKind.Field)] - int PrivateStaticReadonlyValueTypeField { get; } - - // * - + int PrivateStaticReadonlyValueTypeField { get; } + + // * + [Duck(Name = "_publicStaticValueTypeField", Kind = DuckKind.Field)] int PublicStaticValueTypeField { get; set; } @@ -38,10 +38,10 @@ public interface IObscureDuckType int ProtectedStaticValueTypeField { get; set; } [Duck(Name = "_privateStaticValueTypeField", Kind = DuckKind.Field)] - int PrivateStaticValueTypeField { get; set; } - - // * - + int PrivateStaticValueTypeField { get; set; } + + // * + [Duck(Name = "_publicReadonlyValueTypeField", Kind = DuckKind.Field)] int PublicReadonlyValueTypeField { get; } @@ -52,10 +52,10 @@ public interface IObscureDuckType int ProtectedReadonlyValueTypeField { get; } [Duck(Name = "_privateReadonlyValueTypeField", Kind = DuckKind.Field)] - int PrivateReadonlyValueTypeField { get; } - - // * - + int PrivateReadonlyValueTypeField { get; } + + // * + [Duck(Name = "_publicValueTypeField", Kind = DuckKind.Field)] int PublicValueTypeField { get; set; } @@ -66,10 +66,10 @@ public interface IObscureDuckType int ProtectedValueTypeField { get; set; } [Duck(Name = "_privateValueTypeField", Kind = DuckKind.Field)] - int PrivateValueTypeField { get; set; } - - // * - + int PrivateValueTypeField { get; set; } + + // * + [Duck(Name = "_publicStaticNullableIntField", Kind = DuckKind.Field)] int? PublicStaticNullableIntField { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs index e04268d5e..0213dcc8a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureReadonlyErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ValueType.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs index 9f11b0b93..1accbdd29 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/IObscureStaticReadonlyErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ValueType.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs index 094ed5901..9a0595eba 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ValueType.ProxiesDefinitions @@ -24,10 +24,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract int ProtectedStaticReadonlyValueTypeField { get; } [Duck(Name = "_privateStaticReadonlyValueTypeField", Kind = DuckKind.Field)] - public abstract int PrivateStaticReadonlyValueTypeField { get; } - - // * - + public abstract int PrivateStaticReadonlyValueTypeField { get; } + + // * + [Duck(Name = "_publicStaticValueTypeField", Kind = DuckKind.Field)] public abstract int PublicStaticValueTypeField { get; set; } @@ -38,10 +38,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract int ProtectedStaticValueTypeField { get; set; } [Duck(Name = "_privateStaticValueTypeField", Kind = DuckKind.Field)] - public abstract int PrivateStaticValueTypeField { get; set; } - - // * - + public abstract int PrivateStaticValueTypeField { get; set; } + + // * + [Duck(Name = "_publicReadonlyValueTypeField", Kind = DuckKind.Field)] public abstract int PublicReadonlyValueTypeField { get; } @@ -52,10 +52,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract int ProtectedReadonlyValueTypeField { get; } [Duck(Name = "_privateReadonlyValueTypeField", Kind = DuckKind.Field)] - public abstract int PrivateReadonlyValueTypeField { get; } - - // * - + public abstract int PrivateReadonlyValueTypeField { get; } + + // * + [Duck(Name = "_publicValueTypeField", Kind = DuckKind.Field)] public abstract int PublicValueTypeField { get; set; } @@ -66,10 +66,10 @@ public abstract class ObscureDuckTypeAbstractClass public abstract int ProtectedValueTypeField { get; set; } [Duck(Name = "_privateValueTypeField", Kind = DuckKind.Field)] - public abstract int PrivateValueTypeField { get; set; } - - // * - + public abstract int PrivateValueTypeField { get; set; } + + // * + [Duck(Name = "_publicStaticNullableIntField", Kind = DuckKind.Field)] public abstract int? PublicStaticNullableIntField { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs index c032eb7f6..ed877db97 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ValueType.ProxiesDefinitions @@ -24,10 +24,10 @@ public class ObscureDuckTypeVirtualClass public virtual int ProtectedStaticReadonlyValueTypeField { get; } [Duck(Name = "_privateStaticReadonlyValueTypeField", Kind = DuckKind.Field)] - public virtual int PrivateStaticReadonlyValueTypeField { get; } - - // * - + public virtual int PrivateStaticReadonlyValueTypeField { get; } + + // * + [Duck(Name = "_publicStaticValueTypeField", Kind = DuckKind.Field)] public virtual int PublicStaticValueTypeField { get; set; } @@ -38,10 +38,10 @@ public class ObscureDuckTypeVirtualClass public virtual int ProtectedStaticValueTypeField { get; set; } [Duck(Name = "_privateStaticValueTypeField", Kind = DuckKind.Field)] - public virtual int PrivateStaticValueTypeField { get; set; } - - // * - + public virtual int PrivateStaticValueTypeField { get; set; } + + // * + [Duck(Name = "_publicReadonlyValueTypeField", Kind = DuckKind.Field)] public virtual int PublicReadonlyValueTypeField { get; } @@ -52,10 +52,10 @@ public class ObscureDuckTypeVirtualClass public virtual int ProtectedReadonlyValueTypeField { get; } [Duck(Name = "_privateReadonlyValueTypeField", Kind = DuckKind.Field)] - public virtual int PrivateReadonlyValueTypeField { get; } - - // * - + public virtual int PrivateReadonlyValueTypeField { get; } + + // * + [Duck(Name = "_publicValueTypeField", Kind = DuckKind.Field)] public virtual int PublicValueTypeField { get; set; } @@ -66,10 +66,10 @@ public class ObscureDuckTypeVirtualClass public virtual int ProtectedValueTypeField { get; set; } [Duck(Name = "_privateValueTypeField", Kind = DuckKind.Field)] - public virtual int PrivateValueTypeField { get; set; } - - // * - + public virtual int PrivateValueTypeField { get; set; } + + // * + [Duck(Name = "_publicStaticNullableIntField", Kind = DuckKind.Field)] public virtual int? PublicStaticNullableIntField { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ValueTypeFieldTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ValueTypeFieldTests.cs index 15ef4de9c..e7b619a82 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ValueTypeFieldTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Fields/ValueType/ValueTypeFieldTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Collections.Generic; using Elastic.Apm.Profiler.Managed.DuckTyping; using Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Fields.ValueType.ProxiesDefinitions; @@ -46,24 +46,24 @@ public void StaticReadonlyFields(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * + var duckVirtual = obscureObject.DuckCast(); + + // * Assert.Equal(10, duckInterface.PublicStaticReadonlyValueTypeField); Assert.Equal(10, duckAbstract.PublicStaticReadonlyValueTypeField); - Assert.Equal(10, duckVirtual.PublicStaticReadonlyValueTypeField); - - // * + Assert.Equal(10, duckVirtual.PublicStaticReadonlyValueTypeField); + + // * Assert.Equal(11, duckInterface.InternalStaticReadonlyValueTypeField); Assert.Equal(11, duckAbstract.InternalStaticReadonlyValueTypeField); - Assert.Equal(11, duckVirtual.InternalStaticReadonlyValueTypeField); - - // * + Assert.Equal(11, duckVirtual.InternalStaticReadonlyValueTypeField); + + // * Assert.Equal(12, duckInterface.ProtectedStaticReadonlyValueTypeField); Assert.Equal(12, duckAbstract.ProtectedStaticReadonlyValueTypeField); - Assert.Equal(12, duckVirtual.ProtectedStaticReadonlyValueTypeField); - - // * + Assert.Equal(12, duckVirtual.ProtectedStaticReadonlyValueTypeField); + + // * Assert.Equal(13, duckInterface.PrivateStaticReadonlyValueTypeField); Assert.Equal(13, duckAbstract.PrivateStaticReadonlyValueTypeField); Assert.Equal(13, duckVirtual.PrivateStaticReadonlyValueTypeField); @@ -94,10 +94,10 @@ public void StaticFields(object obscureObject) duckVirtual.PublicStaticValueTypeField = 60; Assert.Equal(60, duckInterface.PublicStaticValueTypeField); Assert.Equal(60, duckAbstract.PublicStaticValueTypeField); - Assert.Equal(60, duckVirtual.PublicStaticValueTypeField); - - // * - + Assert.Equal(60, duckVirtual.PublicStaticValueTypeField); + + // * + Assert.Equal(21, duckInterface.InternalStaticValueTypeField); Assert.Equal(21, duckAbstract.InternalStaticValueTypeField); Assert.Equal(21, duckVirtual.InternalStaticValueTypeField); @@ -115,10 +115,10 @@ public void StaticFields(object obscureObject) duckVirtual.InternalStaticValueTypeField = 60; Assert.Equal(60, duckInterface.InternalStaticValueTypeField); Assert.Equal(60, duckAbstract.InternalStaticValueTypeField); - Assert.Equal(60, duckVirtual.InternalStaticValueTypeField); - - // * - + Assert.Equal(60, duckVirtual.InternalStaticValueTypeField); + + // * + Assert.Equal(22, duckInterface.ProtectedStaticValueTypeField); Assert.Equal(22, duckAbstract.ProtectedStaticValueTypeField); Assert.Equal(22, duckVirtual.ProtectedStaticValueTypeField); @@ -136,10 +136,10 @@ public void StaticFields(object obscureObject) duckVirtual.ProtectedStaticValueTypeField = 60; Assert.Equal(60, duckInterface.ProtectedStaticValueTypeField); Assert.Equal(60, duckAbstract.ProtectedStaticValueTypeField); - Assert.Equal(60, duckVirtual.ProtectedStaticValueTypeField); - - // * - + Assert.Equal(60, duckVirtual.ProtectedStaticValueTypeField); + + // * + Assert.Equal(23, duckInterface.PrivateStaticValueTypeField); Assert.Equal(23, duckAbstract.PrivateStaticValueTypeField); Assert.Equal(23, duckVirtual.PrivateStaticValueTypeField); @@ -166,24 +166,24 @@ public void ReadonlyFields(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * + var duckVirtual = obscureObject.DuckCast(); + + // * Assert.Equal(30, duckInterface.PublicReadonlyValueTypeField); Assert.Equal(30, duckAbstract.PublicReadonlyValueTypeField); - Assert.Equal(30, duckVirtual.PublicReadonlyValueTypeField); - - // * + Assert.Equal(30, duckVirtual.PublicReadonlyValueTypeField); + + // * Assert.Equal(31, duckInterface.InternalReadonlyValueTypeField); Assert.Equal(31, duckAbstract.InternalReadonlyValueTypeField); - Assert.Equal(31, duckVirtual.InternalReadonlyValueTypeField); - - // * + Assert.Equal(31, duckVirtual.InternalReadonlyValueTypeField); + + // * Assert.Equal(32, duckInterface.ProtectedReadonlyValueTypeField); Assert.Equal(32, duckAbstract.ProtectedReadonlyValueTypeField); - Assert.Equal(32, duckVirtual.ProtectedReadonlyValueTypeField); - - // * + Assert.Equal(32, duckVirtual.ProtectedReadonlyValueTypeField); + + // * Assert.Equal(33, duckInterface.PrivateReadonlyValueTypeField); Assert.Equal(33, duckAbstract.PrivateReadonlyValueTypeField); Assert.Equal(33, duckVirtual.PrivateReadonlyValueTypeField); @@ -214,10 +214,10 @@ public void Fields(object obscureObject) duckVirtual.PublicValueTypeField = 60; Assert.Equal(60, duckInterface.PublicValueTypeField); Assert.Equal(60, duckAbstract.PublicValueTypeField); - Assert.Equal(60, duckVirtual.PublicValueTypeField); - - // * - + Assert.Equal(60, duckVirtual.PublicValueTypeField); + + // * + Assert.Equal(41, duckInterface.InternalValueTypeField); Assert.Equal(41, duckAbstract.InternalValueTypeField); Assert.Equal(41, duckVirtual.InternalValueTypeField); @@ -235,10 +235,10 @@ public void Fields(object obscureObject) duckVirtual.InternalValueTypeField = 60; Assert.Equal(60, duckInterface.InternalValueTypeField); Assert.Equal(60, duckAbstract.InternalValueTypeField); - Assert.Equal(60, duckVirtual.InternalValueTypeField); - - // * - + Assert.Equal(60, duckVirtual.InternalValueTypeField); + + // * + Assert.Equal(42, duckInterface.ProtectedValueTypeField); Assert.Equal(42, duckAbstract.ProtectedValueTypeField); Assert.Equal(42, duckVirtual.ProtectedValueTypeField); @@ -256,10 +256,10 @@ public void Fields(object obscureObject) duckVirtual.ProtectedValueTypeField = 60; Assert.Equal(60, duckInterface.ProtectedValueTypeField); Assert.Equal(60, duckAbstract.ProtectedValueTypeField); - Assert.Equal(60, duckVirtual.ProtectedValueTypeField); - - // * - + Assert.Equal(60, duckVirtual.ProtectedValueTypeField); + + // * + Assert.Equal(43, duckInterface.PrivateValueTypeField); Assert.Equal(43, duckAbstract.PrivateValueTypeField); Assert.Equal(43, duckVirtual.PrivateValueTypeField); @@ -305,10 +305,10 @@ public void NullableOfKnown(object obscureObject) duckVirtual.PublicStaticNullableIntField = null; Assert.Null(duckInterface.PublicStaticNullableIntField); Assert.Null(duckAbstract.PublicStaticNullableIntField); - Assert.Null(duckVirtual.PublicStaticNullableIntField); - - // * - + Assert.Null(duckVirtual.PublicStaticNullableIntField); + + // * + Assert.Null(duckInterface.PrivateStaticNullableIntField); Assert.Null(duckAbstract.PrivateStaticNullableIntField); Assert.Null(duckVirtual.PrivateStaticNullableIntField); @@ -326,10 +326,10 @@ public void NullableOfKnown(object obscureObject) duckVirtual.PrivateStaticNullableIntField = null; Assert.Null(duckInterface.PrivateStaticNullableIntField); Assert.Null(duckAbstract.PrivateStaticNullableIntField); - Assert.Null(duckVirtual.PrivateStaticNullableIntField); - - // * - + Assert.Null(duckVirtual.PrivateStaticNullableIntField); + + // * + Assert.Null(duckInterface.PublicNullableIntField); Assert.Null(duckAbstract.PublicNullableIntField); Assert.Null(duckVirtual.PublicNullableIntField); @@ -347,10 +347,10 @@ public void NullableOfKnown(object obscureObject) duckVirtual.PublicNullableIntField = null; Assert.Null(duckInterface.PublicNullableIntField); Assert.Null(duckAbstract.PublicNullableIntField); - Assert.Null(duckVirtual.PublicNullableIntField); - - // * - + Assert.Null(duckVirtual.PublicNullableIntField); + + // * + Assert.Null(duckInterface.PrivateNullableIntField); Assert.Null(duckAbstract.PrivateNullableIntField); Assert.Null(duckVirtual.PrivateNullableIntField); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/MethodTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/MethodTests.cs index ee55c5a7c..7a94df3d9 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/MethodTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/MethodTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using Elastic.Apm.Profiler.Managed.DuckTyping; @@ -31,34 +31,34 @@ public void ReturnMethods(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // Integers + var duckVirtual = obscureObject.DuckCast(); + + // Integers Assert.Equal(20, duckInterface.Sum(10, 10)); Assert.Equal(20, duckAbstract.Sum(10, 10)); - Assert.Equal(20, duckVirtual.Sum(10, 10)); - - // Float + Assert.Equal(20, duckVirtual.Sum(10, 10)); + + // Float Assert.Equal(20f, duckInterface.Sum(10f, 10f)); Assert.Equal(20f, duckAbstract.Sum(10f, 10f)); - Assert.Equal(20f, duckVirtual.Sum(10f, 10f)); - - // Double + Assert.Equal(20f, duckVirtual.Sum(10f, 10f)); + + // Double Assert.Equal(20d, duckInterface.Sum(10d, 10d)); Assert.Equal(20d, duckAbstract.Sum(10d, 10d)); - Assert.Equal(20d, duckVirtual.Sum(10d, 10d)); - - // Short + Assert.Equal(20d, duckVirtual.Sum(10d, 10d)); + + // Short Assert.Equal((short)20, duckInterface.Sum((short)10, (short)10)); Assert.Equal((short)20, duckAbstract.Sum((short)10, (short)10)); - Assert.Equal((short)20, duckVirtual.Sum((short)10, (short)10)); - - // Enum + Assert.Equal((short)20, duckVirtual.Sum((short)10, (short)10)); + + // Enum Assert.Equal(TestEnum2.Segundo, duckInterface.ShowEnum(TestEnum2.Segundo)); Assert.Equal(TestEnum2.Segundo, duckAbstract.ShowEnum(TestEnum2.Segundo)); - Assert.Equal(TestEnum2.Segundo, duckVirtual.ShowEnum(TestEnum2.Segundo)); - - // Internal Sum + Assert.Equal(TestEnum2.Segundo, duckVirtual.ShowEnum(TestEnum2.Segundo)); + + // Internal Sum Assert.Equal(20, duckInterface.InternalSum(10, 10)); Assert.Equal(20, duckAbstract.InternalSum(10, 10)); Assert.Equal(20, duckVirtual.InternalSum(10, 10)); @@ -76,19 +76,19 @@ public void VoidMethods(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // Void with object + var duckVirtual = obscureObject.DuckCast(); + + // Void with object duckInterface.Add("Key01", new ObscureObject.DummyFieldObject()); duckAbstract.Add("Key02", new ObscureObject.DummyFieldObject()); - duckVirtual.Add("Key03", new ObscureObject.DummyFieldObject()); - - // Void with int + duckVirtual.Add("Key03", new ObscureObject.DummyFieldObject()); + + // Void with int duckInterface.Add("KeyInt01", 42); duckAbstract.Add("KeyInt02", 42); - duckVirtual.Add("KeyInt03", 42); - - // Void with string + duckVirtual.Add("KeyInt03", 42); + + // Void with string duckInterface.Add("KeyString01", "Value01"); duckAbstract.Add("KeyString02", "Value02"); duckVirtual.Add("KeyString03", "Value03"); @@ -100,9 +100,9 @@ public void RefParametersMethods(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // Ref parameter + var duckVirtual = obscureObject.DuckCast(); + + // Ref parameter var value = 4; duckInterface.Pow2(ref value); duckAbstract.Pow2(ref value); @@ -113,18 +113,18 @@ public void RefParametersMethods(object obscureObject) duckInterface.GetReference(ref value); duckAbstract.GetReference(ref value); duckVirtual.GetReference(ref value); - Assert.Equal(65536, value); - - // Ref object parameter - object objValue = 4; - // ReSharper disable once SuggestVarOrType_BuiltInTypes + Assert.Equal(65536, value); + + // Ref object parameter + object objValue = 4; + // ReSharper disable once SuggestVarOrType_BuiltInTypes object objValue2 = objValue; duckInterface.GetReferenceObject(ref objValue); duckAbstract.GetReferenceObject(ref objValue); duckVirtual.GetReferenceObject(ref objValue); - Assert.Equal(65536, (int)objValue); - - // Ref DuckType + Assert.Equal(65536, (int)objValue); + + // Ref DuckType IDummyFieldObject refDuckType; refDuckType = null; Assert.True(duckInterface.TryGetReference(ref refDuckType)); @@ -132,9 +132,9 @@ public void RefParametersMethods(object obscureObject) Assert.True(duckAbstract.TryGetReference(ref refDuckType)); Assert.Equal(101, refDuckType.MagicNumber); Assert.True(duckVirtual.TryGetReference(ref refDuckType)); - Assert.Equal(102, refDuckType.MagicNumber); - - // Ref object + Assert.Equal(102, refDuckType.MagicNumber); + + // Ref object object refObject; refObject = null; Assert.True(duckInterface.TryGetReferenceObject(ref refObject)); @@ -142,18 +142,18 @@ public void RefParametersMethods(object obscureObject) Assert.True(duckAbstract.TryGetReferenceObject(ref refObject)); Assert.Equal(101, refObject.DuckCast().MagicNumber); Assert.True(duckVirtual.TryGetReferenceObject(ref refObject)); - Assert.Equal(102, refObject.DuckCast().MagicNumber); - - // Private internal parameter type with duck type output + Assert.Equal(102, refObject.DuckCast().MagicNumber); + + // Private internal parameter type with duck type output refDuckType = null; Assert.True(duckInterface.TryGetPrivateReference(ref refDuckType)); Assert.Equal(100, refDuckType.MagicNumber); Assert.True(duckAbstract.TryGetPrivateReference(ref refDuckType)); Assert.Equal(101, refDuckType.MagicNumber); Assert.True(duckVirtual.TryGetPrivateReference(ref refDuckType)); - Assert.Equal(102, refDuckType.MagicNumber); - - // Private internal parameter type object output + Assert.Equal(102, refDuckType.MagicNumber); + + // Private internal parameter type object output refObject = null; Assert.True(duckInterface.TryGetPrivateReferenceObject(ref refObject)); Assert.Equal(100, refObject.DuckCast().MagicNumber); @@ -169,27 +169,27 @@ public void OutParametersMethods(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // Out parameter + var duckVirtual = obscureObject.DuckCast(); + + // Out parameter int outValue; duckInterface.GetOutput(out outValue); Assert.Equal(42, outValue); duckAbstract.GetOutput(out outValue); Assert.Equal(42, outValue); duckVirtual.GetOutput(out outValue); - Assert.Equal(42, outValue); - - // Out object parameter + Assert.Equal(42, outValue); + + // Out object parameter object outObjectValue; duckInterface.GetOutputObject(out outObjectValue); Assert.Equal(42, (int)outObjectValue); duckAbstract.GetOutputObject(out outObjectValue); Assert.Equal(42, (int)outObjectValue); duckVirtual.GetOutputObject(out outObjectValue); - Assert.Equal(42, (int)outObjectValue); - - // Duck type output + Assert.Equal(42, (int)outObjectValue); + + // Duck type output IDummyFieldObject outDuckType; Assert.True(duckInterface.TryGetObscure(out outDuckType)); Assert.NotNull(outDuckType); @@ -201,9 +201,9 @@ public void OutParametersMethods(object obscureObject) Assert.True(duckVirtual.TryGetObscure(out outDuckType)); Assert.NotNull(outDuckType); - Assert.Equal(99, outDuckType.MagicNumber); - - // Object output + Assert.Equal(99, outDuckType.MagicNumber); + + // Object output object outObject; Assert.True(duckInterface.TryGetObscureObject(out outObject)); Assert.NotNull(outObject); @@ -215,9 +215,9 @@ public void OutParametersMethods(object obscureObject) Assert.True(duckVirtual.TryGetObscureObject(out outObject)); Assert.NotNull(outObject); - Assert.Equal(99, outObject.DuckCast().MagicNumber); - - // Private internal parameter type with duck type output + Assert.Equal(99, outObject.DuckCast().MagicNumber); + + // Private internal parameter type with duck type output Assert.True(duckInterface.TryGetPrivateObscure(out outDuckType)); Assert.NotNull(outDuckType); Assert.Equal(99, outDuckType.MagicNumber); @@ -228,9 +228,9 @@ public void OutParametersMethods(object obscureObject) Assert.True(duckVirtual.TryGetPrivateObscure(out outDuckType)); Assert.NotNull(outDuckType); - Assert.Equal(99, outDuckType.MagicNumber); - - // Private internal parameter type object output + Assert.Equal(99, outDuckType.MagicNumber); + + // Private internal parameter type object output Assert.True(duckInterface.TryGetPrivateObscureObject(out outObject)); Assert.NotNull(outObject); Assert.Equal(99, outObject.DuckCast().MagicNumber); @@ -256,25 +256,30 @@ public void DictionaryDuckTypeExample() duckInterface.Add("K", "V"); Assert.True(duckInterface.ContainsKey("K")); - if (duckInterface.ContainsKey("K")) Assert.True(duckInterface.Remove("K")); + if (duckInterface.ContainsKey("K")) + Assert.True(duckInterface.Remove("K")); - if (duckInterface.TryGetValue("Key01", out var value)) Assert.Equal("Value01", value); + if (duckInterface.TryGetValue("Key01", out var value)) + Assert.Equal("Value01", value); Assert.Equal("Value02", duckInterface["Key02"]); Assert.Equal(2, duckInterface.Count); - foreach (var val in duckInterface) Assert.NotNull(val.Key); + foreach (var val in duckInterface) + Assert.NotNull(val.Key); - if (duckInterface.TryGetValueInObject("Key02", out var objValue)) Assert.NotNull(objValue); + if (duckInterface.TryGetValueInObject("Key02", out var objValue)) + Assert.NotNull(objValue); - if (duckInterface.TryGetValueInDuckChaining("Key02", out var dictioValue)) Assert.NotNull(dictioValue); + if (duckInterface.TryGetValueInDuckChaining("Key02", out var dictioValue)) + Assert.NotNull(dictioValue); } [Theory] [MemberData(nameof(Data))] public void DefaultGenericsMethods(object obscureObject) - { + { #if NET452 if (!obscureObject.GetType().IsPublic && !obscureObject.GetType().IsNestedPublic) { @@ -296,37 +301,37 @@ public void DefaultGenericsMethods(object obscureObject) return; } #endif - + var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // GetDefault int + var duckVirtual = obscureObject.DuckCast(); + + // GetDefault int Assert.Equal(0, duckInterface.GetDefault()); Assert.Equal(0, duckAbstract.GetDefault()); - Assert.Equal(0, duckVirtual.GetDefault()); - - // GetDefault double + Assert.Equal(0, duckVirtual.GetDefault()); + + // GetDefault double Assert.Equal(0d, duckInterface.GetDefault()); Assert.Equal(0d, duckAbstract.GetDefault()); - Assert.Equal(0d, duckVirtual.GetDefault()); - - // GetDefault string + Assert.Equal(0d, duckVirtual.GetDefault()); + + // GetDefault string Assert.Null(duckInterface.GetDefault()); Assert.Null(duckAbstract.GetDefault()); - Assert.Null(duckVirtual.GetDefault()); - - // Wrap ints + Assert.Null(duckVirtual.GetDefault()); + + // Wrap ints var wrapper = duckInterface.Wrap(10, 20); Assert.Equal(10, wrapper.Item1); - Assert.Equal(20, wrapper.Item2); - - // Wrap string + Assert.Equal(20, wrapper.Item2); + + // Wrap string var wrapper2 = duckAbstract.Wrap("Hello", "World"); Assert.Equal("Hello", wrapper2.Item1); - Assert.Equal("World", wrapper2.Item2); - - // Wrap object + Assert.Equal("World", wrapper2.Item2); + + // Wrap object var wrapper3 = duckAbstract.Wrap(null, "World"); Assert.Null(wrapper3.Item1); Assert.Equal("World", wrapper3.Item2); @@ -347,19 +352,19 @@ public void GenericsWithAttributeResolution(object obscureObject) result = duckInterface.WrapIntString(42, "All"); Assert.Equal(42, result.Item1); - Assert.Equal("All", result.Item2); - - // ... - + Assert.Equal("All", result.Item2); + + // ... + Assert.Equal(0, duckAttribute.GetDefaultInt()); Assert.Null(duckAttribute.GetDefaultString()); result = duckAttribute.WrapIntString(42, "All"); Assert.Equal(42, result.Item1); - Assert.Equal("All", result.Item2); - - // ... - + Assert.Equal("All", result.Item2); + + // ... + Assert.Equal(0, duckVirtual.GetDefaultInt()); Assert.Null(duckVirtual.GetDefaultString()); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/AbstractGenericsWithAttribute.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/AbstractGenericsWithAttribute.cs index 377d5c2e5..fdc7626f2 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/AbstractGenericsWithAttribute.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/AbstractGenericsWithAttribute.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using Elastic.Apm.Profiler.Managed.DuckTyping; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/DefaultGenericMethodDuckTypeAbstractClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/DefaultGenericMethodDuckTypeAbstractClass.cs index ca0cf6b6f..89f74088e 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/DefaultGenericMethodDuckTypeAbstractClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/DefaultGenericMethodDuckTypeAbstractClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Methods.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/DefaultGenericMethodDuckTypeVirtualClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/DefaultGenericMethodDuckTypeVirtualClass.cs index 0d1828f1f..176bd9d2e 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/DefaultGenericMethodDuckTypeVirtualClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/DefaultGenericMethodDuckTypeVirtualClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Methods.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDefaultGenericMethodDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDefaultGenericMethodDuckType.cs index 4eed51727..ef32a05d2 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDefaultGenericMethodDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDefaultGenericMethodDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Methods.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDictioDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDictioDuckType.cs index 8ba881cde..627c40b5a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDictioDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDictioDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Collections.Generic; using Elastic.Apm.Profiler.Managed.DuckTyping; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDictioValue.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDictioValue.cs index aeb66dfd2..5889ff664 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDictioValue.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDictioValue.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Methods.ProxiesDefinitions { public interface IDictioValue { } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDummyFieldObject.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDummyFieldObject.cs index 92491860f..9733dafbe 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDummyFieldObject.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IDummyFieldObject.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Methods.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IGenericsWithAttribute.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IGenericsWithAttribute.cs index a0e19e626..d9f44e76a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IGenericsWithAttribute.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IGenericsWithAttribute.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using Elastic.Apm.Profiler.Managed.DuckTyping; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IObscureDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IObscureDuckType.cs index 75f341ea6..1b5d46f52 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IObscureDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/IObscureDuckType.cs @@ -1,25 +1,25 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Methods.ProxiesDefinitions { public interface IObscureDuckType - { + { #if INTERFACE_DEFAULTS int Sum(int a, int b) => a + b; #else - int Sum(int a, int b); + int Sum(int a, int b); #endif - + float Sum(float a, float b); double Sum(double a, double b); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs index df4a219fd..70a90a5ea 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Methods.ProxiesDefinitions @@ -69,8 +69,8 @@ public abstract class ObscureDuckTypeAbstractClass public abstract bool TryGetPrivateReferenceObject(ref object obj); public void NormalMethod() - { - // . + { + // . } public abstract IDummyFieldObject Bypass(IDummyFieldObject obj); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs index 8ea775db4..a8db68b06 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Methods.ProxiesDefinitions @@ -85,8 +85,8 @@ public virtual bool TryGetPrivateObscureObject(out object obj) public virtual bool TryGetPrivateReferenceObject(ref object obj) => false; public void NormalMethod() - { - // . + { + // . } public virtual IDummyFieldObject Bypass(IDummyFieldObject obj) => null; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/TestEnum2.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/TestEnum2.cs index 09c202d49..c9eb63a53 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/TestEnum2.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/TestEnum2.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Methods.ProxiesDefinitions { public enum TestEnum2 diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/VirtualGenericsWithAttribute.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/VirtualGenericsWithAttribute.cs index e0f2f3142..4aed0f854 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/VirtualGenericsWithAttribute.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Methods/ProxiesDefinitions/VirtualGenericsWithAttribute.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using Elastic.Apm.Profiler.Managed.DuckTyping; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/ObscureObject.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/ObscureObject.cs index b83cb28a7..6bd53092a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/ObscureObject.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/ObscureObject.cs @@ -1,23 +1,23 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using System.Collections.Generic; using System.Threading.Tasks; -using Elastic.Apm.Profiler.Managed.DuckTyping; - -// ReSharper disable InconsistentNaming -// ReSharper disable FieldCanBeMadeReadOnly.Local - +using Elastic.Apm.Profiler.Managed.DuckTyping; + +// ReSharper disable InconsistentNaming +// ReSharper disable FieldCanBeMadeReadOnly.Local + #pragma warning disable 414 - + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping { public class ObscureObject @@ -40,17 +40,17 @@ public class ObscureObject public static object GetPropertyInternalObject() => propertyInternalObject; - public static object GetPropertyPrivateObject() => propertyPrivateObject; - - // *** + public static object GetPropertyPrivateObject() => propertyPrivateObject; + + // *** public enum TestEnum { First, Second - } - - // *** - + } + + // *** + public class DummyFieldObject { internal static DummyFieldObject Default = new DummyFieldObject(); @@ -75,10 +75,10 @@ private class PrivateDummyFieldObject get => index; set { } } - } - - // *** - + } + + // *** + public class FieldPublicObject { public static readonly int _publicStaticReadonlyValueTypeField = 10; @@ -99,10 +99,10 @@ public class FieldPublicObject public int _publicValueTypeField = 40; internal int _internalValueTypeField = 41; protected int _protectedValueTypeField = 42; - private int _privateValueTypeField = 43; - - // *** - + private int _privateValueTypeField = 43; + + // *** + public static readonly string _publicStaticReadonlyReferenceTypeField = "10"; internal static readonly string _internalStaticReadonlyReferenceTypeField = "11"; protected static readonly string _protectedStaticReadonlyReferenceTypeField = "12"; @@ -121,10 +121,10 @@ public class FieldPublicObject public string _publicReferenceTypeField = "40"; internal string _internalReferenceTypeField = "41"; protected string _protectedReferenceTypeField = "42"; - private string _privateReferenceTypeField = "43"; - - // *** - + private string _privateReferenceTypeField = "43"; + + // *** + public static readonly DummyFieldObject _publicStaticReadonlySelfTypeField = DummyFieldObject.Default; internal static readonly DummyFieldObject _internalStaticReadonlySelfTypeField = DummyFieldObject.Default; protected static readonly DummyFieldObject _protectedStaticReadonlySelfTypeField = DummyFieldObject.Default; @@ -143,10 +143,10 @@ public class FieldPublicObject public DummyFieldObject _publicSelfTypeField = DummyFieldObject.Default; internal DummyFieldObject _internalSelfTypeField = DummyFieldObject.Default; protected DummyFieldObject _protectedSelfTypeField = DummyFieldObject.Default; - private DummyFieldObject _privateSelfTypeField = DummyFieldObject.Default; - - // *** - + private DummyFieldObject _privateSelfTypeField = DummyFieldObject.Default; + + // *** + public static int? _publicStaticNullableIntField = null; private static int? _privateStaticNullableIntField = null; public int? _publicNullableIntField = null; @@ -173,10 +173,10 @@ internal class FieldInternalObject public int _publicValueTypeField = 40; internal int _internalValueTypeField = 41; protected int _protectedValueTypeField = 42; - private int _privateValueTypeField = 43; - - // *** - + private int _privateValueTypeField = 43; + + // *** + public static readonly string _publicStaticReadonlyReferenceTypeField = "10"; internal static readonly string _internalStaticReadonlyReferenceTypeField = "11"; protected static readonly string _protectedStaticReadonlyReferenceTypeField = "12"; @@ -195,10 +195,10 @@ internal class FieldInternalObject public string _publicReferenceTypeField = "40"; internal string _internalReferenceTypeField = "41"; protected string _protectedReferenceTypeField = "42"; - private string _privateReferenceTypeField = "43"; - - // *** - + private string _privateReferenceTypeField = "43"; + + // *** + public static readonly DummyFieldObject _publicStaticReadonlySelfTypeField = DummyFieldObject.Default; internal static readonly DummyFieldObject _internalStaticReadonlySelfTypeField = DummyFieldObject.Default; protected static readonly DummyFieldObject _protectedStaticReadonlySelfTypeField = DummyFieldObject.Default; @@ -217,10 +217,10 @@ internal class FieldInternalObject public DummyFieldObject _publicSelfTypeField = DummyFieldObject.Default; internal DummyFieldObject _internalSelfTypeField = DummyFieldObject.Default; protected DummyFieldObject _protectedSelfTypeField = DummyFieldObject.Default; - private DummyFieldObject _privateSelfTypeField = DummyFieldObject.Default; - - // *** - + private DummyFieldObject _privateSelfTypeField = DummyFieldObject.Default; + + // *** + public static int? _publicStaticNullableIntField = null; private static int? _privateStaticNullableIntField = null; public int? _publicNullableIntField = null; @@ -247,10 +247,10 @@ private class FieldPrivateObject public int _publicValueTypeField = 40; internal int _internalValueTypeField = 41; protected int _protectedValueTypeField = 42; - private int _privateValueTypeField = 43; - - // *** - + private int _privateValueTypeField = 43; + + // *** + public static readonly string _publicStaticReadonlyReferenceTypeField = "10"; internal static readonly string _internalStaticReadonlyReferenceTypeField = "11"; protected static readonly string _protectedStaticReadonlyReferenceTypeField = "12"; @@ -269,10 +269,10 @@ private class FieldPrivateObject public string _publicReferenceTypeField = "40"; internal string _internalReferenceTypeField = "41"; protected string _protectedReferenceTypeField = "42"; - private string _privateReferenceTypeField = "43"; - - // *** - + private string _privateReferenceTypeField = "43"; + + // *** + public static readonly DummyFieldObject _publicStaticReadonlySelfTypeField = DummyFieldObject.Default; internal static readonly DummyFieldObject _internalStaticReadonlySelfTypeField = DummyFieldObject.Default; protected static readonly DummyFieldObject _protectedStaticReadonlySelfTypeField = DummyFieldObject.Default; @@ -291,159 +291,159 @@ private class FieldPrivateObject public DummyFieldObject _publicSelfTypeField = DummyFieldObject.Default; internal DummyFieldObject _internalSelfTypeField = DummyFieldObject.Default; protected DummyFieldObject _protectedSelfTypeField = DummyFieldObject.Default; - private DummyFieldObject _privateSelfTypeField = DummyFieldObject.Default; - - // *** - + private DummyFieldObject _privateSelfTypeField = DummyFieldObject.Default; + + // *** + public static int? _publicStaticNullableIntField = null; private static int? _privateStaticNullableIntField = null; public int? _publicNullableIntField = null; private int? _privateNullableIntField = null; - } - - // *** - + } + + // *** + public class PropertyPublicObject { private Dictionary _dictioInt = new Dictionary(); - private Dictionary _dictioString = new Dictionary(); - - // ********* - + private Dictionary _dictioString = new Dictionary(); + + // ********* + public static int PublicStaticGetValueType { get; } = 10; internal static int InternalStaticGetValueType { get; } = 11; protected static int ProtectedStaticGetValueType { get; } = 12; - private static int PrivateStaticGetValueType { get; } = 13; - - // * - + private static int PrivateStaticGetValueType { get; } = 13; + + // * + public static int PublicStaticGetSetValueType { get; set; } = 20; internal static int InternalStaticGetSetValueType { get; set; } = 21; protected static int ProtectedStaticGetSetValueType { get; set; } = 22; - private static int PrivateStaticGetSetValueType { get; set; } = 23; - - // * - + private static int PrivateStaticGetSetValueType { get; set; } = 23; + + // * + public int PublicGetValueType { get; } = 30; internal int InternalGetValueType { get; } = 31; protected int ProtectedGetValueType { get; } = 32; - private int PrivateGetValueType { get; } = 33; - - // * - + private int PrivateGetValueType { get; } = 33; + + // * + public int PublicGetSetValueType { get; set; } = 40; internal int InternalGetSetValueType { get; set; } = 41; protected int ProtectedGetSetValueType { get; set; } = 42; - private int PrivateGetSetValueType { get; set; } = 43; - - // ********* - + private int PrivateGetSetValueType { get; set; } = 43; + + // ********* + public static string PublicStaticGetReferenceType { get; } = "10"; internal static string InternalStaticGetReferenceType { get; } = "11"; protected static string ProtectedStaticGetReferenceType { get; } = "12"; - private static string PrivateStaticGetReferenceType { get; } = "13"; - - // * - + private static string PrivateStaticGetReferenceType { get; } = "13"; + + // * + public static string PublicStaticGetSetReferenceType { get; set; } = "20"; internal static string InternalStaticGetSetReferenceType { get; set; } = "21"; protected static string ProtectedStaticGetSetReferenceType { get; set; } = "22"; - private static string PrivateStaticGetSetReferenceType { get; set; } = "23"; - - // * - + private static string PrivateStaticGetSetReferenceType { get; set; } = "23"; + + // * + public string PublicGetReferenceType { get; } = "30"; internal string InternalGetReferenceType { get; } = "31"; protected string ProtectedGetReferenceType { get; } = "32"; - private string PrivateGetReferenceType { get; } = "33"; - - // * - + private string PrivateGetReferenceType { get; } = "33"; + + // * + public string PublicGetSetReferenceType { get; set; } = "40"; internal string InternalGetSetReferenceType { get; set; } = "41"; protected string ProtectedGetSetReferenceType { get; set; } = "42"; - private string PrivateGetSetReferenceType { get; set; } = "43"; - - // ********* - + private string PrivateGetSetReferenceType { get; set; } = "43"; + + // ********* + public static DummyFieldObject PublicStaticGetSelfType { get; } = DummyFieldObject.Default; internal static DummyFieldObject InternalStaticGetSelfType { get; } = DummyFieldObject.Default; protected static DummyFieldObject ProtectedStaticGetSelfType { get; } = DummyFieldObject.Default; - private static DummyFieldObject PrivateStaticGetSelfType { get; } = DummyFieldObject.Default; - - // * - + private static DummyFieldObject PrivateStaticGetSelfType { get; } = DummyFieldObject.Default; + + // * + public static DummyFieldObject PublicStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; internal static DummyFieldObject InternalStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; protected static DummyFieldObject ProtectedStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; - private static DummyFieldObject PrivateStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; - - // * - + private static DummyFieldObject PrivateStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; + + // * + public DummyFieldObject PublicGetSelfType { get; } = DummyFieldObject.Default; internal DummyFieldObject InternalGetSelfType { get; } = DummyFieldObject.Default; protected DummyFieldObject ProtectedGetSelfType { get; } = DummyFieldObject.Default; - private DummyFieldObject PrivateGetSelfType { get; } = DummyFieldObject.Default; - - // * - + private DummyFieldObject PrivateGetSelfType { get; } = DummyFieldObject.Default; + + // * + public DummyFieldObject PublicGetSetSelfType { get; set; } = DummyFieldObject.Default; internal DummyFieldObject InternalGetSetSelfType { get; set; } = DummyFieldObject.Default; protected DummyFieldObject ProtectedGetSetSelfType { get; set; } = DummyFieldObject.Default; - private DummyFieldObject PrivateGetSetSelfType { get; set; } = DummyFieldObject.Default; - - // *** - - private PrivateDummyFieldObject PrivateDummyGetSetSelfType { get; set; } = PrivateDummyFieldObject.Default; - - // *** - + private DummyFieldObject PrivateGetSetSelfType { get; set; } = DummyFieldObject.Default; + + // *** + + private PrivateDummyFieldObject PrivateDummyGetSetSelfType { get; set; } = PrivateDummyFieldObject.Default; + + // *** + public static int? PublicStaticNullableInt { get; set; } private static int? PrivateStaticNullableInt { get; set; } public int? PublicNullableInt { get; set; } - private int? PrivateNullableInt { get; set; } - - // *** - + private int? PrivateNullableInt { get; set; } + + // *** + public int this[int index] { get => _dictioInt[index]; @@ -454,13 +454,13 @@ public class PropertyPublicObject { get => _dictioString[index]; set => _dictioString[index] = value; - } - - // *** - - public TaskStatus Status { get; set; } = TaskStatus.RanToCompletion; - - // *** Methods + } + + // *** + + public TaskStatus Status { get; set; } = TaskStatus.RanToCompletion; + + // *** Methods public int Sum(int a, int b) => a + b; public float Sum(float a, float b) => a + b; @@ -527,134 +527,134 @@ internal class PropertyInternalObject protected static int ProtectedStaticGetValueType { get; } = 12; - private static int PrivateStaticGetValueType { get; } = 13; - - // * - + private static int PrivateStaticGetValueType { get; } = 13; + + // * + public static int PublicStaticGetSetValueType { get; set; } = 20; internal static int InternalStaticGetSetValueType { get; set; } = 21; protected static int ProtectedStaticGetSetValueType { get; set; } = 22; - private static int PrivateStaticGetSetValueType { get; set; } = 23; - - // * - + private static int PrivateStaticGetSetValueType { get; set; } = 23; + + // * + public int PublicGetValueType { get; } = 30; internal int InternalGetValueType { get; } = 31; protected int ProtectedGetValueType { get; } = 32; - private int PrivateGetValueType { get; } = 33; - - // * - + private int PrivateGetValueType { get; } = 33; + + // * + public int PublicGetSetValueType { get; set; } = 40; internal int InternalGetSetValueType { get; set; } = 41; protected int ProtectedGetSetValueType { get; set; } = 42; - private int PrivateGetSetValueType { get; set; } = 43; - - // ********* - + private int PrivateGetSetValueType { get; set; } = 43; + + // ********* + public static string PublicStaticGetReferenceType { get; } = "10"; internal static string InternalStaticGetReferenceType { get; } = "11"; protected static string ProtectedStaticGetReferenceType { get; } = "12"; - private static string PrivateStaticGetReferenceType { get; } = "13"; - - // * - + private static string PrivateStaticGetReferenceType { get; } = "13"; + + // * + public static string PublicStaticGetSetReferenceType { get; set; } = "20"; internal static string InternalStaticGetSetReferenceType { get; set; } = "21"; protected static string ProtectedStaticGetSetReferenceType { get; set; } = "22"; - private static string PrivateStaticGetSetReferenceType { get; set; } = "23"; - - // * - + private static string PrivateStaticGetSetReferenceType { get; set; } = "23"; + + // * + public string PublicGetReferenceType { get; } = "30"; internal string InternalGetReferenceType { get; } = "31"; protected string ProtectedGetReferenceType { get; } = "32"; - private string PrivateGetReferenceType { get; } = "33"; - - // * - + private string PrivateGetReferenceType { get; } = "33"; + + // * + public string PublicGetSetReferenceType { get; set; } = "40"; internal string InternalGetSetReferenceType { get; set; } = "41"; protected string ProtectedGetSetReferenceType { get; set; } = "42"; - private string PrivateGetSetReferenceType { get; set; } = "43"; - - // ********* - + private string PrivateGetSetReferenceType { get; set; } = "43"; + + // ********* + public static DummyFieldObject PublicStaticGetSelfType { get; } = DummyFieldObject.Default; internal static DummyFieldObject InternalStaticGetSelfType { get; } = DummyFieldObject.Default; protected static DummyFieldObject ProtectedStaticGetSelfType { get; } = DummyFieldObject.Default; - private static DummyFieldObject PrivateStaticGetSelfType { get; } = DummyFieldObject.Default; - - // * - + private static DummyFieldObject PrivateStaticGetSelfType { get; } = DummyFieldObject.Default; + + // * + public static DummyFieldObject PublicStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; internal static DummyFieldObject InternalStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; protected static DummyFieldObject ProtectedStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; - private static DummyFieldObject PrivateStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; - - // * - + private static DummyFieldObject PrivateStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; + + // * + public DummyFieldObject PublicGetSelfType { get; } = DummyFieldObject.Default; internal DummyFieldObject InternalGetSelfType { get; } = DummyFieldObject.Default; protected DummyFieldObject ProtectedGetSelfType { get; } = DummyFieldObject.Default; - private DummyFieldObject PrivateGetSelfType { get; } = DummyFieldObject.Default; - - // * - + private DummyFieldObject PrivateGetSelfType { get; } = DummyFieldObject.Default; + + // * + public DummyFieldObject PublicGetSetSelfType { get; set; } = DummyFieldObject.Default; internal DummyFieldObject InternalGetSetSelfType { get; set; } = DummyFieldObject.Default; protected DummyFieldObject ProtectedGetSetSelfType { get; set; } = DummyFieldObject.Default; - private DummyFieldObject PrivateGetSetSelfType { get; set; } = DummyFieldObject.Default; - - // *** - - private PrivateDummyFieldObject PrivateDummyGetSetSelfType { get; set; } = PrivateDummyFieldObject.Default; - - // *** - + private DummyFieldObject PrivateGetSetSelfType { get; set; } = DummyFieldObject.Default; + + // *** + + private PrivateDummyFieldObject PrivateDummyGetSetSelfType { get; set; } = PrivateDummyFieldObject.Default; + + // *** + public static int? PublicStaticNullableInt { get; set; } private static int? PrivateStaticNullableInt { get; set; } public int? PublicNullableInt { get; set; } - private int? PrivateNullableInt { get; set; } - - // *** - + private int? PrivateNullableInt { get; set; } + + // *** + public int this[int index] { get => _dictioInt[index]; @@ -665,13 +665,13 @@ internal class PropertyInternalObject { get => _dictioString[index]; set => _dictioString[index] = value; - } - - // *** - - public TaskStatus Status { get; set; } = TaskStatus.RanToCompletion; - - // *** Methods + } + + // *** + + public TaskStatus Status { get; set; } = TaskStatus.RanToCompletion; + + // *** Methods public int Sum(int a, int b) => a + b; public float Sum(float a, float b) => a + b; @@ -738,133 +738,133 @@ private class PropertyPrivateObject protected static int ProtectedStaticGetValueType { get; } = 12; - private static int PrivateStaticGetValueType { get; } = 13; - - // * - + private static int PrivateStaticGetValueType { get; } = 13; + + // * + public static int PublicStaticGetSetValueType { get; set; } = 20; internal static int InternalStaticGetSetValueType { get; set; } = 21; protected static int ProtectedStaticGetSetValueType { get; set; } = 22; - private static int PrivateStaticGetSetValueType { get; set; } = 23; - - // * - + private static int PrivateStaticGetSetValueType { get; set; } = 23; + + // * + public int PublicGetValueType { get; } = 30; internal int InternalGetValueType { get; } = 31; protected int ProtectedGetValueType { get; } = 32; - private int PrivateGetValueType { get; } = 33; - - // * - + private int PrivateGetValueType { get; } = 33; + + // * + public int PublicGetSetValueType { get; set; } = 40; internal int InternalGetSetValueType { get; set; } = 41; protected int ProtectedGetSetValueType { get; set; } = 42; - private int PrivateGetSetValueType { get; set; } = 43; - - // ********* - + private int PrivateGetSetValueType { get; set; } = 43; + + // ********* + public static string PublicStaticGetReferenceType { get; } = "10"; internal static string InternalStaticGetReferenceType { get; } = "11"; protected static string ProtectedStaticGetReferenceType { get; } = "12"; - private static string PrivateStaticGetReferenceType { get; } = "13"; - - // * - + private static string PrivateStaticGetReferenceType { get; } = "13"; + + // * + public static string PublicStaticGetSetReferenceType { get; set; } = "20"; internal static string InternalStaticGetSetReferenceType { get; set; } = "21"; protected static string ProtectedStaticGetSetReferenceType { get; set; } = "22"; - private static string PrivateStaticGetSetReferenceType { get; set; } = "23"; - - // * - + private static string PrivateStaticGetSetReferenceType { get; set; } = "23"; + + // * + public string PublicGetReferenceType { get; } = "30"; internal string InternalGetReferenceType { get; } = "31"; protected string ProtectedGetReferenceType { get; } = "32"; - private string PrivateGetReferenceType { get; } = "33"; - - // * - + private string PrivateGetReferenceType { get; } = "33"; + + // * + public string PublicGetSetReferenceType { get; set; } = "40"; internal string InternalGetSetReferenceType { get; set; } = "41"; protected string ProtectedGetSetReferenceType { get; set; } = "42"; - private string PrivateGetSetReferenceType { get; set; } = "43"; - - // ********* - + private string PrivateGetSetReferenceType { get; set; } = "43"; + + // ********* + public static DummyFieldObject PublicStaticGetSelfType { get; } = DummyFieldObject.Default; internal static DummyFieldObject InternalStaticGetSelfType { get; } = DummyFieldObject.Default; protected static DummyFieldObject ProtectedStaticGetSelfType { get; } = DummyFieldObject.Default; - private static DummyFieldObject PrivateStaticGetSelfType { get; } = DummyFieldObject.Default; - - // * - + private static DummyFieldObject PrivateStaticGetSelfType { get; } = DummyFieldObject.Default; + + // * + public static DummyFieldObject PublicStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; internal static DummyFieldObject InternalStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; protected static DummyFieldObject ProtectedStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; - private static DummyFieldObject PrivateStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; - - // * - + private static DummyFieldObject PrivateStaticGetSetSelfType { get; set; } = DummyFieldObject.Default; + + // * + public DummyFieldObject PublicGetSelfType { get; } = DummyFieldObject.Default; internal DummyFieldObject InternalGetSelfType { get; } = DummyFieldObject.Default; protected DummyFieldObject ProtectedGetSelfType { get; } = DummyFieldObject.Default; - private DummyFieldObject PrivateGetSelfType { get; } = DummyFieldObject.Default; - - // * - + private DummyFieldObject PrivateGetSelfType { get; } = DummyFieldObject.Default; + + // * + public DummyFieldObject PublicGetSetSelfType { get; set; } = DummyFieldObject.Default; internal DummyFieldObject InternalGetSetSelfType { get; set; } = DummyFieldObject.Default; protected DummyFieldObject ProtectedGetSetSelfType { get; set; } = DummyFieldObject.Default; - private DummyFieldObject PrivateGetSetSelfType { get; set; } = DummyFieldObject.Default; - - // *** - - private PrivateDummyFieldObject PrivateDummyGetSetSelfType { get; set; } = PrivateDummyFieldObject.Default; - - // *** - + private DummyFieldObject PrivateGetSetSelfType { get; set; } = DummyFieldObject.Default; + + // *** + + private PrivateDummyFieldObject PrivateDummyGetSetSelfType { get; set; } = PrivateDummyFieldObject.Default; + + // *** + public static int? PublicStaticNullableInt { get; set; } private static int? PrivateStaticNullableInt { get; set; } public int? PublicNullableInt { get; set; } - private int? PrivateNullableInt { get; set; } - - // *** + private int? PrivateNullableInt { get; set; } + + // *** public int this[int index] { get => _dictioInt[index]; @@ -875,13 +875,13 @@ private class PropertyPrivateObject { get => _dictioString[index]; set => _dictioString[index] = value; - } - - // *** - - public TaskStatus Status { get; set; } = TaskStatus.RanToCompletion; - - // *** Methods + } + + // *** + + public TaskStatus Status { get; set; } = TaskStatus.RanToCompletion; + + // *** Methods public int Sum(int a, int b) => a + b; public float Sum(float a, float b) => a + b; @@ -935,10 +935,10 @@ private bool TryGetPrivateReference(ref PrivateDummyFieldObject obj) } private DummyFieldObject Bypass(DummyFieldObject obj) => obj; - } - - // *** - + } + + // *** + public struct PublicStruct { public int PublicGetSetValueType { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IDuckTypeUnion.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IDuckTypeUnion.cs index f50111b9b..dd0d8d86b 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IDuckTypeUnion.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IDuckTypeUnion.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ReferenceType.ProxiesDefinitions @@ -17,7 +17,8 @@ public interface IDuckTypeUnion IPublicReferenceType, IInternalReferenceType, IProtectedReferenceType, - IPrivateReferenceType { } + IPrivateReferenceType + { } public interface IPublicReferenceType { diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureDuckType.cs index c39d98c81..ae7810681 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ReferenceType.ProxiesDefinitions @@ -20,45 +20,45 @@ public interface IObscureDuckType string ProtectedStaticGetReferenceType { get; } - string PrivateStaticGetReferenceType { get; } - - // * - + string PrivateStaticGetReferenceType { get; } + + // * + string PublicStaticGetSetReferenceType { get; set; } string InternalStaticGetSetReferenceType { get; set; } string ProtectedStaticGetSetReferenceType { get; set; } - string PrivateStaticGetSetReferenceType { get; set; } - - // * - + string PrivateStaticGetSetReferenceType { get; set; } + + // * + string PublicGetReferenceType { get; } string InternalGetReferenceType { get; } string ProtectedGetReferenceType { get; } - string PrivateGetReferenceType { get; } - - // * - + string PrivateGetReferenceType { get; } + + // * + string PublicGetSetReferenceType { get; set; } string InternalGetSetReferenceType { get; set; } string ProtectedGetSetReferenceType { get; set; } - string PrivateGetSetReferenceType { get; set; } - - // * - + string PrivateGetSetReferenceType { get; set; } + + // * + [Duck(Name = "PublicStaticGetSetReferenceType")] - string PublicStaticOnlySet { set; } - - // * - + string PublicStaticOnlySet { set; } + + // * + string this[string index] { get; set; } } } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureErrorDuckType.cs index df80a03ec..02ff7e96b 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ReferenceType.ProxiesDefinitions { public interface IObscureErrorDuckType diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureStaticErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureStaticErrorDuckType.cs index 8e26734cd..b41a952f7 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureStaticErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/IObscureStaticErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ReferenceType.ProxiesDefinitions { public interface IObscureStaticErrorDuckType diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs index 4dc2dddda..71a93d56a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ReferenceType.ProxiesDefinitions { public abstract class ObscureDuckTypeAbstractClass @@ -18,40 +18,40 @@ public abstract class ObscureDuckTypeAbstractClass public abstract string ProtectedStaticGetReferenceType { get; } - public abstract string PrivateStaticGetReferenceType { get; } - - // * - + public abstract string PrivateStaticGetReferenceType { get; } + + // * + public abstract string PublicStaticGetSetReferenceType { get; set; } public abstract string InternalStaticGetSetReferenceType { get; set; } public abstract string ProtectedStaticGetSetReferenceType { get; set; } - public abstract string PrivateStaticGetSetReferenceType { get; set; } - - // * - + public abstract string PrivateStaticGetSetReferenceType { get; set; } + + // * + public abstract string PublicGetReferenceType { get; } public abstract string InternalGetReferenceType { get; } public abstract string ProtectedGetReferenceType { get; } - public abstract string PrivateGetReferenceType { get; } - - // * - + public abstract string PrivateGetReferenceType { get; } + + // * + public abstract string PublicGetSetReferenceType { get; set; } public abstract string InternalGetSetReferenceType { get; set; } public abstract string ProtectedGetSetReferenceType { get; set; } - public abstract string PrivateGetSetReferenceType { get; set; } - - // * - + public abstract string PrivateGetSetReferenceType { get; set; } + + // * + public abstract string this[string index] { get; set; } } } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeStruct.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeStruct.cs index 3acc87c27..a57d64217 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeStruct.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeStruct.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ReferenceType.ProxiesDefinitions -{ +{ #pragma warning disable 649 - + [DuckCopy] internal struct ObscureDuckTypeStruct { diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs index bfbe4e88b..8f5562150 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ReferenceType.ProxiesDefinitions { public class ObscureDuckTypeVirtualClass @@ -18,40 +18,40 @@ public class ObscureDuckTypeVirtualClass public virtual string ProtectedStaticGetReferenceType { get; } - public virtual string PrivateStaticGetReferenceType { get; } - - // * - + public virtual string PrivateStaticGetReferenceType { get; } + + // * + public virtual string PublicStaticGetSetReferenceType { get; set; } public virtual string InternalStaticGetSetReferenceType { get; set; } public virtual string ProtectedStaticGetSetReferenceType { get; set; } - public virtual string PrivateStaticGetSetReferenceType { get; set; } - - // * - + public virtual string PrivateStaticGetSetReferenceType { get; set; } + + // * + public virtual string PublicGetReferenceType { get; } public virtual string InternalGetReferenceType { get; } public virtual string ProtectedGetReferenceType { get; } - public virtual string PrivateGetReferenceType { get; } - - // * - + public virtual string PrivateGetReferenceType { get; } + + // * + public virtual string PublicGetSetReferenceType { get; set; } public virtual string InternalGetSetReferenceType { get; set; } public virtual string ProtectedGetSetReferenceType { get; set; } - public virtual string PrivateGetSetReferenceType { get; set; } - - // * - + public virtual string PrivateGetSetReferenceType { get; set; } + + // * + public virtual string this[string index] { get => default; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ReferenceTypePropertyTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ReferenceTypePropertyTests.cs index 2165da2ba..30ac52244 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ReferenceTypePropertyTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ReferenceType/ReferenceTypePropertyTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Collections.Generic; using Elastic.Apm.Profiler.Managed.DuckTyping; using Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ReferenceType.ProxiesDefinitions; @@ -46,24 +46,24 @@ public void StaticGetOnlyProperties(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * + var duckVirtual = obscureObject.DuckCast(); + + // * Assert.Equal("10", duckInterface.PublicStaticGetReferenceType); Assert.Equal("10", duckAbstract.PublicStaticGetReferenceType); - Assert.Equal("10", duckVirtual.PublicStaticGetReferenceType); - - // * + Assert.Equal("10", duckVirtual.PublicStaticGetReferenceType); + + // * Assert.Equal("11", duckInterface.InternalStaticGetReferenceType); Assert.Equal("11", duckAbstract.InternalStaticGetReferenceType); - Assert.Equal("11", duckVirtual.InternalStaticGetReferenceType); - - // * + Assert.Equal("11", duckVirtual.InternalStaticGetReferenceType); + + // * Assert.Equal("12", duckInterface.ProtectedStaticGetReferenceType); Assert.Equal("12", duckAbstract.ProtectedStaticGetReferenceType); - Assert.Equal("12", duckVirtual.ProtectedStaticGetReferenceType); - - // * + Assert.Equal("12", duckVirtual.ProtectedStaticGetReferenceType); + + // * Assert.Equal("13", duckInterface.PrivateStaticGetReferenceType); Assert.Equal("13", duckAbstract.PrivateStaticGetReferenceType); Assert.Equal("13", duckVirtual.PrivateStaticGetReferenceType); @@ -96,10 +96,10 @@ public void StaticProperties(object obscureObject) Assert.Equal("60", duckAbstract.PublicStaticGetSetReferenceType); Assert.Equal("60", duckVirtual.PublicStaticGetSetReferenceType); - duckInterface.PublicStaticGetSetReferenceType = "20"; - - // * - + duckInterface.PublicStaticGetSetReferenceType = "20"; + + // * + Assert.Equal("21", duckInterface.InternalStaticGetSetReferenceType); Assert.Equal("21", duckAbstract.InternalStaticGetSetReferenceType); Assert.Equal("21", duckVirtual.InternalStaticGetSetReferenceType); @@ -119,10 +119,10 @@ public void StaticProperties(object obscureObject) Assert.Equal("60", duckAbstract.InternalStaticGetSetReferenceType); Assert.Equal("60", duckVirtual.InternalStaticGetSetReferenceType); - duckInterface.InternalStaticGetSetReferenceType = "21"; - - // * - + duckInterface.InternalStaticGetSetReferenceType = "21"; + + // * + Assert.Equal("22", duckInterface.ProtectedStaticGetSetReferenceType); Assert.Equal("22", duckAbstract.ProtectedStaticGetSetReferenceType); Assert.Equal("22", duckVirtual.ProtectedStaticGetSetReferenceType); @@ -142,10 +142,10 @@ public void StaticProperties(object obscureObject) Assert.Equal("60", duckAbstract.ProtectedStaticGetSetReferenceType); Assert.Equal("60", duckVirtual.ProtectedStaticGetSetReferenceType); - duckInterface.ProtectedStaticGetSetReferenceType = "22"; - - // * - + duckInterface.ProtectedStaticGetSetReferenceType = "22"; + + // * + Assert.Equal("23", duckInterface.PrivateStaticGetSetReferenceType); Assert.Equal("23", duckAbstract.PrivateStaticGetSetReferenceType); Assert.Equal("23", duckVirtual.PrivateStaticGetSetReferenceType); @@ -174,24 +174,24 @@ public void GetOnlyProperties(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * + var duckVirtual = obscureObject.DuckCast(); + + // * Assert.Equal("30", duckInterface.PublicGetReferenceType); Assert.Equal("30", duckAbstract.PublicGetReferenceType); - Assert.Equal("30", duckVirtual.PublicGetReferenceType); - - // * + Assert.Equal("30", duckVirtual.PublicGetReferenceType); + + // * Assert.Equal("31", duckInterface.InternalGetReferenceType); Assert.Equal("31", duckAbstract.InternalGetReferenceType); - Assert.Equal("31", duckVirtual.InternalGetReferenceType); - - // * + Assert.Equal("31", duckVirtual.InternalGetReferenceType); + + // * Assert.Equal("32", duckInterface.ProtectedGetReferenceType); Assert.Equal("32", duckAbstract.ProtectedGetReferenceType); - Assert.Equal("32", duckVirtual.ProtectedGetReferenceType); - - // * + Assert.Equal("32", duckVirtual.ProtectedGetReferenceType); + + // * Assert.Equal("33", duckInterface.PrivateGetReferenceType); Assert.Equal("33", duckAbstract.PrivateGetReferenceType); Assert.Equal("33", duckVirtual.PrivateGetReferenceType); @@ -224,10 +224,10 @@ public void Properties(object obscureObject) Assert.Equal("60", duckAbstract.PublicGetSetReferenceType); Assert.Equal("60", duckVirtual.PublicGetSetReferenceType); - duckInterface.PublicGetSetReferenceType = "40"; - - // * - + duckInterface.PublicGetSetReferenceType = "40"; + + // * + Assert.Equal("41", duckInterface.InternalGetSetReferenceType); Assert.Equal("41", duckAbstract.InternalGetSetReferenceType); Assert.Equal("41", duckVirtual.InternalGetSetReferenceType); @@ -247,10 +247,10 @@ public void Properties(object obscureObject) Assert.Equal("60", duckAbstract.InternalGetSetReferenceType); Assert.Equal("60", duckVirtual.InternalGetSetReferenceType); - duckInterface.InternalGetSetReferenceType = "41"; - - // * - + duckInterface.InternalGetSetReferenceType = "41"; + + // * + Assert.Equal("42", duckInterface.ProtectedGetSetReferenceType); Assert.Equal("42", duckAbstract.ProtectedGetSetReferenceType); Assert.Equal("42", duckVirtual.ProtectedGetSetReferenceType); @@ -270,10 +270,10 @@ public void Properties(object obscureObject) Assert.Equal("60", duckAbstract.ProtectedGetSetReferenceType); Assert.Equal("60", duckVirtual.ProtectedGetSetReferenceType); - duckInterface.ProtectedGetSetReferenceType = "42"; - - // * - + duckInterface.ProtectedGetSetReferenceType = "42"; + + // * + Assert.Equal("43", duckInterface.PrivateGetSetReferenceType); Assert.Equal("43", duckAbstract.PrivateGetSetReferenceType); Assert.Equal("43", duckVirtual.PrivateGetSetReferenceType); @@ -358,28 +358,28 @@ public void UnionTest(object obscureObject) duckInterface.PublicGetSetReferenceType = "42"; Assert.Equal("42", duckInterface.PublicGetSetReferenceType); - duckInterface.PublicGetSetReferenceType = "40"; - - // * - + duckInterface.PublicGetSetReferenceType = "40"; + + // * + Assert.Equal("41", duckInterface.InternalGetSetReferenceType); duckInterface.InternalGetSetReferenceType = "42"; Assert.Equal("42", duckInterface.InternalGetSetReferenceType); - duckInterface.InternalGetSetReferenceType = "41"; - - // * - + duckInterface.InternalGetSetReferenceType = "41"; + + // * + Assert.Equal("42", duckInterface.ProtectedGetSetReferenceType); duckInterface.ProtectedGetSetReferenceType = "45"; Assert.Equal("45", duckInterface.ProtectedGetSetReferenceType); - duckInterface.ProtectedGetSetReferenceType = "42"; - - // * - + duckInterface.ProtectedGetSetReferenceType = "42"; + + // * + Assert.Equal("43", duckInterface.PrivateGetSetReferenceType); duckInterface.PrivateGetSetReferenceType = "42"; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/DummyFieldStruct.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/DummyFieldStruct.cs index 7976c089d..49b37e966 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/DummyFieldStruct.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/DummyFieldStruct.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.TypeChaining.ProxiesDefinitions -{ +{ #pragma warning disable 649 - + [DuckCopy] public struct DummyFieldStruct { diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IDummyFieldObject.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IDummyFieldObject.cs index 0999037eb..27b5a0ded 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IDummyFieldObject.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IDummyFieldObject.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.TypeChaining.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureDuckType.cs index 723a83272..fbf536e0e 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.TypeChaining.ProxiesDefinitions { public interface IObscureDuckType @@ -18,40 +18,40 @@ public interface IObscureDuckType IDummyFieldObject ProtectedStaticGetSelfType { get; } - IDummyFieldObject PrivateStaticGetSelfType { get; } - - // * - + IDummyFieldObject PrivateStaticGetSelfType { get; } + + // * + IDummyFieldObject PublicStaticGetSetSelfType { get; set; } IDummyFieldObject InternalStaticGetSetSelfType { get; set; } IDummyFieldObject ProtectedStaticGetSetSelfType { get; set; } - IDummyFieldObject PrivateStaticGetSetSelfType { get; set; } - - // * - + IDummyFieldObject PrivateStaticGetSetSelfType { get; set; } + + // * + IDummyFieldObject PublicGetSelfType { get; } IDummyFieldObject InternalGetSelfType { get; } IDummyFieldObject ProtectedGetSelfType { get; } - IDummyFieldObject PrivateGetSelfType { get; } - - // * - + IDummyFieldObject PrivateGetSelfType { get; } + + // * + IDummyFieldObject PublicGetSetSelfType { get; set; } IDummyFieldObject InternalGetSetSelfType { get; set; } IDummyFieldObject ProtectedGetSetSelfType { get; set; } - IDummyFieldObject PrivateGetSetSelfType { get; set; } - - // * - + IDummyFieldObject PrivateGetSetSelfType { get; set; } + + // * + IDummyFieldObject PrivateDummyGetSetSelfType { get; set; } } } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureErrorDuckType.cs index f91a347ec..d8ad94791 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.TypeChaining.ProxiesDefinitions { public interface IObscureErrorDuckType diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureStaticErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureStaticErrorDuckType.cs index c1b09487a..a9278b83d 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureStaticErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/IObscureStaticErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.TypeChaining.ProxiesDefinitions { public interface IObscureStaticErrorDuckType diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ITypesTuple.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ITypesTuple.cs index 9d9770e36..eaafbf869 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ITypesTuple.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ITypesTuple.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System; using Elastic.Apm.Profiler.Managed.DuckTyping; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs index 61ddc1683..f4fd562dc 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.TypeChaining.ProxiesDefinitions { public abstract class ObscureDuckTypeAbstractClass @@ -18,30 +18,30 @@ public abstract class ObscureDuckTypeAbstractClass public abstract IDummyFieldObject ProtectedStaticGetSelfType { get; } - public abstract IDummyFieldObject PrivateStaticGetSelfType { get; } - - // * - + public abstract IDummyFieldObject PrivateStaticGetSelfType { get; } + + // * + public abstract IDummyFieldObject PublicStaticGetSetSelfType { get; set; } public abstract IDummyFieldObject InternalStaticGetSetSelfType { get; set; } public abstract IDummyFieldObject ProtectedStaticGetSetSelfType { get; set; } - public abstract IDummyFieldObject PrivateStaticGetSetSelfType { get; set; } - - // * - + public abstract IDummyFieldObject PrivateStaticGetSetSelfType { get; set; } + + // * + public abstract IDummyFieldObject PublicGetSelfType { get; } public abstract IDummyFieldObject InternalGetSelfType { get; } public abstract IDummyFieldObject ProtectedGetSelfType { get; } - public abstract IDummyFieldObject PrivateGetSelfType { get; } - - // * - + public abstract IDummyFieldObject PrivateGetSelfType { get; } + + // * + public abstract IDummyFieldObject PublicGetSetSelfType { get; set; } public abstract IDummyFieldObject InternalGetSetSelfType { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeStruct.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeStruct.cs index 9fc16f27c..5559e48f3 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeStruct.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeStruct.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.TypeChaining.ProxiesDefinitions -{ +{ #pragma warning disable 649 - + [DuckCopy] public struct ObscureDuckTypeStruct { diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs index 0f3f79b0b..6eb33b35b 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.TypeChaining.ProxiesDefinitions { public class ObscureDuckTypeVirtualClass @@ -18,30 +18,30 @@ public class ObscureDuckTypeVirtualClass public virtual IDummyFieldObject ProtectedStaticGetSelfType { get; } - public virtual IDummyFieldObject PrivateStaticGetSelfType { get; } - - // * - + public virtual IDummyFieldObject PrivateStaticGetSelfType { get; } + + // * + public virtual IDummyFieldObject PublicStaticGetSetSelfType { get; set; } public virtual IDummyFieldObject InternalStaticGetSetSelfType { get; set; } public virtual IDummyFieldObject ProtectedStaticGetSetSelfType { get; set; } - public virtual IDummyFieldObject PrivateStaticGetSetSelfType { get; set; } - - // * - + public virtual IDummyFieldObject PrivateStaticGetSetSelfType { get; set; } + + // * + public virtual IDummyFieldObject PublicGetSelfType { get; } public virtual IDummyFieldObject InternalGetSelfType { get; } public virtual IDummyFieldObject ProtectedGetSelfType { get; } - public virtual IDummyFieldObject PrivateGetSelfType { get; } - - // * - + public virtual IDummyFieldObject PrivateGetSelfType { get; } + + // * + public virtual IDummyFieldObject PublicGetSetSelfType { get; set; } public virtual IDummyFieldObject InternalGetSetSelfType { get; set; } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/TypeChainingPropertyTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/TypeChainingPropertyTests.cs index 31689af4d..a81b3209f 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/TypeChainingPropertyTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/TypeChaining/TypeChainingPropertyTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Collections.Generic; using Elastic.Apm.Profiler.Managed.DuckTyping; using Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.TypeChaining.ProxiesDefinitions; @@ -46,40 +46,40 @@ public void StaticGetOnlyProperties(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * - + var duckVirtual = obscureObject.DuckCast(); + + // * + Assert.Equal(42, duckInterface.PublicStaticGetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.PublicStaticGetSelfType.MagicNumber); Assert.Equal(42, duckVirtual.PublicStaticGetSelfType.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.PublicStaticGetSelfType).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.PublicStaticGetSelfType).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.PublicStaticGetSelfType).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.PublicStaticGetSelfType).Instance); + + // * + Assert.Equal(42, duckInterface.InternalStaticGetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.InternalStaticGetSelfType.MagicNumber); Assert.Equal(42, duckVirtual.InternalStaticGetSelfType.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.InternalStaticGetSelfType).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.InternalStaticGetSelfType).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.InternalStaticGetSelfType).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.InternalStaticGetSelfType).Instance); + + // * + Assert.Equal(42, duckInterface.ProtectedStaticGetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.ProtectedStaticGetSelfType.MagicNumber); Assert.Equal(42, duckVirtual.ProtectedStaticGetSelfType.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.ProtectedStaticGetSelfType).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.ProtectedStaticGetSelfType).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.ProtectedStaticGetSelfType).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.ProtectedStaticGetSelfType).Instance); + + // * + Assert.Equal(42, duckInterface.PrivateStaticGetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.PrivateStaticGetSelfType.MagicNumber); Assert.Equal(42, duckVirtual.PrivateStaticGetSelfType.MagicNumber); @@ -97,17 +97,17 @@ public void StaticProperties(object obscureObject) var duckAbstract = obscureObject.DuckCast(); var duckVirtual = obscureObject.DuckCast(); - IDummyFieldObject newDummy = null; - - // * + IDummyFieldObject newDummy = null; + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 42 }).DuckCast(); duckInterface.PublicStaticGetSetSelfType = newDummy; Assert.Equal(42, duckInterface.PublicStaticGetSetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.PublicStaticGetSetSelfType.MagicNumber); - Assert.Equal(42, duckVirtual.PublicStaticGetSetSelfType.MagicNumber); - - // * + Assert.Equal(42, duckVirtual.PublicStaticGetSetSelfType.MagicNumber); + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 52 }).DuckCast(); duckInterface.InternalStaticGetSetSelfType = newDummy; @@ -116,9 +116,9 @@ public void StaticProperties(object obscureObject) Assert.Equal(52, duckVirtual.InternalStaticGetSetSelfType.MagicNumber); newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 42 }).DuckCast(); - duckInterface.InternalStaticGetSetSelfType = newDummy; - - // * + duckInterface.InternalStaticGetSetSelfType = newDummy; + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 62 }).DuckCast(); duckAbstract.ProtectedStaticGetSetSelfType = newDummy; @@ -127,9 +127,9 @@ public void StaticProperties(object obscureObject) Assert.Equal(62, duckVirtual.ProtectedStaticGetSetSelfType.MagicNumber); newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 42 }).DuckCast(); - duckAbstract.ProtectedStaticGetSetSelfType = newDummy; - - // * + duckAbstract.ProtectedStaticGetSetSelfType = newDummy; + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 72 }).DuckCast(); duckAbstract.PrivateStaticGetSetSelfType = newDummy; @@ -147,40 +147,40 @@ public void GetOnlyProperties(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * - + var duckVirtual = obscureObject.DuckCast(); + + // * + Assert.Equal(42, duckInterface.PublicGetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.PublicGetSelfType.MagicNumber); Assert.Equal(42, duckVirtual.PublicGetSelfType.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.PublicGetSelfType).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.PublicGetSelfType).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.PublicGetSelfType).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.PublicGetSelfType).Instance); + + // * + Assert.Equal(42, duckInterface.InternalGetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.InternalGetSelfType.MagicNumber); Assert.Equal(42, duckVirtual.InternalGetSelfType.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.InternalGetSelfType).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.InternalGetSelfType).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.InternalGetSelfType).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.InternalGetSelfType).Instance); + + // * + Assert.Equal(42, duckInterface.ProtectedGetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.ProtectedGetSelfType.MagicNumber); Assert.Equal(42, duckVirtual.ProtectedGetSelfType.MagicNumber); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckInterface.ProtectedGetSelfType).Instance); Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckAbstract.ProtectedGetSelfType).Instance); - Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.ProtectedGetSelfType).Instance); - - // * - + Assert.Equal(ObscureObject.DummyFieldObject.Default, ((IDuckType)duckVirtual.ProtectedGetSelfType).Instance); + + // * + Assert.Equal(42, duckInterface.PrivateGetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.PrivateGetSelfType.MagicNumber); Assert.Equal(42, duckVirtual.PrivateGetSelfType.MagicNumber); @@ -198,17 +198,17 @@ public void Properties(object obscureObject) var duckAbstract = obscureObject.DuckCast(); var duckVirtual = obscureObject.DuckCast(); - IDummyFieldObject newDummy = null; - - // * + IDummyFieldObject newDummy = null; + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 42 }).DuckCast(); duckInterface.PublicGetSetSelfType = newDummy; Assert.Equal(42, duckInterface.PublicGetSetSelfType.MagicNumber); Assert.Equal(42, duckAbstract.PublicGetSetSelfType.MagicNumber); - Assert.Equal(42, duckVirtual.PublicGetSetSelfType.MagicNumber); - - // * + Assert.Equal(42, duckVirtual.PublicGetSetSelfType.MagicNumber); + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 52 }).DuckCast(); duckInterface.InternalGetSetSelfType = newDummy; @@ -217,9 +217,9 @@ public void Properties(object obscureObject) Assert.Equal(52, duckVirtual.InternalGetSetSelfType.MagicNumber); newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 42 }).DuckCast(); - duckInterface.InternalGetSetSelfType = newDummy; - - // * + duckInterface.InternalGetSetSelfType = newDummy; + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 62 }).DuckCast(); duckInterface.ProtectedGetSetSelfType = newDummy; @@ -228,9 +228,9 @@ public void Properties(object obscureObject) Assert.Equal(62, duckVirtual.ProtectedGetSetSelfType.MagicNumber); newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 42 }).DuckCast(); - duckInterface.ProtectedGetSetSelfType = newDummy; - - // * + duckInterface.ProtectedGetSetSelfType = newDummy; + + // * newDummy = (new ObscureObject.DummyFieldObject { MagicNumber = 72 }).DuckCast(); duckInterface.PrivateGetSetSelfType = newDummy; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureDuckType.cs index ddb7757e1..4a0c867ff 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Threading.Tasks; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ValueType.ProxiesDefinitions @@ -20,54 +20,54 @@ public interface IObscureDuckType int ProtectedStaticGetValueType { get; } - int PrivateStaticGetValueType { get; } - - // * - + int PrivateStaticGetValueType { get; } + + // * + int PublicStaticGetSetValueType { get; set; } int InternalStaticGetSetValueType { get; set; } int ProtectedStaticGetSetValueType { get; set; } - int PrivateStaticGetSetValueType { get; set; } - - // * - + int PrivateStaticGetSetValueType { get; set; } + + // * + int PublicGetValueType { get; } int InternalGetValueType { get; } int ProtectedGetValueType { get; } - int PrivateGetValueType { get; } - - // * - + int PrivateGetValueType { get; } + + // * + int PublicGetSetValueType { get; set; } int InternalGetSetValueType { get; set; } int ProtectedGetSetValueType { get; set; } - int PrivateGetSetValueType { get; set; } - - // * - + int PrivateGetSetValueType { get; set; } + + // * + int? PublicStaticNullableInt { get; set; } int? PrivateStaticNullableInt { get; set; } int? PublicNullableInt { get; set; } - int? PrivateNullableInt { get; set; } - - // * - - TaskStatus Status { get; set; } - - // * - + int? PrivateNullableInt { get; set; } + + // * + + TaskStatus Status { get; set; } + + // * + int this[int index] { get; set; } } } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureErrorDuckType.cs index 97c0b6cc4..41d2d6cc7 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ValueType.ProxiesDefinitions { public interface IObscureErrorDuckType diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureStaticErrorDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureStaticErrorDuckType.cs index 09851edf7..dea66ca4a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureStaticErrorDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IObscureStaticErrorDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ValueType.ProxiesDefinitions { public interface IObscureStaticErrorDuckType diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IStructDuckType.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IStructDuckType.cs index ec3480b74..fac6fc186 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IStructDuckType.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/IStructDuckType.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ValueType.ProxiesDefinitions diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs index 5691a79f1..b2fb4abb2 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeAbstractClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Threading.Tasks; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ValueType.ProxiesDefinitions @@ -20,54 +20,54 @@ public abstract class ObscureDuckTypeAbstractClass public abstract int ProtectedStaticGetValueType { get; } - public abstract int PrivateStaticGetValueType { get; } - - // * - + public abstract int PrivateStaticGetValueType { get; } + + // * + public abstract int PublicStaticGetSetValueType { get; set; } public abstract int InternalStaticGetSetValueType { get; set; } public abstract int ProtectedStaticGetSetValueType { get; set; } - public abstract int PrivateStaticGetSetValueType { get; set; } - - // * - + public abstract int PrivateStaticGetSetValueType { get; set; } + + // * + public abstract int PublicGetValueType { get; } public abstract int InternalGetValueType { get; } public abstract int ProtectedGetValueType { get; } - public abstract int PrivateGetValueType { get; } - - // * - + public abstract int PrivateGetValueType { get; } + + // * + public abstract int PublicGetSetValueType { get; set; } public abstract int InternalGetSetValueType { get; set; } public abstract int ProtectedGetSetValueType { get; set; } - public abstract int PrivateGetSetValueType { get; set; } - - // * - + public abstract int PrivateGetSetValueType { get; set; } + + // * + public abstract int? PublicStaticNullableInt { get; set; } public abstract int? PrivateStaticNullableInt { get; set; } public abstract int? PublicNullableInt { get; set; } - public abstract int? PrivateNullableInt { get; set; } - - // * - - public abstract TaskStatus Status { get; set; } - - // * - + public abstract int? PrivateNullableInt { get; set; } + + // * + + public abstract TaskStatus Status { get; set; } + + // * + public abstract int this[int index] { get; set; } } } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeStruct.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeStruct.cs index bcdf5499b..30b1a0f5d 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeStruct.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeStruct.cs @@ -1,19 +1,19 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ValueType.ProxiesDefinitions -{ +{ #pragma warning disable 649 - + [DuckCopy] internal struct ObscureDuckTypeStruct { diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs index 9539de7ee..610649e24 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ProxiesDefinitions/ObscureDuckTypeVirtualClass.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Threading.Tasks; namespace Elastic.Apm.Profiler.Managed.Tests.DuckTyping.Properties.ValueType.ProxiesDefinitions @@ -20,58 +20,58 @@ public class ObscureDuckTypeVirtualClass public virtual int ProtectedStaticGetValueType { get; } - public virtual int PrivateStaticGetValueType { get; } - - // * - + public virtual int PrivateStaticGetValueType { get; } + + // * + public virtual int PublicStaticGetSetValueType { get; set; } public virtual int InternalStaticGetSetValueType { get; set; } public virtual int ProtectedStaticGetSetValueType { get; set; } - public virtual int PrivateStaticGetSetValueType { get; set; } - - // * - + public virtual int PrivateStaticGetSetValueType { get; set; } + + // * + public virtual int PublicGetValueType { get; } public virtual int InternalGetValueType { get; } public virtual int ProtectedGetValueType { get; } - public virtual int PrivateGetValueType { get; } - - // * - + public virtual int PrivateGetValueType { get; } + + // * + public virtual int PublicGetSetValueType { get; set; } public virtual int InternalGetSetValueType { get; set; } public virtual int ProtectedGetSetValueType { get; set; } - public virtual int PrivateGetSetValueType { get; set; } - - // * - + public virtual int PrivateGetSetValueType { get; set; } + + // * + public virtual int? PublicStaticNullableInt { get; set; } public virtual int? PrivateStaticNullableInt { get; set; } public virtual int? PublicNullableInt { get; set; } - public virtual int? PrivateNullableInt { get; set; } - - // * - + public virtual int? PrivateNullableInt { get; set; } + + // * + public virtual TaskStatus Status { get => default; set { } - } - - // * - + } + + // * + public virtual int this[int index] { get => default; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ValueTypePropertyTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ValueTypePropertyTests.cs index 751711651..f11f57d44 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ValueTypePropertyTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/Properties/ValueType/ValueTypePropertyTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using System.Collections.Generic; using System.Threading.Tasks; using Elastic.Apm.Profiler.Managed.DuckTyping; @@ -47,24 +47,24 @@ public void StaticGetOnlyProperties(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * + var duckVirtual = obscureObject.DuckCast(); + + // * Assert.Equal(10, duckInterface.PublicStaticGetValueType); Assert.Equal(10, duckAbstract.PublicStaticGetValueType); - Assert.Equal(10, duckVirtual.PublicStaticGetValueType); - - // * + Assert.Equal(10, duckVirtual.PublicStaticGetValueType); + + // * Assert.Equal(11, duckInterface.InternalStaticGetValueType); Assert.Equal(11, duckAbstract.InternalStaticGetValueType); - Assert.Equal(11, duckVirtual.InternalStaticGetValueType); - - // * + Assert.Equal(11, duckVirtual.InternalStaticGetValueType); + + // * Assert.Equal(12, duckInterface.ProtectedStaticGetValueType); Assert.Equal(12, duckAbstract.ProtectedStaticGetValueType); - Assert.Equal(12, duckVirtual.ProtectedStaticGetValueType); - - // * + Assert.Equal(12, duckVirtual.ProtectedStaticGetValueType); + + // * Assert.Equal(13, duckInterface.PrivateStaticGetValueType); Assert.Equal(13, duckAbstract.PrivateStaticGetValueType); Assert.Equal(13, duckVirtual.PrivateStaticGetValueType); @@ -97,10 +97,10 @@ public void StaticProperties(object obscureObject) Assert.Equal(60, duckAbstract.PublicStaticGetSetValueType); Assert.Equal(60, duckVirtual.PublicStaticGetSetValueType); - duckInterface.PublicStaticGetSetValueType = 20; - - // * - + duckInterface.PublicStaticGetSetValueType = 20; + + // * + Assert.Equal(21, duckInterface.InternalStaticGetSetValueType); Assert.Equal(21, duckAbstract.InternalStaticGetSetValueType); Assert.Equal(21, duckVirtual.InternalStaticGetSetValueType); @@ -120,10 +120,10 @@ public void StaticProperties(object obscureObject) Assert.Equal(60, duckAbstract.InternalStaticGetSetValueType); Assert.Equal(60, duckVirtual.InternalStaticGetSetValueType); - duckInterface.InternalStaticGetSetValueType = 21; - - // * - + duckInterface.InternalStaticGetSetValueType = 21; + + // * + Assert.Equal(22, duckInterface.ProtectedStaticGetSetValueType); Assert.Equal(22, duckAbstract.ProtectedStaticGetSetValueType); Assert.Equal(22, duckVirtual.ProtectedStaticGetSetValueType); @@ -143,10 +143,10 @@ public void StaticProperties(object obscureObject) Assert.Equal(60, duckAbstract.ProtectedStaticGetSetValueType); Assert.Equal(60, duckVirtual.ProtectedStaticGetSetValueType); - duckInterface.ProtectedStaticGetSetValueType = 22; - - // * - + duckInterface.ProtectedStaticGetSetValueType = 22; + + // * + Assert.Equal(23, duckInterface.PrivateStaticGetSetValueType); Assert.Equal(23, duckAbstract.PrivateStaticGetSetValueType); Assert.Equal(23, duckVirtual.PrivateStaticGetSetValueType); @@ -175,24 +175,24 @@ public void GetOnlyProperties(object obscureObject) { var duckInterface = obscureObject.DuckCast(); var duckAbstract = obscureObject.DuckCast(); - var duckVirtual = obscureObject.DuckCast(); - - // * + var duckVirtual = obscureObject.DuckCast(); + + // * Assert.Equal(30, duckInterface.PublicGetValueType); Assert.Equal(30, duckAbstract.PublicGetValueType); - Assert.Equal(30, duckVirtual.PublicGetValueType); - - // * + Assert.Equal(30, duckVirtual.PublicGetValueType); + + // * Assert.Equal(31, duckInterface.InternalGetValueType); Assert.Equal(31, duckAbstract.InternalGetValueType); - Assert.Equal(31, duckVirtual.InternalGetValueType); - - // * + Assert.Equal(31, duckVirtual.InternalGetValueType); + + // * Assert.Equal(32, duckInterface.ProtectedGetValueType); Assert.Equal(32, duckAbstract.ProtectedGetValueType); - Assert.Equal(32, duckVirtual.ProtectedGetValueType); - - // * + Assert.Equal(32, duckVirtual.ProtectedGetValueType); + + // * Assert.Equal(33, duckInterface.PrivateGetValueType); Assert.Equal(33, duckAbstract.PrivateGetValueType); Assert.Equal(33, duckVirtual.PrivateGetValueType); @@ -225,10 +225,10 @@ public void Properties(object obscureObject) Assert.Equal(60, duckAbstract.PublicGetSetValueType); Assert.Equal(60, duckVirtual.PublicGetSetValueType); - duckInterface.PublicGetSetValueType = 40; - - // * - + duckInterface.PublicGetSetValueType = 40; + + // * + Assert.Equal(41, duckInterface.InternalGetSetValueType); Assert.Equal(41, duckAbstract.InternalGetSetValueType); Assert.Equal(41, duckVirtual.InternalGetSetValueType); @@ -248,10 +248,10 @@ public void Properties(object obscureObject) Assert.Equal(60, duckAbstract.InternalGetSetValueType); Assert.Equal(60, duckVirtual.InternalGetSetValueType); - duckInterface.InternalGetSetValueType = 41; - - // * - + duckInterface.InternalGetSetValueType = 41; + + // * + Assert.Equal(42, duckInterface.ProtectedGetSetValueType); Assert.Equal(42, duckAbstract.ProtectedGetSetValueType); Assert.Equal(42, duckVirtual.ProtectedGetSetValueType); @@ -271,10 +271,10 @@ public void Properties(object obscureObject) Assert.Equal(60, duckAbstract.ProtectedGetSetValueType); Assert.Equal(60, duckVirtual.ProtectedGetSetValueType); - duckInterface.ProtectedGetSetValueType = 42; - - // * - + duckInterface.ProtectedGetSetValueType = 42; + + // * + Assert.Equal(43, duckInterface.PrivateGetSetValueType); Assert.Equal(43, duckAbstract.PrivateGetSetValueType); Assert.Equal(43, duckVirtual.PrivateGetSetValueType); @@ -346,10 +346,10 @@ public void NullableOfKnown(object obscureObject) duckVirtual.PublicStaticNullableInt = null; Assert.Null(duckInterface.PublicStaticNullableInt); Assert.Null(duckAbstract.PublicStaticNullableInt); - Assert.Null(duckVirtual.PublicStaticNullableInt); - - // * - + Assert.Null(duckVirtual.PublicStaticNullableInt); + + // * + Assert.Null(duckInterface.PrivateStaticNullableInt); Assert.Null(duckAbstract.PrivateStaticNullableInt); Assert.Null(duckVirtual.PrivateStaticNullableInt); @@ -367,10 +367,10 @@ public void NullableOfKnown(object obscureObject) duckVirtual.PrivateStaticNullableInt = null; Assert.Null(duckInterface.PrivateStaticNullableInt); Assert.Null(duckAbstract.PrivateStaticNullableInt); - Assert.Null(duckVirtual.PrivateStaticNullableInt); - - // * - + Assert.Null(duckVirtual.PrivateStaticNullableInt); + + // * + Assert.Null(duckInterface.PublicNullableInt); Assert.Null(duckAbstract.PublicNullableInt); Assert.Null(duckVirtual.PublicNullableInt); @@ -388,10 +388,10 @@ public void NullableOfKnown(object obscureObject) duckVirtual.PublicNullableInt = null; Assert.Null(duckInterface.PublicNullableInt); Assert.Null(duckAbstract.PublicNullableInt); - Assert.Null(duckVirtual.PublicNullableInt); - - // * - + Assert.Null(duckVirtual.PublicNullableInt); + + // * + Assert.Null(duckInterface.PrivateNullableInt); Assert.Null(duckAbstract.PrivateNullableInt); Assert.Null(duckVirtual.PrivateNullableInt); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/StructTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/StructTests.cs index 15fe40939..780e9ad5f 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/StructTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/StructTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; using Xunit; @@ -106,11 +106,11 @@ public interface IPrivateTarget } private class PrivateDuckChainingTarget - { + { #pragma warning disable SA1401 // Fields must be private - public PrivateTarget ChainingTestField = new PrivateTarget { Name = "Hello World 1" }; + public PrivateTarget ChainingTestField = new PrivateTarget { Name = "Hello World 1" }; #pragma warning restore SA1401 // Fields must be private - + public PrivateTarget ChainingTest => new PrivateTarget { Name = "Hello World 2" }; public PrivateTarget ChainingTestMethod() => new PrivateTarget { Name = "Hello World 3" }; @@ -122,11 +122,11 @@ private struct PrivateTarget } public class PublicDuckChainingTarget - { + { #pragma warning disable SA1401 // Fields must be private - public PublicTarget ChainingTestField = new PublicTarget { Name = "Hello World 1" }; + public PublicTarget ChainingTestField = new PublicTarget { Name = "Hello World 1" }; #pragma warning restore SA1401 // Fields must be private - + public PublicTarget ChainingTest => new PublicTarget { Name = "Hello World 2" }; public PublicTarget ChainingTestMethod() => new PublicTarget { Name = "Hello World 3" }; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/TypesTupleTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/TypesTupleTests.cs index 74b9e9edd..1538b7994 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/TypesTupleTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/DuckTyping/TypesTupleTests.cs @@ -1,13 +1,13 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// -// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. -// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. -// - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + using Elastic.Apm.Profiler.Managed.DuckTyping; using Xunit; @@ -22,8 +22,8 @@ public void EqualsTupleTest() var tuple2 = new TypesTuple(typeof(string), typeof(int)); Assert.True(tuple1.Equals(tuple2)); - Assert.True(tuple1.Equals((object)tuple2)); - // ReSharper disable once SuspiciousTypeConversion.Global + Assert.True(tuple1.Equals((object)tuple2)); + // ReSharper disable once SuspiciousTypeConversion.Global Assert.False(tuple1.Equals("Hello World")); } } diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/ExcludeTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/ExcludeTests.cs index c655b58c0..70c9cb6e8 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/ExcludeTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/ExcludeTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -58,9 +58,9 @@ public async Task ShouldNotInstrumentExcludedIntegrations() } logs.Should().Contain(line => line.Contains("exclude integrations that match SqliteCommand")); - logs.Should().Contain(line => line.Contains("exclude integrations that match AdoNet")); - - // count of manual spans without any auto instrumented spans + logs.Should().Contain(line => line.Contains("exclude integrations that match AdoNet")); + + // count of manual spans without any auto instrumented spans apmServer.ReceivedData.Spans.Should().HaveCount(32); await apmServer.StopAsync(); @@ -116,9 +116,9 @@ public async Task ShouldNotInstrumentExcludedProcess(string targetFramework, str logs.Should() .Contain(line => - line.Contains($"process name {excludeProcess} matches excluded name {excludeProcess}. Profiler disabled")); - - // count of manual spans without any auto instrumented spans + line.Contains($"process name {excludeProcess} matches excluded name {excludeProcess}. Profiler disabled")); + + // count of manual spans without any auto instrumented spans apmServer.ReceivedData.Spans.Should().HaveCount(32); await apmServer.StopAsync(); @@ -164,9 +164,9 @@ public async Task ShouldNotInstrumentExcludedServiceName() logs.Should() .Contain(line => - line.Contains($"service name {serviceName} matches excluded name {serviceName}. Profiler disabled")); - - // count of manual spans without any auto instrumented spans + line.Contains($"service name {serviceName} matches excluded name {serviceName}. Profiler disabled")); + + // count of manual spans without any auto instrumented spans apmServer.ReceivedData.Spans.Should().HaveCount(32); await apmServer.StopAsync(); @@ -190,15 +190,15 @@ public async Task ShouldNotInstrumentAzureAppServiceInfrastructureOrReservedProc { ["ELASTIC_APM_SERVER_URL"] = $"http://localhost:{port}", ["ELASTIC_APM_DISABLE_METRICS"] = "*", - ["ELASTIC_APM_PROFILER_LOG_TARGETS"] = "file;stdout", - - // Azure App Service environment variables + ["ELASTIC_APM_PROFILER_LOG_TARGETS"] = "file;stdout", + + // Azure App Service environment variables [AzureEnvironmentVariables.WebsiteOwnerName] = AzureEnvironmentVariables.WebsiteOwnerName, [AzureEnvironmentVariables.WebsiteInstanceId] = AzureEnvironmentVariables.WebsiteInstanceId, [AzureEnvironmentVariables.WebsiteResourceGroup] = AzureEnvironmentVariables.WebsiteResourceGroup, - [AzureEnvironmentVariables.WebsiteSiteName] = AzureEnvironmentVariables.WebsiteSiteName, - - // Azure App Service infra/reserved process environment variable + [AzureEnvironmentVariables.WebsiteSiteName] = AzureEnvironmentVariables.WebsiteSiteName, + + // Azure App Service infra/reserved process environment variable [key] = value }; @@ -217,9 +217,9 @@ public async Task ShouldNotInstrumentAzureAppServiceInfrastructureOrReservedProc exception => _output.WriteLine($"{exception}")); } - logs.Should().Contain(line => line.Contains("Profiler disabled")); - - // count of manual spans without any auto instrumented spans + logs.Should().Contain(line => line.Contains("Profiler disabled")); + + // count of manual spans without any auto instrumented spans apmServer.ReceivedData.Spans.Should().HaveCount(32); await apmServer.StopAsync(); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Kafka/KafkaFixture.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Kafka/KafkaFixture.cs index 26fef03ca..80a3bfa4a 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Kafka/KafkaFixture.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Kafka/KafkaFixture.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Kafka/KafkaTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Kafka/KafkaTests.cs index 319a5ac16..cec251f4f 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Kafka/KafkaTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/Kafka/KafkaTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; @@ -55,9 +55,9 @@ public async Task CaptureAutoInstrumentedSpans(string targetFramework) null, line => _output.WriteLine(line.Line), exception => _output.WriteLine($"{exception}")); - } - - // 6 * 10 consume transactions, 14 produce transactions + } + + // 6 * 10 consume transactions, 14 produce transactions var transactions = apmServer.ReceivedData.Transactions; transactions.Should().HaveCount(74); @@ -81,8 +81,8 @@ public async Task CaptureAutoInstrumentedSpans(string targetFramework) var spans = apmServer.ReceivedData.Spans.Where(s => s.TransactionId == produceTransaction.Id).ToList(); if (produceTransaction.Name.Contains("INVALID-TOPIC")) - spans.Should().HaveCount(1); - // the produce transaction shouldn't have an auto instrumented publish span as topic is ignored + spans.Should().HaveCount(1); + // the produce transaction shouldn't have an auto instrumented publish span as topic is ignored else if (produceTransaction.Name.Contains(ignoreTopic)) spans.Should().BeEmpty(); else diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/ProfiledApplication.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/ProfiledApplication.cs index 86d0e8735..03b08eb75 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/ProfiledApplication.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/ProfiledApplication.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Diagnostics; @@ -21,9 +21,9 @@ public class ProfiledIntegrationApplication : ProfiledApplication { public ProfiledIntegrationApplication(string projectName) : base(projectName, "test", "integrations", "applications") - {} - } - + { } + } + /// /// A sample application that can be instrumented with the (Core)CLR profiler /// @@ -35,14 +35,14 @@ public class ProfiledApplication : IDisposable private readonly string _projectName; private readonly string _publishDirectory; - public ProfiledApplication(string projectName) : this(projectName, null) {} + public ProfiledApplication(string projectName) : this(projectName, null) { } protected ProfiledApplication(string projectName, params string[] folders) { _projectName = projectName; var root = folders == null || folders.Length == 0 ? Path.Combine(SolutionPaths.Root, "test", "profiler", "applications") - : Path.Combine(new [] { SolutionPaths.Root }.Concat(folders).ToArray()); + : Path.Combine(new[] { SolutionPaths.Root }.Concat(folders).ToArray()); _projectDirectory = Path.Combine(root, projectName); if (!Directory.Exists(_projectDirectory)) @@ -71,9 +71,9 @@ protected ProfiledApplication(string projectName, params string[] folders) private ObservableProcess _process; private void Publish(string targetFramework, string outputDirectory, string msBuildProperties) - { - // if we're running on CI and the publish directory already exists for the - // target framework, skip publishing again. + { + // if we're running on CI and the publish directory already exists for the + // target framework, skip publishing again. if (TestEnvironment.IsCi && Directory.Exists(outputDirectory)) return; @@ -87,8 +87,8 @@ private void Publish(string targetFramework, string outputDirectory, string msBu using var process = new Process { StartInfo = processInfo }; process.Start(); process.WaitForExit(); - } - + } + /// /// Starts the sample application and returns the on which the application /// can be reached. @@ -133,9 +133,9 @@ private void Publish(string targetFramework, string outputDirectory, string msBu environmentVariables["COR_ENABLE_PROFILING"] = "1"; environmentVariables["COR_PROFILER"] = ProfilerClassId; - environmentVariables["COR_PROFILER_PATH"] = _profilerPath; - - //Temporarily disable since it does IO that fails on CI which is noisy + environmentVariables["COR_PROFILER_PATH"] = _profilerPath; + + //Temporarily disable since it does IO that fails on CI which is noisy environmentVariables["ELASTIC_APM_CENTRAL_CONFIG"] = "false"; environmentVariables["ELASTIC_APM_CLOUD_PROVIDER"] = "none"; @@ -144,14 +144,14 @@ private void Publish(string targetFramework, string outputDirectory, string msBu environmentVariables["ELASTIC_APM_PROFILER_INTEGRATIONS"] = Path.Combine(SolutionPaths.Root, "src", "profiler", "Elastic.Apm.Profiler.Managed", "integrations.yml"); - environmentVariables["ELASTIC_APM_PROFILER_LOG"] = "trace"; - // log to relative logs directory for managed loader + environmentVariables["ELASTIC_APM_PROFILER_LOG"] = "trace"; + // log to relative logs directory for managed loader environmentVariables["ELASTIC_APM_PROFILER_LOG_DIR"] = Path.Combine(SolutionPaths.Root, "logs"); - environmentVariables["ELASTIC_APM_PROFILER_LOG_TARGETS"] = "file;stdout"; - //environmentVariables["ELASTIC_APM_PROFILER_LOG_IL"] = "true"; - - // use the .exe for net462 + environmentVariables["ELASTIC_APM_PROFILER_LOG_TARGETS"] = "file;stdout"; + //environmentVariables["ELASTIC_APM_PROFILER_LOG_IL"] = "true"; + + // use the .exe for net462 var arguments = targetFramework == "net462" ? new StartArguments(Path.Combine(workingDirectory, $"{_projectName}.exe")) : useLocalhostHttp5000 diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/RabbitMq/RabbitMqFixture.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/RabbitMq/RabbitMqFixture.cs index f55ea40bc..42f0265cc 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/RabbitMq/RabbitMqFixture.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/RabbitMq/RabbitMqFixture.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Threading.Tasks; using Testcontainers.RabbitMq; using Xunit; diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/RabbitMq/RabbitMqTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/RabbitMq/RabbitMqTests.cs index 595902bc7..15b882cc9 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/RabbitMq/RabbitMqTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/RabbitMq/RabbitMqTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; @@ -61,8 +61,8 @@ public async Task CaptureAutoInstrumentedSpans(string targetFramework) transactions.Should().HaveCount(9); - var ignoreTransaction = transactions.Single(t => t.Name == "PublishAndGetIgnore"); - // don't capture any spans for ignored queues and messages + var ignoreTransaction = transactions.Single(t => t.Name == "PublishAndGetIgnore"); + // don't capture any spans for ignored queues and messages spans.Where(s => s.TransactionId == ignoreTransaction.Id).Should().BeEmpty(); var publishAndGetTransaction = transactions.Single(t => t.Name == "PublishAndGet"); diff --git a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/SatelliteAssemblyTests.cs b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/SatelliteAssemblyTests.cs index f32632c5f..82f0134e2 100644 --- a/test/profiler/Elastic.Apm.Profiler.Managed.Tests/SatelliteAssemblyTests.cs +++ b/test/profiler/Elastic.Apm.Profiler.Managed.Tests/SatelliteAssemblyTests.cs @@ -1,4 +1,4 @@ -// Licensed to Elasticsearch B.V under +// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information diff --git a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandExecutor.cs b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandExecutor.cs index 416e5eebc..bbdb53c1c 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandExecutor.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandExecutor.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; using System.Threading; using System.Threading.Tasks; diff --git a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardClassExecutor.cs b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardClassExecutor.cs index e78cdcca2..b2c468a6b 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardClassExecutor.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardClassExecutor.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; using System.Data.Common; using System.Threading; diff --git a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardInterfaceExecutor.cs b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardInterfaceExecutor.cs index 3d5278b68..06f51d579 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardInterfaceExecutor.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardInterfaceExecutor.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; using System.Threading; using System.Threading.Tasks; diff --git a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardInterfaceGenericExecutor.cs b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardInterfaceGenericExecutor.cs index 15eddcf01..ecfc2b35e 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardInterfaceGenericExecutor.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/DbCommandNetStandardInterfaceGenericExecutor.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; using System.Threading; using System.Threading.Tasks; diff --git a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/IDbCommandExecutor.cs b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/IDbCommandExecutor.cs index 4e7190405..72ac73daa 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/IDbCommandExecutor.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet.NetStandard/IDbCommandExecutor.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; using System.Threading; using System.Threading.Tasks; diff --git a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandClassExecutor.cs b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandClassExecutor.cs index 3bbdb08b1..093561d21 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandClassExecutor.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandClassExecutor.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; using System.Data.Common; using System.Threading; diff --git a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandExtensions.cs b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandExtensions.cs index f930b39ab..4c1d2c987 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandExtensions.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandExtensions.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; namespace Elastic.Apm.AdoNet diff --git a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandFactory.cs b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandFactory.cs index 1a4e3666a..0bedce2e4 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandFactory.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandFactory.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; namespace Elastic.Apm.AdoNet @@ -22,53 +22,53 @@ public DbCommandFactory(IDbConnection connection, string tableName) TableName = tableName; } - public virtual IDbCommand GetCreateTableCommand() - { - var command = Connection.CreateCommand(); - command.CommandText = $"DROP TABLE IF EXISTS {TableName}; CREATE TABLE {TableName} (Id int PRIMARY KEY, Name varchar(100));"; - return command; - } - - public virtual IDbCommand GetInsertRowCommand() - { - var command = Connection.CreateCommand(); - command.CommandText = $"INSERT INTO {TableName} (Id, Name) VALUES (@Id, @Name);"; - command.AddParameterWithValue("Id", 1); - command.AddParameterWithValue("Name", "Name1"); - return command; - } - - public virtual IDbCommand GetUpdateRowCommand() - { - var command = Connection.CreateCommand(); - command.CommandText = $"UPDATE {TableName} SET Name=@Name WHERE Id=@Id;"; - command.AddParameterWithValue("Name", "Name2"); - command.AddParameterWithValue("Id", 1); - return command; - } - - public virtual IDbCommand GetSelectScalarCommand() - { - var command = Connection.CreateCommand(); - command.CommandText = $"SELECT Name FROM {TableName} WHERE Id=@Id;"; - command.AddParameterWithValue("Id", 1); - return command; - } - - public virtual IDbCommand GetSelectRowCommand() - { - var command = Connection.CreateCommand(); - command.CommandText = $"SELECT * FROM {TableName} WHERE Id=@Id;"; - command.AddParameterWithValue("Id", 1); - return command; - } - - public virtual IDbCommand GetDeleteRowCommand() - { - var command = Connection.CreateCommand(); - command.CommandText = $"DELETE FROM {TableName} WHERE Id=@Id;"; - command.AddParameterWithValue("Id", 1); - return command; - } + public virtual IDbCommand GetCreateTableCommand() + { + var command = Connection.CreateCommand(); + command.CommandText = $"DROP TABLE IF EXISTS {TableName}; CREATE TABLE {TableName} (Id int PRIMARY KEY, Name varchar(100));"; + return command; + } + + public virtual IDbCommand GetInsertRowCommand() + { + var command = Connection.CreateCommand(); + command.CommandText = $"INSERT INTO {TableName} (Id, Name) VALUES (@Id, @Name);"; + command.AddParameterWithValue("Id", 1); + command.AddParameterWithValue("Name", "Name1"); + return command; + } + + public virtual IDbCommand GetUpdateRowCommand() + { + var command = Connection.CreateCommand(); + command.CommandText = $"UPDATE {TableName} SET Name=@Name WHERE Id=@Id;"; + command.AddParameterWithValue("Name", "Name2"); + command.AddParameterWithValue("Id", 1); + return command; + } + + public virtual IDbCommand GetSelectScalarCommand() + { + var command = Connection.CreateCommand(); + command.CommandText = $"SELECT Name FROM {TableName} WHERE Id=@Id;"; + command.AddParameterWithValue("Id", 1); + return command; + } + + public virtual IDbCommand GetSelectRowCommand() + { + var command = Connection.CreateCommand(); + command.CommandText = $"SELECT * FROM {TableName} WHERE Id=@Id;"; + command.AddParameterWithValue("Id", 1); + return command; + } + + public virtual IDbCommand GetDeleteRowCommand() + { + var command = Connection.CreateCommand(); + command.CommandText = $"DELETE FROM {TableName} WHERE Id=@Id;"; + command.AddParameterWithValue("Id", 1); + return command; + } } } diff --git a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandInterfaceExecutor.cs b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandInterfaceExecutor.cs index 5e263e38a..52a147ca4 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandInterfaceExecutor.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandInterfaceExecutor.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; using System.Threading; using System.Threading.Tasks; diff --git a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandInterfaceGenericExecutor.cs b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandInterfaceGenericExecutor.cs index eedeed83e..451142520 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandInterfaceGenericExecutor.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandInterfaceGenericExecutor.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; using System.Threading; using System.Threading.Tasks; diff --git a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandRunner.cs b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandRunner.cs index 053f7d49d..ddc106e3d 100644 --- a/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandRunner.cs +++ b/test/profiler/applications/Elastic.Apm.AdoNet/DbCommandRunner.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System; using System.Collections.Generic; using System.Data; @@ -17,7 +17,7 @@ namespace Elastic.Apm.AdoNet { public class DbCommandRunner - { + { /// /// Creates a RunAllAsync<TDbCommand> transaction with the following spans, /// when the profiler is attached: @@ -103,8 +103,8 @@ CancellationToken token foreach (var executor in executors) await RunAsync(transaction, commandFactory, executor, token); }); - } - + } + /// /// Creates a RunBaseTypesAsync transaction with the following spans, /// when the profiler is attached: diff --git a/test/profiler/applications/KafkaSample/Consumer.cs b/test/profiler/applications/KafkaSample/Consumer.cs index 8a940fb19..91b64f1bf 100644 --- a/test/profiler/applications/KafkaSample/Consumer.cs +++ b/test/profiler/applications/KafkaSample/Consumer.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on Producer type in https://github.com/DataDog/dd-trace-dotnet/blob/master/tracer/test/test-applications/integrations/Samples.Kafka/Consumer.cs -// Licensed under Apache 2.0 - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on Producer type in https://github.com/DataDog/dd-trace-dotnet/blob/master/tracer/test/test-applications/integrations/Samples.Kafka/Consumer.cs +// Licensed under Apache 2.0 + using System; using System.Text; using System.Threading; @@ -17,191 +17,191 @@ namespace KafkaSample { - internal class Consumer: IDisposable - { - private readonly string _consumerName; - private readonly IConsumer _consumer; - - public static int TotalAsyncMessages; - public static int TotalSyncMessages; - public static int TotalTombstones; - - private Consumer(ConsumerConfig config, string topic, string consumerName) - { - _consumerName = consumerName; - _consumer = new ConsumerBuilder(config).Build(); - _consumer.Subscribe(topic); - } - - public bool Consume(int retries, int timeoutMilliSeconds) - { - try - { - for (var i = 0; i < retries; i++) - { - try - { - // will block until a message is available - // on 1.5.3 this will throw if the topic doesn't exist - var consumeResult = _consumer.Consume(timeoutMilliSeconds); - if (consumeResult is null) - { - Console.WriteLine($"{_consumerName}: Null consume result"); - return true; - } - - if (consumeResult.IsPartitionEOF) - { - Console.WriteLine($"{_consumerName}: Reached EOF"); - return true; - } + internal class Consumer : IDisposable + { + private readonly string _consumerName; + private readonly IConsumer _consumer; + + public static int TotalAsyncMessages; + public static int TotalSyncMessages; + public static int TotalTombstones; + + private Consumer(ConsumerConfig config, string topic, string consumerName) + { + _consumerName = consumerName; + _consumer = new ConsumerBuilder(config).Build(); + _consumer.Subscribe(topic); + } + + public bool Consume(int retries, int timeoutMilliSeconds) + { + try + { + for (var i = 0; i < retries; i++) + { + try + { + // will block until a message is available + // on 1.5.3 this will throw if the topic doesn't exist + var consumeResult = _consumer.Consume(timeoutMilliSeconds); + if (consumeResult is null) + { + Console.WriteLine($"{_consumerName}: Null consume result"); + return true; + } + + if (consumeResult.IsPartitionEOF) + { + Console.WriteLine($"{_consumerName}: Reached EOF"); + return true; + } HandleMessage(consumeResult); return true; - } - catch (ConsumeException ex) - { - Console.WriteLine($"Consume Exception in manual consume: {ex}"); - } - - Task.Delay(500); - } - } - catch (TaskCanceledException) - { - Console.WriteLine($"{_consumerName}: Cancellation requested, exiting."); - } - - return false; - } - - public void Consume(CancellationToken cancellationToken = default) - { - try - { - while (!cancellationToken.IsCancellationRequested) - { - // will block until a message is available - var consumeResult = _consumer.Consume(cancellationToken); - - if (consumeResult.IsPartitionEOF) + } + catch (ConsumeException ex) + { + Console.WriteLine($"Consume Exception in manual consume: {ex}"); + } + + Task.Delay(500); + } + } + catch (TaskCanceledException) + { + Console.WriteLine($"{_consumerName}: Cancellation requested, exiting."); + } + + return false; + } + + public void Consume(CancellationToken cancellationToken = default) + { + try + { + while (!cancellationToken.IsCancellationRequested) + { + // will block until a message is available + var consumeResult = _consumer.Consume(cancellationToken); + + if (consumeResult.IsPartitionEOF) Console.WriteLine($"{_consumerName}: Reached EOF"); else HandleMessage(consumeResult); - } - } - catch (TaskCanceledException) - { - Console.WriteLine($"{_consumerName}: Cancellation requested, exiting."); - } - } - - public void ConsumeWithExplicitCommit(int commitEveryXMessages, CancellationToken cancellationToken = default) - { - ConsumeResult consumeResult = null; - try - { - while (!cancellationToken.IsCancellationRequested) - { - // will block until a message is available - consumeResult = _consumer.Consume(cancellationToken); - - if (consumeResult.IsPartitionEOF) + } + } + catch (TaskCanceledException) + { + Console.WriteLine($"{_consumerName}: Cancellation requested, exiting."); + } + } + + public void ConsumeWithExplicitCommit(int commitEveryXMessages, CancellationToken cancellationToken = default) + { + ConsumeResult consumeResult = null; + try + { + while (!cancellationToken.IsCancellationRequested) + { + // will block until a message is available + consumeResult = _consumer.Consume(cancellationToken); + + if (consumeResult.IsPartitionEOF) Console.WriteLine($"{_consumerName}: Reached EOF"); else HandleMessage(consumeResult); - if (consumeResult.Offset % commitEveryXMessages == 0) - { - try - { - Console.WriteLine($"{_consumerName}: committing..."); - _consumer.Commit(consumeResult); - } - catch (KafkaException e) - { - Console.WriteLine($"{_consumerName}: commit error: {e.Error.Reason}"); - } - } - } - } - catch (TaskCanceledException) - { - Console.WriteLine($"{_consumerName}: Cancellation requested, exiting."); - } - - // As we're doing manual commit, make sure we force a commit now - if (consumeResult is not null) - { - Console.WriteLine($"{_consumerName}: committing..."); - _consumer.Commit(consumeResult); - } - } - - private void HandleMessage(ConsumeResult consumeResult) + if (consumeResult.Offset % commitEveryXMessages == 0) + { + try + { + Console.WriteLine($"{_consumerName}: committing..."); + _consumer.Commit(consumeResult); + } + catch (KafkaException e) + { + Console.WriteLine($"{_consumerName}: commit error: {e.Error.Reason}"); + } + } + } + } + catch (TaskCanceledException) + { + Console.WriteLine($"{_consumerName}: Cancellation requested, exiting."); + } + + // As we're doing manual commit, make sure we force a commit now + if (consumeResult is not null) + { + Console.WriteLine($"{_consumerName}: committing..."); + _consumer.Commit(consumeResult); + } + } + + private void HandleMessage(ConsumeResult consumeResult) { var transaction = Agent.Tracer.CurrentTransaction; ISpan span = null; if (transaction != null) - span = transaction.StartSpan("Consume message", "kafka"); - - var kafkaMessage = consumeResult.Message; - Console.WriteLine($"{_consumerName}: Consuming {kafkaMessage.Key}, {consumeResult.TopicPartitionOffset}"); - - var headers = kafkaMessage.Headers; - var traceParent = headers.TryGetLastBytes("elasticapmtraceparent", out var traceParentHeader) + span = transaction.StartSpan("Consume message", "kafka"); + + var kafkaMessage = consumeResult.Message; + Console.WriteLine($"{_consumerName}: Consuming {kafkaMessage.Key}, {consumeResult.TopicPartitionOffset}"); + + var headers = kafkaMessage.Headers; + var traceParent = headers.TryGetLastBytes("elasticapmtraceparent", out var traceParentHeader) ? Encoding.UTF8.GetString(traceParentHeader) : null; var traceState = headers.TryGetLastBytes("tracestate", out var traceStateHeader) ? Encoding.UTF8.GetString(traceStateHeader) - : null; - - if (traceParent is null || traceState is null) - { - // For kafka brokers < 0.11.0, we can't inject custom headers, so context will not be propagated - Console.WriteLine($"Error extracting trace context for {kafkaMessage.Key}, {consumeResult.TopicPartitionOffset}"); - } - else + : null; + + if (traceParent is null || traceState is null) + { + // For kafka brokers < 0.11.0, we can't inject custom headers, so context will not be propagated + Console.WriteLine($"Error extracting trace context for {kafkaMessage.Key}, {consumeResult.TopicPartitionOffset}"); + } + else Console.WriteLine($"Successfully extracted trace context from message: {traceParent}, {traceState}"); - if (string.IsNullOrEmpty(kafkaMessage.Value)) - { - Console.WriteLine($"Received Tombstone for {kafkaMessage.Key}"); - Interlocked.Increment(ref TotalTombstones); - } - else - { - var sampleMessage = JsonConvert.DeserializeObject(kafkaMessage.Value); - Console.WriteLine($"Received {(sampleMessage.IsProducedAsync ? "async" : "sync")}message for {kafkaMessage.Key}"); - if (sampleMessage.IsProducedAsync) + if (string.IsNullOrEmpty(kafkaMessage.Value)) + { + Console.WriteLine($"Received Tombstone for {kafkaMessage.Key}"); + Interlocked.Increment(ref TotalTombstones); + } + else + { + var sampleMessage = JsonConvert.DeserializeObject(kafkaMessage.Value); + Console.WriteLine($"Received {(sampleMessage.IsProducedAsync ? "async" : "sync")}message for {kafkaMessage.Key}"); + if (sampleMessage.IsProducedAsync) Interlocked.Increment(ref TotalAsyncMessages); else Interlocked.Increment(ref TotalSyncMessages); } - span?.End(); - } - - public void Dispose() - { - Console.WriteLine($"{_consumerName}: Closing consumer"); - _consumer?.Close(); - _consumer?.Dispose(); - } - - public static Consumer Create(ClientConfig clientConfig, bool enableAutoCommit, string topic, string consumerName) - { - Console.WriteLine($"Creating consumer '{consumerName}' and subscribing to topic {topic}"); + span?.End(); + } + + public void Dispose() + { + Console.WriteLine($"{_consumerName}: Closing consumer"); + _consumer?.Close(); + _consumer?.Dispose(); + } + + public static Consumer Create(ClientConfig clientConfig, bool enableAutoCommit, string topic, string consumerName) + { + Console.WriteLine($"Creating consumer '{consumerName}' and subscribing to topic {topic}"); var config = new ConsumerConfig(clientConfig) { GroupId = "KafkaSample", AutoOffsetReset = AutoOffsetReset.Earliest, EnableAutoCommit = enableAutoCommit, - }; - return new Consumer(config, topic, consumerName); - } - } + }; + return new Consumer(config, topic, consumerName); + } + } } diff --git a/test/profiler/applications/KafkaSample/Producer.cs b/test/profiler/applications/KafkaSample/Producer.cs index aa4184a47..93f53204f 100644 --- a/test/profiler/applications/KafkaSample/Producer.cs +++ b/test/profiler/applications/KafkaSample/Producer.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on Producer type in https://github.com/DataDog/dd-trace-dotnet/blob/master/tracer/test/test-applications/integrations/Samples.Kafka/Producer.cs -// Licensed under Apache 2.0 - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on Producer type in https://github.com/DataDog/dd-trace-dotnet/blob/master/tracer/test/test-applications/integrations/Samples.Kafka/Producer.cs +// Licensed under Apache 2.0 + using System; using System.Threading; using System.Threading.Tasks; @@ -16,13 +16,13 @@ using Newtonsoft.Json.Linq; namespace KafkaSample -{ - internal static class Producer - { - // Flush every x messages - private const int FlushInterval = 3; - private static readonly TimeSpan FlushTimeout = TimeSpan.FromSeconds(5); - private static int MessageNumber; +{ + internal static class Producer + { + // Flush every x messages + private const int FlushInterval = 3; + private static readonly TimeSpan FlushTimeout = TimeSpan.FromSeconds(5); + private static int MessageNumber; public static async Task ProduceAsync(string topic, int numMessages, ClientConfig config, bool isTombstone) => await Agent.Tracer.CaptureTransaction($"Produce Messages Async {topic}", ApiConstants.TypeMessaging, async () => @@ -53,14 +53,14 @@ internal static class Producer Console.WriteLine($"Finished producing {numMessages} messages to topic {topic}"); }); - private static void Flush(IProducer producer) - { - var queueLength = 1; - while (queueLength > 0) + private static void Flush(IProducer producer) + { + var queueLength = 1; + while (queueLength > 0) queueLength = producer.Flush(FlushTimeout); - } - - public static void Produce(string topic, int numMessages, ClientConfig config, bool handleDelivery, bool isTombstone) => + } + + public static void Produce(string topic, int numMessages, ClientConfig config, bool handleDelivery, bool isTombstone) => Produce(topic, numMessages, config, handleDelivery ? HandleDelivery : null, isTombstone); private static void Produce(string topic, int numMessages, ClientConfig config, Action> deliveryHandler, bool isTombstone) => @@ -94,10 +94,10 @@ private static void Flush(IProducer producer) ? $"Failed to deliver message: {deliveryReport.Error.Reason}" : $"Produced message to: {deliveryReport.TopicPartitionOffset}"); - private static string GetMessage(int iteration, bool isProducedAsync) - { - var message = new SampleMessage("fruit", iteration, isProducedAsync); - return JObject.FromObject(message).ToString(Formatting.None); - } - } + private static string GetMessage(int iteration, bool isProducedAsync) + { + var message = new SampleMessage("fruit", iteration, isProducedAsync); + return JObject.FromObject(message).ToString(Formatting.None); + } + } } diff --git a/test/profiler/applications/KafkaSample/Program.cs b/test/profiler/applications/KafkaSample/Program.cs index e8e5bc55a..9f559c151 100644 --- a/test/profiler/applications/KafkaSample/Program.cs +++ b/test/profiler/applications/KafkaSample/Program.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on Producer type in https://github.com/DataDog/dd-trace-dotnet/blob/master/tracer/test/test-applications/integrations/Samples.Kafka -// Licensed under Apache 2.0 - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on Producer type in https://github.com/DataDog/dd-trace-dotnet/blob/master/tracer/test/test-applications/integrations/Samples.Kafka +// Licensed under Apache 2.0 + using System; using System.Collections.Generic; using System.Threading; @@ -33,79 +33,79 @@ private static async Task Main(string[] args) await ProduceMessagesInvalidTopic(config); - var ignoreMessageQueues = Environment.GetEnvironmentVariable("ELASTIC_APM_IGNORE_MESSAGE_QUEUES"); - - // only run the ignore produce and consume if the agent has been configured with the ignore topic + var ignoreMessageQueues = Environment.GetEnvironmentVariable("ELASTIC_APM_IGNORE_MESSAGE_QUEUES"); + + // only run the ignore produce and consume if the agent has been configured with the ignore topic if (!string.IsNullOrEmpty(ignoreMessageQueues) && ignoreMessageQueues.Contains(IgnoreTopic)) { await CreateTopic(config, IgnoreTopic); await ConsumeAndProduceMessages(IgnoreTopic, config, 1); - } - - // allow time for agent to send APM data + } + + // allow time for agent to send APM data await Task.Delay(TimeSpan.FromSeconds(30)); Console.WriteLine("finished"); } - private static async Task ConsumeAndProduceMessages(string topic, ClientConfig config, int numberOfMessagesPerProducer = 10) - { - var commitPeriod = 3; + private static async Task ConsumeAndProduceMessages(string topic, ClientConfig config, int numberOfMessagesPerProducer = 10) + { + var commitPeriod = 3; var cts = new CancellationTokenSource(); using var consumer1 = Consumer.Create(config, true, topic, "AutoCommitConsumer1"); - using var consumer2 = Consumer.Create(config, false, topic, "ManualCommitConsumer2"); - - Console.WriteLine("Starting consumers..."); - - var consumeTask1 = Task.Run(() => consumer1.Consume(cts.Token)); - var consumeTask2 = Task.Run(() => consumer2.ConsumeWithExplicitCommit(commitEveryXMessages: commitPeriod, cts.Token)); - - Console.WriteLine($"Producing messages"); - - var messagesProduced = await ProduceMessages(topic, config, numberOfMessagesPerProducer); - - // Wait for all messages to be consumed - // This assumes that the topic starts empty, and nothing else is producing to the topic - var deadline = DateTime.UtcNow.AddSeconds(30); - while (true) - { - var syncCount = Volatile.Read(ref Consumer.TotalSyncMessages); - var asyncCount = Volatile.Read(ref Consumer.TotalAsyncMessages); - var tombstoneCount = Volatile.Read(ref Consumer.TotalTombstones); - - if (syncCount >= messagesProduced.SyncMessages - && asyncCount >= messagesProduced.AsyncMessages - && tombstoneCount >= messagesProduced.TombstoneMessages) - { - Console.WriteLine($"All messages produced and consumed"); - break; - } - - if (DateTime.UtcNow > deadline) - { - Console.WriteLine($"Exiting consumer: did not consume all messages syncCount {syncCount}, asyncCount {asyncCount}"); - break; - } - - await Task.Delay(1000); - } - - cts.Cancel(); - Console.WriteLine($"Waiting for graceful exit..."); - - await Task.WhenAny( - Task.WhenAll(consumeTask1, consumeTask2), - Task.Delay(TimeSpan.FromSeconds(5))); - } + using var consumer2 = Consumer.Create(config, false, topic, "ManualCommitConsumer2"); + + Console.WriteLine("Starting consumers..."); + + var consumeTask1 = Task.Run(() => consumer1.Consume(cts.Token)); + var consumeTask2 = Task.Run(() => consumer2.ConsumeWithExplicitCommit(commitEveryXMessages: commitPeriod, cts.Token)); + + Console.WriteLine($"Producing messages"); + + var messagesProduced = await ProduceMessages(topic, config, numberOfMessagesPerProducer); + + // Wait for all messages to be consumed + // This assumes that the topic starts empty, and nothing else is producing to the topic + var deadline = DateTime.UtcNow.AddSeconds(30); + while (true) + { + var syncCount = Volatile.Read(ref Consumer.TotalSyncMessages); + var asyncCount = Volatile.Read(ref Consumer.TotalAsyncMessages); + var tombstoneCount = Volatile.Read(ref Consumer.TotalTombstones); + + if (syncCount >= messagesProduced.SyncMessages + && asyncCount >= messagesProduced.AsyncMessages + && tombstoneCount >= messagesProduced.TombstoneMessages) + { + Console.WriteLine($"All messages produced and consumed"); + break; + } + + if (DateTime.UtcNow > deadline) + { + Console.WriteLine($"Exiting consumer: did not consume all messages syncCount {syncCount}, asyncCount {asyncCount}"); + break; + } + + await Task.Delay(1000); + } + + cts.Cancel(); + Console.WriteLine($"Waiting for graceful exit..."); + + await Task.WhenAny( + Task.WhenAll(consumeTask1, consumeTask2), + Task.Delay(TimeSpan.FromSeconds(5))); + } private static async Task ProduceMessagesInvalidTopic(ClientConfig config) - { - // try to produce invalid messages + { + // try to produce invalid messages const string invalidTopic = "INVALID-TOPIC"; - Producer.Produce(invalidTopic, 1, config, true, false); // failure should be logged by delivery handler - + Producer.Produce(invalidTopic, 1, config, true, false); // failure should be logged by delivery handler + try { await Producer.ProduceAsync(invalidTopic, 1, config, isTombstone: false); @@ -114,35 +114,35 @@ private static async Task ProduceMessagesInvalidTopic(ClientConfig config) { Console.WriteLine($"Error producing a message to an unknown topic (expected): {ex}"); } + } + + private static async Task ProduceMessages(string topic, ClientConfig config, int numberOfMessagesPerProducer) + { + // Send valid messages + Producer.Produce(topic, numberOfMessagesPerProducer, config, false, false); + Producer.Produce(topic, numberOfMessagesPerProducer, config, true, false); + await Producer.ProduceAsync(topic, numberOfMessagesPerProducer, config, false); + + // Send tombstone messages + Producer.Produce(topic, numberOfMessagesPerProducer, config, false, true); + Producer.Produce(topic, numberOfMessagesPerProducer, config, true, true); + await Producer.ProduceAsync(topic, numberOfMessagesPerProducer, config, true); + + return new MessagesProduced + { + SyncMessages = numberOfMessagesPerProducer * 2, + AsyncMessages = numberOfMessagesPerProducer * 1, + TombstoneMessages = numberOfMessagesPerProducer * 3, + }; + } + + private struct MessagesProduced + { + public int SyncMessages; + public int AsyncMessages; + public int TombstoneMessages; } - private static async Task ProduceMessages(string topic, ClientConfig config, int numberOfMessagesPerProducer) - { - // Send valid messages - Producer.Produce(topic, numberOfMessagesPerProducer, config, false, false); - Producer.Produce(topic, numberOfMessagesPerProducer, config, true, false); - await Producer.ProduceAsync(topic, numberOfMessagesPerProducer, config, false); - - // Send tombstone messages - Producer.Produce(topic, numberOfMessagesPerProducer, config, false, true); - Producer.Produce(topic, numberOfMessagesPerProducer, config, true, true); - await Producer.ProduceAsync(topic, numberOfMessagesPerProducer, config, true); - - return new MessagesProduced - { - SyncMessages = numberOfMessagesPerProducer * 2, - AsyncMessages = numberOfMessagesPerProducer * 1, - TombstoneMessages = numberOfMessagesPerProducer * 3, - }; - } - - private struct MessagesProduced - { - public int SyncMessages; - public int AsyncMessages; - public int TombstoneMessages; - } - private static async Task CreateTopic(ClientConfig config, string topic) { using var adminClient = new AdminClientBuilder(config).Build(); diff --git a/test/profiler/applications/KafkaSample/SampleMessage.cs b/test/profiler/applications/KafkaSample/SampleMessage.cs index 5a720d298..e27dccdaa 100644 --- a/test/profiler/applications/KafkaSample/SampleMessage.cs +++ b/test/profiler/applications/KafkaSample/SampleMessage.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on Producer type in https://github.com/DataDog/dd-trace-dotnet/blob/master/tracer/test/test-applications/integrations/Samples.Kafka/Producer.cs#L107-L119 -// Licensed under Apache 2.0 - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on Producer type in https://github.com/DataDog/dd-trace-dotnet/blob/master/tracer/test/test-applications/integrations/Samples.Kafka/Producer.cs#L107-L119 +// Licensed under Apache 2.0 + namespace KafkaSample { public class SampleMessage diff --git a/test/profiler/applications/MySqlDataSample/MySqlDataCommandExecutor.cs b/test/profiler/applications/MySqlDataSample/MySqlDataCommandExecutor.cs index ec7860a74..3b5e2ca30 100644 --- a/test/profiler/applications/MySqlDataSample/MySqlDataCommandExecutor.cs +++ b/test/profiler/applications/MySqlDataSample/MySqlDataCommandExecutor.cs @@ -1,10 +1,10 @@ -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Data; using System.Data.Common; using System.Threading; diff --git a/test/profiler/applications/MySqlDataSample/Program.cs b/test/profiler/applications/MySqlDataSample/Program.cs index 4c82fdaac..7ad03e3fe 100644 --- a/test/profiler/applications/MySqlDataSample/Program.cs +++ b/test/profiler/applications/MySqlDataSample/Program.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Data.Common; using System.Reflection; @@ -45,9 +45,9 @@ private static async Task Main(string[] args) cancellationTokenSource.Token); } - Console.WriteLine("Finished sending commands"); - - // allow the agent time to send the spans + Console.WriteLine("Finished sending commands"); + + // allow the agent time to send the spans await Task.Delay(TimeSpan.FromSeconds(40), cancellationTokenSource.Token); return 0; } diff --git a/test/profiler/applications/NpgsqlSample/NpgsqlCommandExecutor.cs b/test/profiler/applications/NpgsqlSample/NpgsqlCommandExecutor.cs index 71bce39f6..23717a236 100644 --- a/test/profiler/applications/NpgsqlSample/NpgsqlCommandExecutor.cs +++ b/test/profiler/applications/NpgsqlSample/NpgsqlCommandExecutor.cs @@ -1,10 +1,10 @@ -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Data; using System.Data.Common; using System.Threading; diff --git a/test/profiler/applications/NpgsqlSample/Program.cs b/test/profiler/applications/NpgsqlSample/Program.cs index a5a0ebe55..85c3b2f96 100644 --- a/test/profiler/applications/NpgsqlSample/Program.cs +++ b/test/profiler/applications/NpgsqlSample/Program.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Data.Common; using System.Reflection; @@ -45,9 +45,9 @@ private static async Task Main(string[] args) cancellationTokenSource.Token); } - Console.WriteLine("Finished sending commands"); - - // allow the agent time to send the spans + Console.WriteLine("Finished sending commands"); + + // allow the agent time to send the spans await Task.Delay(TimeSpan.FromSeconds(40), cancellationTokenSource.Token); return 0; } diff --git a/test/profiler/applications/OracleManagedDataAccessCoreSample/OracleCommandExecutor.cs b/test/profiler/applications/OracleManagedDataAccessCoreSample/OracleCommandExecutor.cs index 93813f17a..9fb99cad1 100644 --- a/test/profiler/applications/OracleManagedDataAccessCoreSample/OracleCommandExecutor.cs +++ b/test/profiler/applications/OracleManagedDataAccessCoreSample/OracleCommandExecutor.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Data; using System.Data.Common; using System.Threading; diff --git a/test/profiler/applications/OracleManagedDataAccessCoreSample/OracleDbCommandFactory.cs b/test/profiler/applications/OracleManagedDataAccessCoreSample/OracleDbCommandFactory.cs index 94965b170..6ef67358a 100644 --- a/test/profiler/applications/OracleManagedDataAccessCoreSample/OracleDbCommandFactory.cs +++ b/test/profiler/applications/OracleManagedDataAccessCoreSample/OracleDbCommandFactory.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Data; using Elastic.Apm.AdoNet; diff --git a/test/profiler/applications/OracleManagedDataAccessCoreSample/Program.cs b/test/profiler/applications/OracleManagedDataAccessCoreSample/Program.cs index b304adad0..8a297201b 100644 --- a/test/profiler/applications/OracleManagedDataAccessCoreSample/Program.cs +++ b/test/profiler/applications/OracleManagedDataAccessCoreSample/Program.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Data.Common; using System.Reflection; @@ -45,9 +45,9 @@ private static async Task Main(string[] args) cancellationTokenSource.Token); } - Console.WriteLine("Finished sending commands"); - - // allow the agent time to send the spans + Console.WriteLine("Finished sending commands"); + + // allow the agent time to send the spans await Task.Delay(TimeSpan.FromSeconds(40), cancellationTokenSource.Token); return 0; } diff --git a/test/profiler/applications/OracleManagedDataAccessSample/OracleCommandExecutor.cs b/test/profiler/applications/OracleManagedDataAccessSample/OracleCommandExecutor.cs index 6fb4d9fd7..59a23805a 100644 --- a/test/profiler/applications/OracleManagedDataAccessSample/OracleCommandExecutor.cs +++ b/test/profiler/applications/OracleManagedDataAccessSample/OracleCommandExecutor.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Data; using System.Data.Common; using System.Threading; diff --git a/test/profiler/applications/OracleManagedDataAccessSample/OracleDbCommandFactory.cs b/test/profiler/applications/OracleManagedDataAccessSample/OracleDbCommandFactory.cs index 79c7c1195..44bb7b47b 100644 --- a/test/profiler/applications/OracleManagedDataAccessSample/OracleDbCommandFactory.cs +++ b/test/profiler/applications/OracleManagedDataAccessSample/OracleDbCommandFactory.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Data; using Elastic.Apm.AdoNet; diff --git a/test/profiler/applications/OracleManagedDataAccessSample/Program.cs b/test/profiler/applications/OracleManagedDataAccessSample/Program.cs index 29833c465..7d5ca62f2 100644 --- a/test/profiler/applications/OracleManagedDataAccessSample/Program.cs +++ b/test/profiler/applications/OracleManagedDataAccessSample/Program.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Data.Common; using System.Reflection; @@ -19,7 +19,7 @@ private static async Task Main(string[] args) { var cancellationTokenSource = new CancellationTokenSource(); var connectionType = typeof(OracleConnection); - var guid = Guid.NewGuid().ToString("N").Substring(0,8); + var guid = Guid.NewGuid().ToString("N").Substring(0, 8); Console.WriteLine($"Run commands ({guid})"); @@ -45,9 +45,9 @@ private static async Task Main(string[] args) cancellationTokenSource.Token); } - Console.WriteLine("Finished sending commands"); - - // allow the agent time to send the spans + Console.WriteLine("Finished sending commands"); + + // allow the agent time to send the spans await Task.Delay(TimeSpan.FromSeconds(40), cancellationTokenSource.Token); return 0; } diff --git a/test/profiler/applications/RabbitMqSample/Program.cs b/test/profiler/applications/RabbitMqSample/Program.cs index d7c42b79e..10c47775a 100644 --- a/test/profiler/applications/RabbitMqSample/Program.cs +++ b/test/profiler/applications/RabbitMqSample/Program.cs @@ -1,26 +1,26 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on https://github.com/DataDog/dd-trace-dotnet/blob/a72b74fc8e67d8d8a6430628fe8643b3a693d2bc/tracer/test/test-applications/integrations/Samples.RabbitMQ/Program.cs -// Licensed under Apache 2.0 - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on https://github.com/DataDog/dd-trace-dotnet/blob/a72b74fc8e67d8d8a6430628fe8643b3a693d2bc/tracer/test/test-applications/integrations/Samples.RabbitMQ/Program.cs +// Licensed under Apache 2.0 + using System; using System.Text; using System.Threading; using Elastic.Apm; using Elastic.Apm.Api; using RabbitMQ.Client; -using RabbitMQ.Client.Events; -// ReSharper disable AccessToDisposedClosure - -// ReSharper disable AccessToDisposedClosure - +using RabbitMQ.Client.Events; +// ReSharper disable AccessToDisposedClosure + +// ReSharper disable AccessToDisposedClosure + namespace RabbitMqSample { - internal class Program - { + internal class Program + { private static volatile int MessageCount; private static readonly AutoResetEvent SendFinished = new(false); @@ -38,9 +38,9 @@ internal class Program public static void Main(string[] args) { - var ignoreMessageQueues = Environment.GetEnvironmentVariable("ELASTIC_APM_IGNORE_MESSAGE_QUEUES"); - - // only run the ignore publish and get if the agent has been configured with the ignore exchange and queue. + var ignoreMessageQueues = Environment.GetEnvironmentVariable("ELASTIC_APM_IGNORE_MESSAGE_QUEUES"); + + // only run the ignore publish and get if the agent has been configured with the ignore exchange and queue. if (!string.IsNullOrEmpty(ignoreMessageQueues) && ignoreMessageQueues.Contains(IgnoreExchangeName) && ignoreMessageQueues.Contains(IgnoreQueueName)) @@ -56,20 +56,20 @@ public static void Main(string[] args) receiveThread.Start(); sendThread.Join(); - receiveThread.Join(); - - // Allow time for the agent to send data + receiveThread.Join(); + + // Allow time for the agent to send data Thread.Sleep(TimeSpan.FromSeconds(30)); - Console.WriteLine("finished"); - } - - private static void PublishAndGet(string name, string exchange, string queue, string routingKey) - { - // Configure and send to RabbitMQ queue - var factory = new ConnectionFactory { Uri = new Uri(Host()) }; - - using (var connection = factory.CreateConnection()) - using (var channel = connection.CreateModel()) + Console.WriteLine("finished"); + } + + private static void PublishAndGet(string name, string exchange, string queue, string routingKey) + { + // Configure and send to RabbitMQ queue + var factory = new ConnectionFactory { Uri = new Uri(Host()) }; + + using (var connection = factory.CreateConnection()) + using (var channel = connection.CreateModel()) { Agent.Tracer.CaptureTransaction(name, "messaging", () => { @@ -80,12 +80,12 @@ private static void PublishAndGet(string name, string exchange, string queue, st autoDelete: false, arguments: null); channel.QueueBind(queue, exchange, routingKey); - channel.QueuePurge(queue); // Ensure there are no more messages in this queue - - // Test an empty BasicGetResult - channel.BasicGet(queue, true); - - // Send message to the exchange + channel.QueuePurge(queue); // Ensure there are no more messages in this queue + + // Test an empty BasicGetResult + channel.BasicGet(queue, true); + + // Send message to the exchange var message = $"{name} - Message"; var body = Encoding.UTF8.GetBytes(message); @@ -95,37 +95,37 @@ private static void PublishAndGet(string name, string exchange, string queue, st body: body); Console.WriteLine($"[{name}] BasicPublish - Sent message: {message}"); - var result = channel.BasicGet(queue, true); + var result = channel.BasicGet(queue, true); #if RABBITMQ_6_0 - var resultMessage = Encoding.UTF8.GetString(result.Body.ToArray()); + var resultMessage = Encoding.UTF8.GetString(result.Body.ToArray()); #else var resultMessage = Encoding.UTF8.GetString(result.Body); #endif - Console.WriteLine($"[{name}] BasicGet - Received message: {resultMessage}"); - // ReSharper restore AccessToDisposedClosure + Console.WriteLine($"[{name}] BasicGet - Received message: {resultMessage}"); + // ReSharper restore AccessToDisposedClosure }); - } - } - - private static void PublishAndGetDefault() - { - // Configure and send to RabbitMQ queue - var factory = new ConnectionFactory() { Uri = new Uri(Host()) }; - - using (var connection = factory.CreateConnection()) - using (var channel = connection.CreateModel()) - { - string defaultQueueName; + } + } + + private static void PublishAndGetDefault() + { + // Configure and send to RabbitMQ queue + var factory = new ConnectionFactory() { Uri = new Uri(Host()) }; + + using (var connection = factory.CreateConnection()) + using (var channel = connection.CreateModel()) + { + string defaultQueueName; Agent.Tracer.CaptureTransaction("PublishAndGetDefault", "messaging", () => { defaultQueueName = channel.QueueDeclare().QueueName; - channel.QueuePurge(QueueName); // Ensure there are no more messages in this queue - - // Test an empty BasicGetResult - channel.BasicGet(defaultQueueName, true); - - // Send message to the default exchange and use new queue as the routingKey + channel.QueuePurge(QueueName); // Ensure there are no more messages in this queue + + // Test an empty BasicGetResult + channel.BasicGet(defaultQueueName, true); + + // Send message to the default exchange and use new queue as the routingKey var message = "PublishAndGetDefault - Message"; var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", @@ -134,33 +134,33 @@ private static void PublishAndGetDefault() body: body); Console.WriteLine($"[PublishAndGetDefault] BasicPublish - Sent message: {message}"); - var result = channel.BasicGet(defaultQueueName, true); + var result = channel.BasicGet(defaultQueueName, true); #if RABBITMQ_6_0 - var resultMessage = Encoding.UTF8.GetString(result.Body.ToArray()); + var resultMessage = Encoding.UTF8.GetString(result.Body.ToArray()); #else var resultMessage = Encoding.UTF8.GetString(result.Body); #endif - + Console.WriteLine($"[PublishAndGetDefault] BasicGet - Received message: {resultMessage}"); }); - } - } - - private static void Send() - { - // Configure and send to RabbitMQ queue - var factory = new ConnectionFactory() { Uri = new Uri(Host()) }; - using(var connection = factory.CreateConnection()) - using(var channel = connection.CreateModel()) - { - channel.QueueDeclare(queue: "hello", - durable: false, - exclusive: false, - autoDelete: false, - arguments: null); - channel.QueuePurge("hello"); // Ensure there are no more messages in this queue - - for (var i = 0; i < 3; i++) + } + } + + private static void Send() + { + // Configure and send to RabbitMQ queue + var factory = new ConnectionFactory() { Uri = new Uri(Host()) }; + using (var connection = factory.CreateConnection()) + using (var channel = connection.CreateModel()) + { + channel.QueueDeclare(queue: "hello", + durable: false, + exclusive: false, + autoDelete: false, + arguments: null); + channel.QueuePurge("hello"); // Ensure there are no more messages in this queue + + for (var i = 0; i < 3; i++) { Agent.Tracer.CaptureTransaction("PublishToConsumer", "messaging", () => { @@ -174,57 +174,57 @@ private static void Send() Console.WriteLine("[Send] - [x] Sent \"{0}\"", message); Interlocked.Increment(ref MessageCount); }); - } - } - - SendFinished.Set(); - Console.WriteLine("[Send] Exiting Thread."); - } - - private static void Receive() - { - // Let's just wait for all sending activity to finish before doing any work - SendFinished.WaitOne(); - - // Configure and listen to RabbitMQ queue - var factory = new ConnectionFactory { Uri = new Uri(Host()) }; - using(var connection = factory.CreateConnection()) - using(var channel = connection.CreateModel()) - { - channel.QueueDeclare(queue: "hello", - durable: false, - exclusive: false, - autoDelete: false, - arguments: null); - - var consumer = new EventingBasicConsumer(channel); - consumer.Received += (_, ea) => - { + } + } + + SendFinished.Set(); + Console.WriteLine("[Send] Exiting Thread."); + } + + private static void Receive() + { + // Let's just wait for all sending activity to finish before doing any work + SendFinished.WaitOne(); + + // Configure and listen to RabbitMQ queue + var factory = new ConnectionFactory { Uri = new Uri(Host()) }; + using (var connection = factory.CreateConnection()) + using (var channel = connection.CreateModel()) + { + channel.QueueDeclare(queue: "hello", + durable: false, + exclusive: false, + autoDelete: false, + arguments: null); + + var consumer = new EventingBasicConsumer(channel); + consumer.Received += (_, ea) => + { var transaction = Agent.Tracer.CurrentTransaction; - var span = transaction?.StartSpan("Consume message", ApiConstants.TypeMessaging); - + var span = transaction?.StartSpan("Consume message", ApiConstants.TypeMessaging); + #if RABBITMQ_6_0 - var body = ea.Body.ToArray(); + var body = ea.Body.ToArray(); #else var body = ea.Body; #endif - - var message = Encoding.UTF8.GetString(body); - Console.WriteLine("[Receive] - [x] Received {0}", message); + + var message = Encoding.UTF8.GetString(body); + Console.WriteLine("[Receive] - [x] Received {0}", message); Interlocked.Decrement(ref MessageCount); - span?.End(); - }; - - channel.BasicConsume("hello", - true, - consumer); - - while (MessageCount != 0) + span?.End(); + }; + + channel.BasicConsume("hello", + true, + consumer); + + while (MessageCount != 0) Thread.Sleep(1000); - Console.WriteLine("[Receive] Exiting Thread."); - } - } - } + Console.WriteLine("[Receive] Exiting Thread."); + } + } + } } diff --git a/test/profiler/applications/SatelliteAssemblySample/Program.cs b/test/profiler/applications/SatelliteAssemblySample/Program.cs index fd8190a67..d4b6cfd7e 100644 --- a/test/profiler/applications/SatelliteAssemblySample/Program.cs +++ b/test/profiler/applications/SatelliteAssemblySample/Program.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using Microsoft.FSharp.Collections; var germanCulture = new CultureInfo("de"); diff --git a/test/profiler/applications/SqlClientSample/Program.cs b/test/profiler/applications/SqlClientSample/Program.cs index 0d6a1325c..9655313a6 100644 --- a/test/profiler/applications/SqlClientSample/Program.cs +++ b/test/profiler/applications/SqlClientSample/Program.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Data.Common; using System.Data.SqlClient; @@ -45,9 +45,9 @@ private static async Task Main() cancellationTokenSource.Token); } - Console.WriteLine("Finished sending commands"); - - // allow the agent time to send the spans + Console.WriteLine("Finished sending commands"); + + // allow the agent time to send the spans await Task.Delay(TimeSpan.FromSeconds(40), cancellationTokenSource.Token); return 0; } diff --git a/test/profiler/applications/SqlClientSample/SqlCommandExecutor.cs b/test/profiler/applications/SqlClientSample/SqlCommandExecutor.cs index 14fed4872..4818be053 100644 --- a/test/profiler/applications/SqlClientSample/SqlCommandExecutor.cs +++ b/test/profiler/applications/SqlClientSample/SqlCommandExecutor.cs @@ -1,11 +1,11 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information -// -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information +// +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet + using System.Data; using System.Data.Common; using System.Data.SqlClient; @@ -16,51 +16,51 @@ namespace SqlClientSample { public class SqlCommandExecutor : DbCommandExecutor - { - public override string CommandTypeName => nameof(SqlCommand); - - public override bool SupportsAsyncMethods => true; - - public override void ExecuteNonQuery(SqlCommand command) => command.ExecuteNonQuery(); - - public override Task ExecuteNonQueryAsync(SqlCommand command) => command.ExecuteNonQueryAsync(); - - public override Task ExecuteNonQueryAsync(SqlCommand command, CancellationToken cancellationToken) => command.ExecuteNonQueryAsync(cancellationToken); - - public override void ExecuteScalar(SqlCommand command) => command.ExecuteScalar(); - - public override Task ExecuteScalarAsync(SqlCommand command) => command.ExecuteScalarAsync(); - - public override Task ExecuteScalarAsync(SqlCommand command, CancellationToken cancellationToken) => command.ExecuteScalarAsync(cancellationToken); - - public override void ExecuteReader(SqlCommand command) - { - using DbDataReader reader = command.ExecuteReader(); - } - - public override void ExecuteReader(SqlCommand command, CommandBehavior behavior) - { - using DbDataReader reader = command.ExecuteReader(behavior); - } - - public override async Task ExecuteReaderAsync(SqlCommand command) - { - using DbDataReader reader = await command.ExecuteReaderAsync(); - } - - public override async Task ExecuteReaderAsync(SqlCommand command, CommandBehavior behavior) - { - using DbDataReader reader = await command.ExecuteReaderAsync(behavior); - } - - public override async Task ExecuteReaderAsync(SqlCommand command, CancellationToken cancellationToken) - { - using DbDataReader reader = await command.ExecuteReaderAsync(cancellationToken); - } - - public override async Task ExecuteReaderAsync(SqlCommand command, CommandBehavior behavior, CancellationToken cancellationToken) - { - using DbDataReader reader = await command.ExecuteReaderAsync(behavior, cancellationToken); - } + { + public override string CommandTypeName => nameof(SqlCommand); + + public override bool SupportsAsyncMethods => true; + + public override void ExecuteNonQuery(SqlCommand command) => command.ExecuteNonQuery(); + + public override Task ExecuteNonQueryAsync(SqlCommand command) => command.ExecuteNonQueryAsync(); + + public override Task ExecuteNonQueryAsync(SqlCommand command, CancellationToken cancellationToken) => command.ExecuteNonQueryAsync(cancellationToken); + + public override void ExecuteScalar(SqlCommand command) => command.ExecuteScalar(); + + public override Task ExecuteScalarAsync(SqlCommand command) => command.ExecuteScalarAsync(); + + public override Task ExecuteScalarAsync(SqlCommand command, CancellationToken cancellationToken) => command.ExecuteScalarAsync(cancellationToken); + + public override void ExecuteReader(SqlCommand command) + { + using DbDataReader reader = command.ExecuteReader(); + } + + public override void ExecuteReader(SqlCommand command, CommandBehavior behavior) + { + using DbDataReader reader = command.ExecuteReader(behavior); + } + + public override async Task ExecuteReaderAsync(SqlCommand command) + { + using DbDataReader reader = await command.ExecuteReaderAsync(); + } + + public override async Task ExecuteReaderAsync(SqlCommand command, CommandBehavior behavior) + { + using DbDataReader reader = await command.ExecuteReaderAsync(behavior); + } + + public override async Task ExecuteReaderAsync(SqlCommand command, CancellationToken cancellationToken) + { + using DbDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + } + + public override async Task ExecuteReaderAsync(SqlCommand command, CommandBehavior behavior, CancellationToken cancellationToken) + { + using DbDataReader reader = await command.ExecuteReaderAsync(behavior, cancellationToken); + } } } diff --git a/test/profiler/applications/SqliteSample/Program.cs b/test/profiler/applications/SqliteSample/Program.cs index fca027946..5a5a3432e 100644 --- a/test/profiler/applications/SqliteSample/Program.cs +++ b/test/profiler/applications/SqliteSample/Program.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Data.Common; using System.Reflection; @@ -45,9 +45,9 @@ private static async Task Main() cancellationTokenSource.Token); } - Console.WriteLine("Finished sending commands"); - - // allow the agent time to send the spans + Console.WriteLine("Finished sending commands"); + + // allow the agent time to send the spans await Task.Delay(TimeSpan.FromSeconds(40), cancellationTokenSource.Token); return 0; } diff --git a/test/profiler/applications/SqliteSample/SqliteCommandExecutor.cs b/test/profiler/applications/SqliteSample/SqliteCommandExecutor.cs index 3486767be..324700987 100644 --- a/test/profiler/applications/SqliteSample/SqliteCommandExecutor.cs +++ b/test/profiler/applications/SqliteSample/SqliteCommandExecutor.cs @@ -1,10 +1,10 @@ -// Based on .NET Tracer for Datadog APM by Datadog -// https://github.com/DataDog/dd-trace-dotnet -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Based on .NET Tracer for Datadog APM by Datadog +// https://github.com/DataDog/dd-trace-dotnet +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System.Data; using System.Data.Common; using System.Threading; diff --git a/test/startuphook/Elastic.Apm.StartupHook.Sample/Controllers/HomeController.cs b/test/startuphook/Elastic.Apm.StartupHook.Sample/Controllers/HomeController.cs index e3d72d13c..994789ffe 100644 --- a/test/startuphook/Elastic.Apm.StartupHook.Sample/Controllers/HomeController.cs +++ b/test/startuphook/Elastic.Apm.StartupHook.Sample/Controllers/HomeController.cs @@ -1,14 +1,14 @@ -using System; +using System; using System.Diagnostics; +using Elastic.Apm.StartupHook.Sample.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; -using Elastic.Apm.StartupHook.Sample.Models; namespace Elastic.Apm.StartupHook.Sample.Controllers { public class HomeController : Controller - { - // ReSharper disable once NotAccessedField.Local + { + // ReSharper disable once NotAccessedField.Local private readonly ILogger _logger; public HomeController(ILogger logger) => _logger = logger; diff --git a/test/startuphook/Elastic.Apm.StartupHook.Sample/Startup.cs b/test/startuphook/Elastic.Apm.StartupHook.Sample/Startup.cs index 54d75465a..4759bc7dd 100644 --- a/test/startuphook/Elastic.Apm.StartupHook.Sample/Startup.cs +++ b/test/startuphook/Elastic.Apm.StartupHook.Sample/Startup.cs @@ -9,19 +9,19 @@ public class Startup { public Startup(IConfiguration configuration) => Configuration = configuration; - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) - { + { #if NET5_0_OR_GREATER - services.AddControllersWithViews(); + services.AddControllersWithViews(); #else services.AddMvc(); #endif - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseDeveloperExceptionPage(); diff --git a/test/startuphook/Elastic.Apm.StartupHook.Tests/DotnetProject.cs b/test/startuphook/Elastic.Apm.StartupHook.Tests/DotnetProject.cs index 550667c42..ab311bf39 100644 --- a/test/startuphook/Elastic.Apm.StartupHook.Tests/DotnetProject.cs +++ b/test/startuphook/Elastic.Apm.StartupHook.Tests/DotnetProject.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Diagnostics; @@ -12,7 +12,7 @@ using ProcNet; namespace Elastic.Apm.StartupHook.Tests -{ +{ /// /// Creates new dotnet projects from templates, providing the ability to run them /// @@ -27,23 +27,23 @@ private DotnetProject(string name, string template, string framework, string dir Template = template; Framework = framework; Directory = directory; - } - + } + /// /// The directory in which the project is created /// - public string Directory { get; } - + public string Directory { get; } + /// /// The dotnet template used to create the project /// - public string Template { get; } - + public string Template { get; } + /// /// The project target framework /// - public string Framework { get; } - + public string Framework { get; } + /// /// The name of the project /// @@ -68,8 +68,8 @@ private void Publish() { throw new Exception($"Problem running dotnet publish in {Directory} to output to {_publishDirectory}", e); } - } - + } + /// /// Creates a process to run the dotnet project that will start when subscribed to. /// @@ -92,8 +92,8 @@ public ObservableProcess CreateProcess(string startupHookZipPath, IDictionary /// Unzips the agent startup hook zip file to the temp directory, and returns /// the path to the startup hook assembly. diff --git a/test/startuphook/Elastic.Apm.StartupHook.Tests/SampleApplication.cs b/test/startuphook/Elastic.Apm.StartupHook.Tests/SampleApplication.cs index 8d79b773f..781a3b1e1 100644 --- a/test/startuphook/Elastic.Apm.StartupHook.Tests/SampleApplication.cs +++ b/test/startuphook/Elastic.Apm.StartupHook.Tests/SampleApplication.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Diagnostics; @@ -14,7 +14,7 @@ using ProcNet; namespace Elastic.Apm.StartupHook.Tests -{ +{ /// /// A sample ASP.NET 5/Core application that can be instrumented using startup hooks /// @@ -46,8 +46,8 @@ private void Publish(string projectDirectory, string targetFramework) using var process = new Process { StartInfo = processInfo }; process.Start(); process.WaitForExit(); - } - + } + /// /// Starts the sample application and returns the on which the application /// can be reached. @@ -113,8 +113,8 @@ public Uri Start(string targetFramework, IDictionary environment e?.Throw(); return uri; - } - + } + /// /// Unzips the agent startup hook zip file to the temp directory, and returns /// the path to the startup hook assembly. diff --git a/test/startuphook/Elastic.Apm.StartupHook.Tests/SolutionPaths.cs b/test/startuphook/Elastic.Apm.StartupHook.Tests/SolutionPaths.cs index c475b7d12..ea18d8583 100644 --- a/test/startuphook/Elastic.Apm.StartupHook.Tests/SolutionPaths.cs +++ b/test/startuphook/Elastic.Apm.StartupHook.Tests/SolutionPaths.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.IO; using System.Linq; @@ -11,8 +11,8 @@ namespace Elastic.Apm.StartupHook.Tests { public static class SolutionPaths { - private static readonly Lazy _root = new Lazy(FindSolutionRoot); - + private static readonly Lazy _root = new Lazy(FindSolutionRoot); + private static readonly Lazy _agentZip = new Lazy(FindVersionedAgentZip); private static string FindSolutionRoot() { @@ -28,8 +28,8 @@ private static string FindSolutionRoot() } while (candidateDirectory != null); throw new InvalidOperationException($"Could not find solution root directory from the current directory `{currentDirectory}'"); - } - + } + private static string FindVersionedAgentZip() { var buildOutputDir = Path.Combine(Root, "build/output"); @@ -50,8 +50,8 @@ private static string FindVersionedAgentZip() } return agentZip; - } - + } + public static string Root => _root.Value; public static string AgentZip => _agentZip.Value; } diff --git a/test/startuphook/Elastic.Apm.StartupHook.Tests/StartupHookTests.cs b/test/startuphook/Elastic.Apm.StartupHook.Tests/StartupHookTests.cs index ad0ac91e7..46ccd4285 100644 --- a/test/startuphook/Elastic.Apm.StartupHook.Tests/StartupHookTests.cs +++ b/test/startuphook/Elastic.Apm.StartupHook.Tests/StartupHookTests.cs @@ -1,8 +1,8 @@ -// Licensed to Elasticsearch B.V under -// one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - +// Licensed to Elasticsearch B.V under +// one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + using System; using System.Collections.Generic; using System.Linq; @@ -34,20 +34,20 @@ public static IEnumerable DotNetFrameworkVersionInfos() => GetDotNetFrameworkVersionInfos().Select(i => new[] { i.TargetFramework, i.RuntimeName, i.Version }); public static IEnumerable DotNetFrameworks() - => DotNetFrameworkVersionInfos().Select(o => o[0 .. 1]); + => DotNetFrameworkVersionInfos().Select(o => o[0..1]); public static IEnumerable WebAppInfos() { var testData = new List(); foreach (var i in GetDotNetFrameworkVersionInfos()) { - testData.Add(new []{ "webapi", $"WebApi{i.ShortVersion}", i.TargetFramework, "weatherforecast"}); - testData.Add(new []{ "webapp", $"WebApp{i.ShortVersion}", i.TargetFramework, ""}); - testData.Add(new []{ "mvc", $"Mvc{i.ShortVersion}", i.TargetFramework, ""}); + testData.Add(new[] { "webapi", $"WebApi{i.ShortVersion}", i.TargetFramework, "weatherforecast" }); + testData.Add(new[] { "webapp", $"WebApp{i.ShortVersion}", i.TargetFramework, "" }); + testData.Add(new[] { "mvc", $"Mvc{i.ShortVersion}", i.TargetFramework, "" }); } return testData; - } - + } + /// /// Asserts that startup hooks successfully hook up the APM agent and /// send data to mock APM server for the supported framework versions