Skip to content

Commit 228b76c

Browse files
committed
Update analyzers for .NET 10 SDK
1 parent 8c6b12e commit 228b76c

File tree

41 files changed

+358
-251
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+358
-251
lines changed

dotnet/Directory.Build.props

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
<!-- Default properties inherited by all projects. Projects can override. -->
44
<RunAnalyzersDuringBuild>true</RunAnalyzersDuringBuild>
55
<EnableNETAnalyzers>true</EnableNETAnalyzers>
6-
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
7-
<AnalysisLevel>latest</AnalysisLevel>
6+
<AnalysisLevel>10.0-all</AnalysisLevel>
87
<GenerateDocumentationFile>true</GenerateDocumentationFile>
98
<LangVersion>latest</LangVersion>
109
<Nullable>enable</Nullable>

dotnet/samples/.editorconfig

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Suppressing errors for Sample projects under dotnet/samples folder
22
[*.cs]
33
dotnet_diagnostic.CA1716.severity = none # Add summary to documentation comment.
4+
dotnet_diagnostic.CA1873.severity = none # Evaluation of logging arguments may be expensive
45
dotnet_diagnostic.CA2000.severity = none # Call System.IDisposable.Dispose on object before all references to it are out of scope
56
dotnet_diagnostic.CA2007.severity = none # Do not directly await a Task
67

dotnet/samples/GettingStarted/AgentProviders/Agent_With_GoogleGemini/GeminiChatClient.cs

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public async Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messag
4949
GenerateContentResponse generateResult = await this._models.GenerateContentAsync(modelId!, contents, config).ConfigureAwait(false);
5050

5151
// Create the response.
52-
ChatResponse chatResponse = new(new ChatMessage(ChatRole.Assistant, new List<AIContent>()))
52+
ChatResponse chatResponse = new(new ChatMessage(ChatRole.Assistant, []))
5353
{
5454
CreatedAt = generateResult.CreateTime is { } dt ? new DateTimeOffset(dt) : null,
5555
ModelId = !string.IsNullOrWhiteSpace(generateResult.ModelVersion) ? generateResult.ModelVersion : modelId,
@@ -82,7 +82,7 @@ public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnu
8282
await foreach (GenerateContentResponse generateResult in this._models.GenerateContentStreamAsync(modelId!, contents, config).WithCancellation(cancellationToken).ConfigureAwait(false))
8383
{
8484
// Create a response update for each result in the stream.
85-
ChatResponseUpdate responseUpdate = new(ChatRole.Assistant, new List<AIContent>())
85+
ChatResponseUpdate responseUpdate = new(ChatRole.Assistant, [])
8686
{
8787
CreatedAt = generateResult.CreateTime is { } dt ? new DateTimeOffset(dt) : null,
8888
ModelId = !string.IsNullOrWhiteSpace(generateResult.ModelVersion) ? generateResult.ModelVersion : modelId,
@@ -148,7 +148,7 @@ void IDisposable.Dispose() { /* nop */ }
148148
// create the request instance, allowing the caller to populate it with GenAI-specific options. Otherwise, create
149149
// a new instance directly.
150150
string? model = this._defaultModelId;
151-
List<Content> contents = new();
151+
List<Content> contents = [];
152152
GenerateContentConfig config = options?.RawRepresentationFactory?.Invoke(this) as GenerateContentConfig ?? new();
153153

154154
if (options is not null)
@@ -160,7 +160,7 @@ void IDisposable.Dispose() { /* nop */ }
160160

161161
if (options.Instructions is { } instructions)
162162
{
163-
((config.SystemInstruction ??= new()).Parts ??= new()).Add(new() { Text = instructions });
163+
((config.SystemInstruction ??= new()).Parts ??= []).Add(new() { Text = instructions });
164164
}
165165

166166
if (options.MaxOutputTokens is { } maxOutputTokens)
@@ -185,7 +185,7 @@ void IDisposable.Dispose() { /* nop */ }
185185

186186
if (options.StopSequences is { } stopSequences)
187187
{
188-
(config.StopSequences ??= new()).AddRange(stopSequences);
188+
(config.StopSequences ??= []).AddRange(stopSequences);
189189
}
190190

191191
if (options.Temperature is { } temperature)
@@ -213,7 +213,7 @@ void IDisposable.Dispose() { /* nop */ }
213213
switch (tool)
214214
{
215215
case AIFunctionDeclaration af:
216-
functionDeclarations ??= new();
216+
functionDeclarations ??= [];
217217
functionDeclarations.Add(new()
218218
{
219219
Name = af.Name,
@@ -223,15 +223,15 @@ void IDisposable.Dispose() { /* nop */ }
223223
break;
224224

225225
case HostedCodeInterpreterTool:
226-
(config.Tools ??= new()).Add(new() { CodeExecution = new() });
226+
(config.Tools ??= []).Add(new() { CodeExecution = new() });
227227
break;
228228

229229
case HostedFileSearchTool:
230-
(config.Tools ??= new()).Add(new() { Retrieval = new() });
230+
(config.Tools ??= []).Add(new() { Retrieval = new() });
231231
break;
232232

233233
case HostedWebSearchTool:
234-
(config.Tools ??= new()).Add(new() { GoogleSearch = new() });
234+
(config.Tools ??= []).Add(new() { GoogleSearch = new() });
235235
break;
236236
}
237237
}
@@ -240,8 +240,8 @@ void IDisposable.Dispose() { /* nop */ }
240240
if (functionDeclarations is { Count: > 0 })
241241
{
242242
Tool functionTools = new();
243-
(functionTools.FunctionDeclarations ??= new()).AddRange(functionDeclarations);
244-
(config.Tools ??= new()).Add(functionTools);
243+
(functionTools.FunctionDeclarations ??= []).AddRange(functionDeclarations);
244+
(config.Tools ??= []).Add(functionTools);
245245
}
246246

247247
// Transfer over the tool mode if there are any tools.
@@ -261,7 +261,7 @@ void IDisposable.Dispose() { /* nop */ }
261261
config.ToolConfig = new() { FunctionCallingConfig = new() { Mode = FunctionCallingConfigMode.ANY } };
262262
if (required.RequiredFunctionName is not null)
263263
{
264-
((config.ToolConfig.FunctionCallingConfig ??= new()).AllowedFunctionNames ??= new()).Add(required.RequiredFunctionName);
264+
((config.ToolConfig.FunctionCallingConfig ??= new()).AllowedFunctionNames ??= []).Add(required.RequiredFunctionName);
265265
}
266266
break;
267267
}
@@ -287,14 +287,14 @@ void IDisposable.Dispose() { /* nop */ }
287287
string instruction = message.Text;
288288
if (!string.IsNullOrWhiteSpace(instruction))
289289
{
290-
((config.SystemInstruction ??= new()).Parts ??= new()).Add(new() { Text = instruction });
290+
((config.SystemInstruction ??= new()).Parts ??= []).Add(new() { Text = instruction });
291291
}
292292

293293
continue;
294294
}
295295

296296
Content content = new() { Role = message.Role == ChatRole.Assistant ? "model" : "user" };
297-
content.Parts ??= new();
297+
content.Parts ??= [];
298298
AddPartsForAIContents(ref callIdToFunctionNames, message.Contents, content.Parts);
299299

300300
contents.Add(content);
@@ -367,7 +367,7 @@ private static void AddPartsForAIContents(ref Dictionary<string, string>? callId
367367
break;
368368

369369
case FunctionCallContent functionCallContent:
370-
(callIdToFunctionNames ??= new())[functionCallContent.CallId] = functionCallContent.Name;
370+
(callIdToFunctionNames ??= [])[functionCallContent.CallId] = functionCallContent.Name;
371371
callIdToFunctionNames[""] = functionCallContent.Name; // track last function name in case calls don't have IDs
372372

373373
part = new()
@@ -480,22 +480,22 @@ private static void AddAIContentsForParts(List<Part> parts, IList<AIContent> con
480480
{
481481
foreach (var citation in citations)
482482
{
483-
textContent.Annotations = new List<AIAnnotation>()
484-
{
485-
new CitationAnnotation()
486-
{
487-
Title = citation.Title,
488-
Url = Uri.TryCreate(citation.Uri, UriKind.Absolute, out Uri? uri) ? uri : null,
489-
AnnotatedRegions = new List<AnnotatedRegion>()
490-
{
491-
new TextSpanAnnotatedRegion()
492-
{
493-
StartIndex = citation.StartIndex,
494-
EndIndex = citation.EndIndex,
495-
}
496-
},
497-
}
498-
};
483+
textContent.Annotations =
484+
[
485+
new CitationAnnotation()
486+
{
487+
Title = citation.Title,
488+
Url = Uri.TryCreate(citation.Uri, UriKind.Absolute, out Uri? uri) ? uri : null,
489+
AnnotatedRegions =
490+
[
491+
new TextSpanAnnotatedRegion()
492+
{
493+
StartIndex = citation.StartIndex,
494+
EndIndex = citation.EndIndex,
495+
}
496+
],
497+
}
498+
];
499499
}
500500
}
501501
}
@@ -551,7 +551,7 @@ void AddIfPresent(string key, int? value)
551551
{
552552
if (value is int i)
553553
{
554-
(details.AdditionalCounts ??= new())[key] = i;
554+
(details.AdditionalCounts ??= [])[key] = i;
555555
}
556556
}
557557
}

dotnet/src/Microsoft.Agents.AI.A2A/A2AAgent.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ private static AgentMessage CreateA2AMessage(A2AAgentThread typedThread, IEnumer
281281

282282
private static A2AContinuationToken? CreateContinuationToken(string taskId, TaskState state)
283283
{
284-
if (state == TaskState.Submitted || state == TaskState.Working)
284+
if (state is TaskState.Submitted or TaskState.Working)
285285
{
286286
return new A2AContinuationToken(taskId);
287287
}

dotnet/src/Microsoft.Agents.AI.AGUI/AGUIChatClient.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,11 @@ public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
220220
if (options?.Tools is { Count: > 0 })
221221
{
222222
input.Tools = options.Tools.AsAGUITools();
223-
this._logger.LogDebug("[AGUIChatClient] Tool count: {ToolCount}", options.Tools.Count);
223+
224+
if (this._logger.IsEnabled(LogLevel.Debug))
225+
{
226+
this._logger.LogDebug("[AGUIChatClient] Tool count: {ToolCount}", options.Tools.Count);
227+
}
224228
}
225229

226230
var clientToolSet = new HashSet<string>();

dotnet/src/Microsoft.Agents.AI.CopilotStudio/ActivityProcessor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public static async IAsyncEnumerable<ChatMessage> ProcessActivityAsync(IAsyncEnu
2727
{
2828
yield return CreateChatMessageFromActivity(activity, [new TextContent(activity.Text)]);
2929
}
30-
else
30+
else if (logger.IsEnabled(LogLevel.Warning))
3131
{
3232
logger.LogWarning("Unknown activity type '{ActivityType}' received.", activity.Type);
3333
}

dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosChatMessageStore.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ public static CosmosChatMessageStore CreateFromSerializedState(CosmosClient cosm
274274
throw new ArgumentException("Invalid serialized state", nameof(serializedStoreState));
275275
}
276276

277-
var state = JsonSerializer.Deserialize<StoreState>(serializedStoreState, jsonSerializerOptions);
277+
var state = serializedStoreState.Deserialize<StoreState>(jsonSerializerOptions);
278278
if (state?.ConversationIdentifier is not { } conversationId)
279279
{
280280
throw new ArgumentException("Invalid serialized state", nameof(serializedStoreState));

dotnet/src/Microsoft.Agents.AI.DevUI/DevUIMiddleware.cs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,11 @@ public async Task HandleRequestAsync(HttpContext context)
8383
context.Response.StatusCode = StatusCodes.Status301MovedPermanently;
8484
context.Response.Headers.Location = redirectUrl;
8585

86-
this._logger.LogDebug("Redirecting {OriginalPath} to {RedirectUrl}", NewlineRegex().Replace(path, ""), NewlineRegex().Replace(redirectUrl, ""));
86+
if (this._logger.IsEnabled(LogLevel.Debug))
87+
{
88+
this._logger.LogDebug("Redirecting {OriginalPath} to {RedirectUrl}", NewlineRegex().Replace(path, ""), NewlineRegex().Replace(redirectUrl, ""));
89+
}
90+
8791
return;
8892
}
8993

@@ -123,7 +127,11 @@ private async Task<bool> TryServeResourceAsync(HttpContext context, string resou
123127
{
124128
if (!this._resourceCache.TryGetValue(resourcePath.Replace('.', '/'), out var cacheEntry))
125129
{
126-
this._logger.LogDebug("Embedded resource not found: {ResourcePath}", resourcePath);
130+
if (this._logger.IsEnabled(LogLevel.Debug))
131+
{
132+
this._logger.LogDebug("Embedded resource not found: {ResourcePath}", resourcePath);
133+
}
134+
127135
return false;
128136
}
129137

@@ -133,7 +141,12 @@ private async Task<bool> TryServeResourceAsync(HttpContext context, string resou
133141
if (context.Request.Headers.IfNoneMatch == cacheEntry.ETag)
134142
{
135143
response.StatusCode = StatusCodes.Status304NotModified;
136-
this._logger.LogDebug("Resource not modified (304): {ResourcePath}", resourcePath);
144+
145+
if (this._logger.IsEnabled(LogLevel.Debug))
146+
{
147+
this._logger.LogDebug("Resource not modified (304): {ResourcePath}", resourcePath);
148+
}
149+
137150
return true;
138151
}
139152

@@ -161,12 +174,20 @@ private async Task<bool> TryServeResourceAsync(HttpContext context, string resou
161174

162175
await response.Body.WriteAsync(content, context.RequestAborted).ConfigureAwait(false);
163176

164-
this._logger.LogDebug("Served embedded resource: {ResourcePath} (compressed: {Compressed})", resourcePath, serveCompressed);
177+
if (this._logger.IsEnabled(LogLevel.Debug))
178+
{
179+
this._logger.LogDebug("Served embedded resource: {ResourcePath} (compressed: {Compressed})", resourcePath, serveCompressed);
180+
}
181+
165182
return true;
166183
}
167184
catch (Exception ex)
168185
{
169-
this._logger.LogError(ex, "Error serving embedded resource: {ResourcePath}", resourcePath);
186+
if (this._logger.IsEnabled(LogLevel.Error))
187+
{
188+
this._logger.LogError(ex, "Error serving embedded resource: {ResourcePath}", resourcePath);
189+
}
190+
170191
return false;
171192
}
172193
}

dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgent.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,10 @@ public override async Task<AgentRunResponse> RunAsync(
9898
responseFormat = chatClientOptions.ChatOptions?.ResponseFormat;
9999
}
100100

101-
RunRequest request = new([.. messages], responseFormat, enableToolCalls, enableToolNames);
102-
request.OrchestrationId = this._context.InstanceId;
101+
RunRequest request = new([.. messages], responseFormat, enableToolCalls, enableToolNames)
102+
{
103+
OrchestrationId = this._context.InstanceId
104+
};
103105

104106
try
105107
{

dotnet/src/Microsoft.Agents.AI.DurableTask/State/DurableAgentStateFunctionCallContent.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public static DurableAgentStateFunctionCallContent FromFunctionCallContent(Funct
4646
{
4747
return new DurableAgentStateFunctionCallContent()
4848
{
49-
Arguments = content.Arguments?.ToImmutableDictionary() ?? ImmutableDictionary<string, object?>.Empty,
49+
Arguments = content.Arguments?.ToDictionary() ?? [],
5050
CallId = content.CallId,
5151
Name = content.Name
5252
};

0 commit comments

Comments
 (0)