Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;

namespace Microsoft.Extensions.Telemetry.Bench;

[global::System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Emulating generated code")]
Expand Down Expand Up @@ -35,7 +37,7 @@ public static void RefTypes(global::Microsoft.Extensions.Logging.ILogger logger,
var length = s.TagArray[3].Value ?? "(null)";
var flags = s.TagArray[2].Value ?? "(null)";
var other = s.TagArray[1].Value ?? "(null)";
return global::System.FormattableString.Invariant($"Connection id '{connectionId}' received {type} frame for stream ID {streamId} with length {length} and flags {flags} and {other}");
return string.Create(CultureInfo.InvariantCulture, $"Connection id '{connectionId}' received {type} frame for stream ID {streamId} with length {length} and flags {flags} and {other}");
});

state.Clear();
Expand Down Expand Up @@ -66,7 +68,7 @@ public static void ValueTypes(global::Microsoft.Extensions.Logging.ILogger logge
var end = s.TagArray[3].Value;
var options = s.TagArray[2].Value;
var guid = s.TagArray[1].Value;
return global::System.FormattableString.Invariant($"Range [{start}..{end}], options {options}, guid {guid}");
return string.Create(CultureInfo.InvariantCulture, $"Range [{start}..{end}], options {options}, guid {guid}");
});

state.Clear();
Expand Down
21 changes: 18 additions & 3 deletions eng/Tools/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -2931,7 +2931,7 @@ dotnet_diagnostic.S1067.severity = warning
# Title : Methods should not have too many parameters
# Category : Major Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-107
dotnet_diagnostic.S107.severity = warning
dotnet_diagnostic.S107.severity = none

# Title : URIs should not be hardcoded
# Category : Minor Code Smell
Expand Down Expand Up @@ -3964,7 +3964,7 @@ dotnet_diagnostic.S3246.severity = warning
# Title : Duplicate casts should not be made
# Category : Minor Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-3247
dotnet_diagnostic.S3247.severity = warning
dotnet_diagnostic.S3247.severity = none

# Title : Classes directly extending "object" should not call "base" in "GetHashCode" or "Equals"
# Category : Major Bug
Expand Down Expand Up @@ -5084,7 +5084,7 @@ dotnet_diagnostic.S6585.severity = none
# Title : Use the "UnixEpoch" field instead of creating "DateTime" instances that point to the beginning of the Unix epoch
# Category : Minor Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6588
dotnet_diagnostic.S6588.severity = warning
dotnet_diagnostic.S6588.severity = none

# Title : "Find" method should be used instead of the "FirstOrDefault" extension
# Category : Minor Code Smell
Expand Down Expand Up @@ -5146,6 +5146,21 @@ dotnet_diagnostic.S6618.severity = none
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6640
dotnet_diagnostic.S6640.severity = warning

# Title : Generic logger injection should match enclosing type
# Category : Minor Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6672
dotnet_diagnostic.S6672.severity = none

# Title : Awaitable method should be used
# Category : Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6966
dotnet_diagnostic.S6966.severity = none

# Title : ModelState.IsValid should be called in controller actions
# Category : Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6967
dotnet_diagnostic.S6967.severity = none

# Title : Literal suffixes should be upper case
# Category : Minor Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-818
Expand Down
2 changes: 1 addition & 1 deletion eng/packages/General.props
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
<ItemGroup>
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.10.48" />
<PackageVersion Include="ReferenceTrimmer" Version="3.3.1" />
<PackageVersion Include="SonarAnalyzer.CSharp" Version="8.56.0.67649" />
<PackageVersion Include="SonarAnalyzer.CSharp" Version="10.16.0.128591" />
<PackageVersion Include="StyleCop.Analyzers.Unstable" Version="1.2.0.556" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public void AnalyzeType(INamedTypeSymbol type)
{
var typeSignature = type.ToDisplayString(_format);
var typeModifiersAndName = PrependModifiers(typeSignature, type);
var typeDef = Assembly.Types.FirstOrDefault(x => x.ModifiersAndName == typeModifiersAndName);
var typeDef = Array.Find(Assembly.Types, x => x.ModifiersAndName == typeModifiersAndName);

if (typeDef == null)
{
Expand Down Expand Up @@ -218,7 +218,7 @@ and not MethodKind.EventAdd
{
var methodSignature = member.ToDisplayString(_formatNoVariance) + ";";

var method = typeDef.Methods.FirstOrDefault(x => x.Member == methodSignature);
var method = Array.Find(typeDef.Methods, x => x.Member == methodSignature);
if (method != null)
{
_ = MissingMethods.Remove(method);
Expand All @@ -233,7 +233,7 @@ and not MethodKind.EventAdd
{
var propSignature = member.ToDisplayString(_formatNoVariance);

var prop = typeDef.Properties.FirstOrDefault(x => x.Member == propSignature);
var prop = Array.Find(typeDef.Properties, x => x.Member == propSignature);
if (prop != null)
{
_ = MissingProperties.Remove(prop);
Expand All @@ -255,7 +255,7 @@ and not MethodKind.EventAdd
fieldSignature = "const " + t.ToDisplayString(_enumType) + " " + fieldSignature;
}

var field = typeDef.Fields.FirstOrDefault(x => x.Member == fieldSignature);
var field = Array.Find(typeDef.Fields, x => x.Member == fieldSignature);
if (field != null)
{
_ = MissingFields.Remove(field);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ public KeyValuePair[] Keys
}
}

[DebuggerDisplay("{value.ToString(),nq}", Name = "{key}", Type = "JsonValue({Type})")]
[DebuggerDisplay("{_value,nq}", Name = "{_key}")]
public sealed class KeyValuePair
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ public int AsInteger
/// Gets this value as a system.DateTime.
/// </summary>
/// <value>This value as a system.DateTime.</value>
public DateTime? AsDateTime => IsString && DateTime.TryParse((string?)_reference ?? string.Empty, out var value)
public DateTime? AsDateTime => IsString && DateTime.TryParse((string?)_reference ?? string.Empty, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out var value)
? value
: null;

Expand Down
2 changes: 1 addition & 1 deletion src/Generators/Microsoft.Gen.Logging/Parsing/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ public IReadOnlyList<LoggingType> GetLogTypes(IEnumerable<TypeDeclarationSyntax>
if (keepMethod &&
string.IsNullOrWhiteSpace(lm.Message) &&
!lm.EventId.HasValue &&
lm.Parameters.All(x => x.IsLogger || x.IsLogLevel))
lm.Parameters.TrueForAll(static x => x.IsLogger || x.IsLogLevel))
{
if (!_failedMethod)
{
Expand Down
4 changes: 1 addition & 3 deletions src/Generators/Shared/DiagDescriptorsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ protected static DiagnosticDescriptor Make(
category,
defaultSeverity,
isEnabledByDefault,
null,
string.Format(DiagnosticIds.UrlFormat, id),
Array.Empty<string>());
helpLinkUri: string.Format(DiagnosticIds.UrlFormat, id));
#pragma warning restore CS0436 // Type conflicts with imported type
#pragma warning restore CA1863 // Use 'CompositeFormat'
#pragma warning restore CA1305 // Specify IFormatProvider
Expand Down
21 changes: 18 additions & 3 deletions src/Libraries/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -2968,7 +2968,7 @@ dotnet_diagnostic.S1067.severity = suggestion
# Title : Methods should not have too many parameters
# Category : Major Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-107
dotnet_diagnostic.S107.severity = suggestion
dotnet_diagnostic.S107.severity = none

# Title : URIs should not be hardcoded
# Category : Minor Code Smell
Expand Down Expand Up @@ -4001,7 +4001,7 @@ dotnet_diagnostic.S3246.severity = warning
# Title : Duplicate casts should not be made
# Category : Minor Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-3247
dotnet_diagnostic.S3247.severity = warning
dotnet_diagnostic.S3247.severity = none

# Title : Classes directly extending "object" should not call "base" in "GetHashCode" or "Equals"
# Category : Major Bug
Expand Down Expand Up @@ -5121,7 +5121,7 @@ dotnet_diagnostic.S6585.severity = none
# Title : Use the "UnixEpoch" field instead of creating "DateTime" instances that point to the beginning of the Unix epoch
# Category : Minor Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6588
dotnet_diagnostic.S6588.severity = warning
dotnet_diagnostic.S6588.severity = none

# Title : "Find" method should be used instead of the "FirstOrDefault" extension
# Category : Minor Code Smell
Expand Down Expand Up @@ -5183,6 +5183,21 @@ dotnet_diagnostic.S6618.severity = warning
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6640
dotnet_diagnostic.S6640.severity = warning

# Title : Generic logger injection should match enclosing type
# Category : Minor Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6672
dotnet_diagnostic.S6672.severity = none

# Title : Awaitable method should be used
# Category : Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6966
dotnet_diagnostic.S6966.severity = none

# Title : ModelState.IsValid should be called in controller actions
# Category : Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-6967
dotnet_diagnostic.S6967.severity = none

# Title : Literal suffixes should be upper case
# Category : Minor Code Smell
# Help Link: https://rules.sonarsource.com/csharp/RSPEC-818
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ await logger.ExecuteWithCatchAsync(
if (storageRootDir is not null)
{
string storageRootPath = storageRootDir.FullName;
logger.LogInformation("Storage root path: {storageRootPath}", storageRootPath);
logger.LogInformation("Storage root path: {StorageRootPath}", storageRootPath);
logger.LogInformation("Deleting expired cache entries...");

cacheProvider = new DiskBasedResponseCacheProvider(storageRootPath);
Expand All @@ -46,7 +46,7 @@ await logger.ExecuteWithCatchAsync(
}
else if (endpointUri is not null)
{
logger.LogInformation("Azure Storage endpoint: {endpointUri}", endpointUri);
logger.LogInformation("Azure Storage endpoint: {EndpointUri}", endpointUri);

var fsClient = new DataLakeDirectoryClient(endpointUri, new DefaultAzureCredential());
cacheProvider = new AzureStorageResponseCacheProvider(fsClient);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ await logger.ExecuteWithCatchAsync(
if (storageRootDir is not null)
{
string storageRootPath = storageRootDir.FullName;
logger.LogInformation("Storage root path: {storageRootPath}", storageRootPath);
logger.LogInformation("Storage root path: {StorageRootPath}", storageRootPath);

resultStore = new DiskBasedResultStore(storageRootPath);

telemetryProperties[PropertyNames.StorageType] = PropertyValues.StorageTypeDisk;
}
else if (endpointUri is not null)
{
logger.LogInformation("Azure Storage endpoint: {endpointUri}", endpointUri);
logger.LogInformation("Azure Storage endpoint: {EndpointUri}", endpointUri);

var fsClient = new DataLakeDirectoryClient(endpointUri, new DefaultAzureCredential());
resultStore = new AzureStorageResultStore(fsClient);
Expand All @@ -72,7 +72,7 @@ await resultStore.DeleteResultsAsync(
else
{
logger.LogInformation(
"Deleting all results except the {lastN} most recent ones...",
"Deleting all results except the {LastN} most recent ones...",
lastN);

HashSet<string> toPreserve = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,15 @@ await logger.ExecuteWithCatchAsync(
if (storageRootDir is not null)
{
string storageRootPath = storageRootDir.FullName;
logger.LogInformation("Storage root path: {storageRootPath}", storageRootPath);
logger.LogInformation("Storage root path: {StorageRootPath}", storageRootPath);

resultStore = new DiskBasedResultStore(storageRootPath);

telemetryProperties[PropertyNames.StorageType] = PropertyValues.StorageTypeDisk;
}
else if (endpointUri is not null)
{
logger.LogInformation("Azure Storage endpoint: {endpointUri}", endpointUri);
logger.LogInformation("Azure Storage endpoint: {EndpointUri}", endpointUri);

var fsClient = new DataLakeDirectoryClient(endpointUri, new DefaultAzureCredential());
resultStore = new AzureStorageResultStore(fsClient);
Expand Down Expand Up @@ -107,7 +107,7 @@ await logger.ExecuteWithCatchAsync(
results.Add(result);

logger.LogInformation(
"Execution: {executionName} Scenario: {scenarioName} Iteration: {iterationName}",
"Execution: {ExecutionName} Scenario: {ScenarioName} Iteration: {IterationName}",
result.ExecutionName,
result.ScenarioName,
result.IterationName);
Expand All @@ -131,7 +131,7 @@ await logger.ExecuteWithCatchAsync(
};

await reportWriter.WriteReportAsync(results, cancellationToken).ConfigureAwait(false);
logger.LogInformation("Report: {outputFilePath} [{format}]", outputFilePath, format);
logger.LogInformation("Report: {OutputFilePath} [{Format}]", outputFilePath, format);

// See the following issues for reasoning behind this check. We want to avoid opening the
// report if this process is running as a service or in a CI pipeline.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Linq;

namespace Microsoft.Extensions.AI.Evaluation.Console.Telemetry;

Expand Down Expand Up @@ -54,7 +53,7 @@ public static bool IsCIEnvironment()

foreach (string[] variables in _mustNotBeNullCIVariables)
{
if (variables.All(variable => !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(variable))))
if (Array.TrueForAll(variables, static variable => !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(variable))))
{
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ internal void ReportEvent(
}
catch (Exception ex)
{
_logger.LogWarning(ex, $"Failed to report event '{eventName}' in telemetry.");
_logger.LogWarning(ex, "Failed to report event '{EventName}' in telemetry.", eventName);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,6 @@ async ValueTask<EvaluationResult> EvaluateAsync(IEvaluator e)
}

IEnumerable<ValueTask<EvaluationResult>> concurrentTasks = _evaluators.Select(EvaluateAsync);
return concurrentTasks.StreamResultsAsync(preserveOrder: false, cancellationToken);
return concurrentTasks.StreamResultsAsync(cancellationToken: cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ static IEnumerable<ChatMessageAnnotation> ConvertAnnotations(IEnumerable<AIConte
}
else
{
yield return OpenAIChatModelFactory.ChatMessageAnnotation(0, 0, citation.Url, citation.Title);
yield return OpenAIChatModelFactory.ChatMessageAnnotation(webResourceUri: citation.Url, webResourceTitle: citation.Title);
}
}
}
Expand Down Expand Up @@ -149,8 +149,10 @@ public static async IAsyncEnumerable<StreamingChatCompletionUpdate> AsOpenAIStre

var toolCallUpdates = update.Contents.OfType<FunctionCallContent>().Select((fcc, index) =>
OpenAIChatModelFactory.StreamingChatToolCallUpdate(
index, fcc.CallId, ChatToolCallKind.Function, fcc.Name,
new(JsonSerializer.SerializeToUtf8Bytes(fcc.Arguments, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(IDictionary<string, object?>))))))
index,
fcc.CallId,
functionName: fcc.Name,
functionArgumentsUpdate: new(JsonSerializer.SerializeToUtf8Bytes(fcc.Arguments, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(IDictionary<string, object?>))))))
.ToList();

yield return OpenAIChatModelFactory.StreamingChatCompletionUpdate(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -751,7 +751,7 @@ private static (Dictionary<string, AITool>? ToolMap, bool AnyRequireApproval) Cr
/// Gets whether <paramref name="messages"/> contains any <see cref="FunctionApprovalRequestContent"/> or <see cref="FunctionApprovalResponseContent"/> instances.
/// </summary>
private static bool HasAnyApprovalContent(List<ChatMessage> messages) =>
messages.Any(static m => m.Contents.Any(static c => c is FunctionApprovalRequestContent or FunctionApprovalResponseContent));
messages.Exists(static m => m.Contents.Any(static c => c is FunctionApprovalRequestContent or FunctionApprovalResponseContent));

/// <summary>Copies any <see cref="FunctionCallContent"/> from <paramref name="messages"/> to <paramref name="functionCalls"/>.</summary>
private static bool CopyFunctionCalls(
Expand Down Expand Up @@ -925,7 +925,7 @@ select ProcessFunctionCallAsync(
messages, options, toolMap, functionCallContents,
iteration, callIndex, captureExceptions: true, isStreaming, cancellationToken)));

shouldTerminate = results.Any(r => r.Terminate);
shouldTerminate = results.Exists(static r => r.Terminate);
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<MinCodeCoverage>75</MinCodeCoverage>
<MinMutationScore>75</MinMutationScore>
<!-- Convert abstract class into interface -->
<NoWarn>$(NoWarn);S1694</NoWarn>
<NoWarn>$(NoWarn);S1694;S2368</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ private async Task<string> ConvertToMarkdownAsync(DataContent dataContent, Cance
await using (transport.ConfigureAwait(false))
{
// Create MCP client
McpClient client = await McpClient.CreateAsync(transport, _options, loggerFactory: null, cancellationToken).ConfigureAwait(false);
McpClient client = await McpClient.CreateAsync(transport, _options, cancellationToken: cancellationToken).ConfigureAwait(false);

await using (client.ConfigureAwait(false))
{
Expand Down
Loading
Loading