Skip to content

Commit 9b32946

Browse files
authored
Replace Where+FirstOrDefault call with FirstOrDefault. Also few cleanups (typos, removed unused usings, changing some methods to private) (#9096)
1 parent 008b546 commit 9b32946

File tree

7 files changed

+31
-39
lines changed

7 files changed

+31
-39
lines changed

src/WebJobs.Script.Grpc/Channel/GrpcWorkerChannelFactory.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
using System;
55
using System.Collections.Generic;
66
using System.Linq;
7-
using System.Reactive.Linq;
87
using Microsoft.Azure.WebJobs.Script.Config;
98
using Microsoft.Azure.WebJobs.Script.Diagnostics;
109
using Microsoft.Azure.WebJobs.Script.Eventing;
@@ -44,10 +43,10 @@ public GrpcWorkerChannelFactory(IScriptEventManager eventManager, IEnvironment e
4443

4544
public IRpcWorkerChannel Create(string scriptRootPath, string runtime, IMetricsLogger metricsLogger, int attemptCount, IEnumerable<RpcWorkerConfig> workerConfigs)
4645
{
47-
var languageWorkerConfig = workerConfigs.Where(c => c.Description.Language.Equals(runtime, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
46+
var languageWorkerConfig = workerConfigs.FirstOrDefault(c => c.Description.Language.Equals(runtime, StringComparison.OrdinalIgnoreCase));
4847
if (languageWorkerConfig == null)
4948
{
50-
throw new InvalidOperationException($"WorkerCofig for runtime: {runtime} not found");
49+
throw new InvalidOperationException($"WorkerConfig for runtime: {runtime} not found");
5150
}
5251
string workerId = Guid.NewGuid().ToString();
5352
_eventManager.AddGrpcChannels(workerId); // prepare the inbound/outbound dedicated channels

src/WebJobs.Script/Description/FunctionGenerator.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public static Type Generate(string functionAssemblyName, string typeName, Collec
5353
continue;
5454
}
5555

56-
var retValue = function.Parameters.Where(x => x.Name == ScriptConstants.SystemReturnParameterName).FirstOrDefault();
56+
var retValue = function.Parameters.FirstOrDefault(x => x.Name == ScriptConstants.SystemReturnParameterName);
5757
var parameters = function.Parameters.Where(x => x != retValue).ToArray();
5858

5959
MethodBuilder methodBuilder = tb.DefineMethod(function.Name, MethodAttributes.Public | MethodAttributes.Static);

src/WebJobs.Script/Utility.cs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ public static class Utility
3737
{
3838
// Prefix that uniquely identifies our assemblies
3939
// i.e.: "f-<functionname>"
40-
public const string AssemblyPrefix = "f-";
41-
public const string AssemblySeparator = "__";
40+
private const string AssemblyPrefix = "f-";
41+
private const string AssemblySeparator = "__";
4242
private const string BlobServiceDomain = "blob";
4343
private const string SasVersionQueryParam = "sv";
4444

@@ -153,7 +153,7 @@ internal static async Task InvokeWithRetriesAsync(Func<Task> action, int maxRetr
153153
/// </summary>
154154
/// <param name="timeoutSeconds">The maximum number of seconds to delay.</param>
155155
/// <param name="pollingIntervalMilliseconds">The polling interval.</param>
156-
/// <param name="condition">The condition to check</param>
156+
/// <param name="condition">The condition to check.</param>
157157
/// <returns>A Task representing the delay.</returns>
158158
internal static Task<bool> DelayAsync(int timeoutSeconds, int pollingIntervalMilliseconds, Func<bool> condition)
159159
{
@@ -166,7 +166,7 @@ internal static Task<bool> DelayAsync(int timeoutSeconds, int pollingIntervalMil
166166
/// </summary>
167167
/// <param name="timeoutSeconds">The maximum number of seconds to delay.</param>
168168
/// <param name="pollingIntervalMilliseconds">The polling interval.</param>
169-
/// <param name="condition">The async condition to check</param>
169+
/// <param name="condition">The async condition to check.</param>
170170
/// <returns>A Task representing the delay.</returns>
171171
internal static Task<bool> DelayAsync(int timeoutSeconds, int pollingIntervalMilliseconds, Func<Task<bool>> condition, CancellationToken cancellationToken)
172172
{
@@ -279,7 +279,7 @@ public static bool IsValidUserType(Type type)
279279

280280
public static IReadOnlyDictionary<string, string> ToStringValues(this IReadOnlyDictionary<string, object> data)
281281
{
282-
return data.ToDictionary(p => p.Key, p => p.Value != null ? p.Value.ToString() : null, StringComparer.OrdinalIgnoreCase);
282+
return data.ToDictionary(p => p.Key, p => p.Value?.ToString(), StringComparer.OrdinalIgnoreCase);
283283
}
284284

285285
public static string GetValueOrNull(this StringDictionary dictionary, string key)
@@ -365,7 +365,7 @@ public static string FlattenException(Exception ex, Func<string, string> sourceF
365365

366366
/// <summary>
367367
/// Applies any additional binding data from the input value to the specified binding data.
368-
/// This binding data then becomes available to the binding process (in the case of late bound bindings)
368+
/// This binding data then becomes available to the binding process (in the case of late bound bindings).
369369
/// </summary>
370370
internal static void ApplyBindingData(object value, Dictionary<string, object> bindingData)
371371
{
@@ -441,9 +441,9 @@ public static string ToLowerFirstCharacter(string input)
441441
}
442442

443443
/// <summary>
444-
/// Checks if a given string has a UTF8 BOM
444+
/// Checks if a given string has a UTF8 BOM.
445445
/// </summary>
446-
/// <param name="input">The string to be evalutated</param>
446+
/// <param name="input">The string to be evaluated.</param>
447447
/// <returns>True if the string begins with a UTF8 BOM; Otherwise, false.</returns>
448448
public static bool HasUtf8ByteOrderMark(string input)
449449
=> input != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(input, UTF8ByteOrderMark, CompareOptions.Ordinal);
@@ -649,11 +649,9 @@ internal static bool IsSingleLanguage(IEnumerable<FunctionMetadata> functions, s
649649

650650
internal static string GetWorkerRuntime(IEnumerable<FunctionMetadata> functions, IEnvironment environment = null)
651651
{
652-
string workerRuntime = null;
653-
654652
if (environment != null)
655653
{
656-
workerRuntime = environment.GetEnvironmentVariable(EnvironmentSettingNames.FunctionWorkerRuntime);
654+
var workerRuntime = environment.GetEnvironmentVariable(EnvironmentSettingNames.FunctionWorkerRuntime);
657655

658656
if (!string.IsNullOrEmpty(workerRuntime))
659657
{
@@ -746,7 +744,7 @@ internal static IEnumerable<FunctionMetadata> GetValidFunctions(IEnumerable<Func
746744
// No valid functions
747745
return null;
748746
}
749-
return indexedFunctions.Where(m => functionDescriptors.Select(fd => fd.Metadata.Name).Contains(m.Name) == true);
747+
return indexedFunctions.Where(m => functionDescriptors.Select(fd => fd.Metadata.Name).Contains(m.Name));
750748
}
751749

752750
public static bool CheckAppOffline(string scriptPath)
@@ -857,10 +855,10 @@ public static bool IsHttporManualTrigger(string triggerType)
857855
}
858856

859857
/// <summary>
860-
/// Computes a stable non-cryptographic hash
858+
/// Computes a stable non-cryptographic hash.
861859
/// </summary>
862-
/// <param name="value">The string to use for computation</param>
863-
/// <returns>A stable, non-cryptographic, hash</returns>
860+
/// <param name="value">The string to use for computation.</param>
861+
/// <returns>A stable, non-cryptographic, hash.</returns>
864862
internal static int GetStableHash(string value)
865863
{
866864
if (value == null)
@@ -933,7 +931,7 @@ public static bool CanWorkerIndex(IEnumerable<RpcWorkerConfig> workerConfigs, IE
933931
&& !environment.IsMultiLanguageRuntimeEnvironment())
934932
{
935933
var workerRuntime = environment.GetEnvironmentVariable(EnvironmentSettingNames.FunctionWorkerRuntime);
936-
var workerConfig = workerConfigs.Where(c => c.Description != null && c.Description.Language != null && c.Description.Language.Equals(workerRuntime, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
934+
var workerConfig = workerConfigs.FirstOrDefault(c => c.Description?.Language != null && c.Description.Language.Equals(workerRuntime, StringComparison.InvariantCultureIgnoreCase));
937935

938936
// if feature flag is enabled and workerConfig.WorkerIndexing == true, then return true
939937
if (workerConfig != null

src/WebJobs.Script/Workers/Rpc/FunctionRegistration/RpcFunctionInvocationDispatcher.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,8 @@ private async Task<int> GetMaxProcessCount()
117117

118118
if (!string.IsNullOrEmpty(_workerRuntime))
119119
{
120-
var workerConfig = _workerConfigs.Where(c => c.Description.Language.Equals(_workerRuntime, StringComparison.InvariantCultureIgnoreCase))
121-
.FirstOrDefault();
120+
var workerConfig = _workerConfigs
121+
.FirstOrDefault(c => c.Description.Language.Equals(_workerRuntime, StringComparison.InvariantCultureIgnoreCase));
122122
if (workerConfig != null)
123123
{
124124
return workerConfig.CountOptions.ProcessCount;
@@ -261,7 +261,7 @@ public async Task InitializeAsync(IEnumerable<FunctionMetadata> functions, Cance
261261
return;
262262
}
263263

264-
var workerConfig = _workerConfigs.Where(c => c.Description.Language.Equals(_workerRuntime, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
264+
var workerConfig = _workerConfigs.FirstOrDefault(c => c.Description.Language.Equals(_workerRuntime, StringComparison.InvariantCultureIgnoreCase));
265265

266266
// For other OOP workers, workerconfigs are present inside "workers" folder of host bin directory and is used to populate "_workerConfigs".
267267
// For dotnet-isolated _workerConfigs is populated by reading workerconfig.json from the deployed payload(customer function app code).
@@ -271,7 +271,7 @@ public async Task InitializeAsync(IEnumerable<FunctionMetadata> functions, Cance
271271

272272
// We are skipping this check for multi-language environments because they use multiple workers and thus doesn't honor 'FUNCTIONS_WORKER_RUNTIME'
273273
// Also, skip if dotnet-isolated app without payload as it is a valid case to exist.
274-
if ((workerConfig == null && (functions == null || functions.Count() == 0))
274+
if (workerConfig == null && (functions == null || !functions.Any())
275275
&& !_environment.IsMultiLanguageRuntimeEnvironment()
276276
&& !isDotNetIsolatedAppWithoutPayload)
277277
{
@@ -283,7 +283,7 @@ public async Task InitializeAsync(IEnumerable<FunctionMetadata> functions, Cance
283283
throw new InvalidOperationException($"WorkerConfig for runtime: {_workerRuntime} not found");
284284
}
285285

286-
if (functions == null || functions.Count() == 0)
286+
if (functions == null || !functions.Any())
287287
{
288288
// do not initialize function dispatcher if there are no functions, unless the worker is indexing
289289
_logger.LogDebug($"{nameof(RpcFunctionInvocationDispatcher)} received no functions");
@@ -443,7 +443,7 @@ internal async Task<IEnumerable<IRpcWorkerChannel>> GetInitializedWorkerChannels
443443
return initializedWorkers;
444444
}
445445

446-
public async void WorkerError(WorkerErrorEvent workerError)
446+
private async void WorkerError(WorkerErrorEvent workerError)
447447
{
448448
if (_disposing || _disposed)
449449
{
@@ -473,7 +473,7 @@ public async void WorkerError(WorkerErrorEvent workerError)
473473
}
474474
}
475475

476-
public async void WorkerRestart(WorkerRestartEvent workerRestart)
476+
private async void WorkerRestart(WorkerRestartEvent workerRestart)
477477
{
478478
if (_disposing || _disposed)
479479
{
@@ -582,7 +582,7 @@ private async Task StartWorkerChannel(string runtime)
582582
}
583583
}
584584
}
585-
else if (_jobHostLanguageWorkerChannelManager.GetChannels().Count() == 0)
585+
else if (!_jobHostLanguageWorkerChannelManager.GetChannels().Any())
586586
{
587587
_logger.LogError("Exceeded language worker restart retry count for runtime:{runtime}. Shutting down and proactively recycling the Functions Host to recover", runtime);
588588
_applicationLifetime.StopApplication();

test/WebJobs.Script.Tests/UtilityTests.cs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,18 @@
33

44
using System;
55
using System.Collections.Generic;
6-
using System.Diagnostics;
76
using System.Dynamic;
87
using System.Globalization;
98
using System.IO;
109
using System.Linq;
11-
using System.Reflection;
1210
using System.Text;
1311
using System.Threading;
1412
using System.Threading.Tasks;
15-
using Microsoft.Azure.WebJobs.Host.Scale;
1613
using Microsoft.Azure.WebJobs.Logging;
17-
using Microsoft.Azure.WebJobs.Script.Config;
1814
using Microsoft.Azure.WebJobs.Script.Description;
1915
using Microsoft.Azure.WebJobs.Script.Diagnostics;
2016
using Microsoft.Azure.WebJobs.Script.Models;
2117
using Microsoft.Azure.WebJobs.Script.Workers.Rpc;
22-
using Microsoft.CodeAnalysis.CSharp.Syntax;
2318
using Microsoft.Extensions.Logging;
2419
using Microsoft.Extensions.Options;
2520
using Microsoft.WebJobs.Script.Tests;
@@ -950,7 +945,7 @@ public void TryReadAsBool_ReturnsExpectedBoolValue(object value, bool expectedVa
950945

951946
private static void VerifyLogLevel(IList<LogMessage> allLogs, string msg, LogLevel expectedLevel)
952947
{
953-
var message = allLogs.Where(l => l.FormattedMessage.Contains(msg)).FirstOrDefault();
948+
var message = allLogs.FirstOrDefault(l => l.FormattedMessage.Contains(msg));
954949
Assert.NotNull(message);
955950
Assert.Equal(expectedLevel, message.Level);
956951
}

test/WebJobs.Script.Tests/Workers/Rpc/RpcWorkerConfigFactoryTests.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ public void JavaPath_FromEnvVars()
107107
var testLogger = new TestLogger("test");
108108
var configFactory = new RpcWorkerConfigFactory(config, testLogger, _testSysRuntimeInfo, _testEnvironment, new TestMetricsLogger(), _testWorkerProfileManager);
109109
var workerConfigs = configFactory.GetConfigs();
110-
var javaPath = workerConfigs.Where(c => c.Description.Language.Equals("java", StringComparison.OrdinalIgnoreCase)).FirstOrDefault().Description.DefaultExecutablePath;
110+
var javaPath = workerConfigs.FirstOrDefault(c => c.Description.Language.Equals("java", StringComparison.OrdinalIgnoreCase)).Description.DefaultExecutablePath;
111111
Assert.DoesNotContain(@"%JAVA_HOME%", javaPath);
112112
Assert.Contains(@"/bin/java", javaPath);
113113
}
@@ -128,8 +128,8 @@ public void DefaultWorkerConfigs_Overrides_DefaultWorkerRuntimeVersion_AppSettin
128128
{
129129
var configFactory = new RpcWorkerConfigFactory(config, testLogger, _testSysRuntimeInfo, _testEnvironment, new TestMetricsLogger(), _testWorkerProfileManager);
130130
var workerConfigs = configFactory.GetConfigs();
131-
var pythonWorkerConfig = workerConfigs.Where(w => w.Description.Language.Equals("python", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
132-
var powershellWorkerConfig = workerConfigs.Where(w => w.Description.Language.Equals("powershell", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
131+
var pythonWorkerConfig = workerConfigs.FirstOrDefault(w => w.Description.Language.Equals("python", StringComparison.OrdinalIgnoreCase));
132+
var powershellWorkerConfig = workerConfigs.FirstOrDefault(w => w.Description.Language.Equals("powershell", StringComparison.OrdinalIgnoreCase));
133133
Assert.Equal(4, workerConfigs.Count);
134134
Assert.NotNull(pythonWorkerConfig);
135135
Assert.NotNull(powershellWorkerConfig);
@@ -150,7 +150,7 @@ public void DefaultWorkerConfigs_Overrides_VersionAppSetting()
150150
var testLogger = new TestLogger("test");
151151
var configFactory = new RpcWorkerConfigFactory(config, testLogger, _testSysRuntimeInfo, testEnvironment, new TestMetricsLogger(), _testWorkerProfileManager);
152152
var workerConfigs = configFactory.GetConfigs();
153-
var powershellWorkerConfig = workerConfigs.Where(w => w.Description.Language.Equals("powershell", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
153+
var powershellWorkerConfig = workerConfigs.FirstOrDefault(w => w.Description.Language.Equals("powershell", StringComparison.OrdinalIgnoreCase));
154154
Assert.Equal(1, workerConfigs.Count);
155155
Assert.NotNull(powershellWorkerConfig);
156156
Assert.Equal("7.2", powershellWorkerConfig.Description.DefaultRuntimeVersion);

test/WebJobs.Script.Tests/Workers/Rpc/RpcWorkerConfigTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ public void ReadWorkerProviderFromConfig_InvalidConfigFile()
153153
var workerConfigs = TestReadWorkerProviderFromConfig(configs, testLogger, testMetricsLogger);
154154
AreRequiredMetricsEmitted(testMetricsLogger);
155155
var logs = testLogger.GetLogMessages();
156-
var errorLog = logs.Where(log => log.Level == LogLevel.Error).FirstOrDefault();
156+
var errorLog = logs.FirstOrDefault(log => log.Level == LogLevel.Error);
157157
Assert.NotNull(errorLog);
158158
Assert.NotNull(errorLog.Exception);
159159
Assert.True(errorLog.FormattedMessage.Contains("Failed to initialize"));

0 commit comments

Comments
 (0)