From 265f486f3b389a2915acb448b449af8a25d4aa40 Mon Sep 17 00:00:00 2001 From: Michael Yanni Date: Wed, 6 Mar 2024 12:18:01 -0800 Subject: [PATCH 1/7] Removed the explicit, in-code #nullable enable statements. Started fixing projects previously using these statements to now use enable. Got the Microsoft.DotNet.Cli.Utils.csproj building. More to come. --- .../BlockingMemoryStream.cs | 10 ++-- .../BuiltInCommand.cs | 8 +-- src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs | 26 +++++----- .../CommandResult.cs | 6 +-- .../DangerousFileDetector.cs | 8 +-- .../DependencyProvider.cs | 20 ++++---- .../DotDefaultPathCorrector.cs | 11 ++-- .../DotnetVersionFile.cs | 10 ++-- src/Cli/Microsoft.DotNet.Cli.Utils/Env.cs | 8 +-- .../EnvironmentProvider.cs | 29 ++++++----- .../ExponentialRetry.cs | 4 +- .../Extensions/ProcessExtensions.cs | 2 +- .../ForwardingAppImplementation.cs | 16 +++--- .../FrameworkDependencyFile.cs | 16 +++--- .../GracefulException.cs | 4 +- .../Microsoft.DotNet.Cli.Utils/ICommand.cs | 4 +- .../IEnvironmentProvider.cs | 10 ++-- .../Microsoft.DotNet.Cli.Utils/IReporter.cs | 2 - .../IWindowsRegistryEnvironmentPathEditor.cs | 2 +- .../MSBuildForwardingAppWithoutLogging.cs | 14 +++--- .../MSBuildProjectExtensions.cs | 10 ++-- .../MSBuildPropertyParser.cs | 3 -- .../Microsoft.DotNet.Cli.Utils.csproj | 1 + src/Cli/Microsoft.DotNet.Cli.Utils/Muxer.cs | 13 ++--- .../NativeMethods.cs | 2 +- .../Microsoft.DotNet.Cli.Utils/PathUtility.cs | 8 ++- .../ProcessReaper.cs | 2 - .../ProcessStartInfoExtensions.cs | 2 +- .../Microsoft.DotNet.Cli.Utils/Reporter.cs | 3 -- .../RuntimeEnvironment.cs | 24 ++++----- .../Sha256Hasher.cs | 2 - .../StreamForwarder.cs | 12 ++--- .../TelemetryEventEntry.cs | 50 +++++++++---------- .../ToolCommandName.cs | 2 +- .../TypoCorrection.cs | 3 -- .../UILanguageOverride.cs | 16 +++--- src/Cli/Microsoft.DotNet.Cli.Utils/Windows.cs | 2 +- .../WindowsRegistryEnvironmentPathEditor.cs | 8 +-- src/Cli/dotnet/CommonOptionsFactory.cs | 2 - .../NuGetSignatureVerificationEnabler.cs | 2 - .../dotnet/ReleasePropertyProjectLocator.cs | 1 - .../dotnet-new/DotnetCommandCallbacks.cs | 2 - .../CapabilityExpressionEvaluator.cs | 2 - .../MSBuildEvaluationResult.cs | 2 - .../MSBuildEvaluation/MSBuildEvaluator.cs | 2 - .../MultiTargetEvaluationResult.cs | 2 - .../MultipleProjectsEvaluationResult.cs | 2 - .../NonSDKStyleEvaluationResult.cs | 2 - .../ProjectCapabilityConstraint.cs | 2 - .../ProjectContextSymbolSource.cs | 2 - .../SDKStyleEvaluationResult.cs | 2 - .../commands/dotnet-new/NewCommandParser.cs | 2 - .../DotnetAddPostActionProcessor.cs | 2 - .../DotnetRestorePostActionProcessor.cs | 2 - .../DotnetSlnPostActionProcessor.cs | 2 - .../LaunchSettings/ILaunchSettingsProvider.cs | 2 - .../LaunchSettings/LaunchSettingsManager.cs | 2 - .../ProjectLaunchSettingsProvider.cs | 2 - .../dotnet-sdk/check/BundleOutputWriter.cs | 1 - .../dotnet-sdk/check/RuntimeOutputWriter.cs | 1 - .../dotnet-sdk/check/SdkOutputWriter.cs | 1 - .../dotnet-workload/WorkloadException.cs | 3 -- .../clean/WorkloadCleanCommand.cs | 2 - .../dotnet-workload/install/NullReporter.cs | 2 - src/Common/CliFolderPathCalculatorCore.cs | 6 --- src/Common/EnvironmentVariableNames.cs | 5 -- src/Common/PathUtilities.cs | 5 -- .../PublicAPI/net472/PublicAPI.Shipped.txt | 2 +- .../PublicAPI/net9.0/PublicAPI.Shipped.txt | 2 +- .../FXVersion.cs | 3 -- .../EnvironmentProvider.cs | 3 -- .../Microsoft.DotNet.NativeWrapper/Interop.cs | 10 ---- .../Microsoft.DotNet.NativeWrapper.csproj | 1 + .../NETCoreSdkResolverNativeWrapper.cs | 5 -- .../SdkResolutionResult.cs | 4 -- .../Microsoft.DotNet.SdkResolver.csproj | 1 + .../NETCoreSdkResolver.cs | 3 -- .../VSSettings.cs | 4 -- .../CachingWorkloadResolver.cs | 1 - src/Tasks/Common/Logger.cs | 4 -- src/Tasks/Common/Message.cs | 4 -- src/Tasks/Common/TaskBase.cs | 3 -- ...icrosoft.NET.Build.Extensions.Tasks.csproj | 1 + .../GivenAAllowEmptyTelemetry.cs | 2 - .../Mapping/AssemblyMapperTests.cs | 2 - .../Mapping/AssemblySetMapperTests.cs | 2 - .../Mapping/MemberMapperTests.cs | 2 - .../Mapping/NamespaceMapperTests.cs | 2 - .../Mapping/TypeMapperTests.cs | 2 - .../Runner/ApiCompatOptionsTests.cs | 3 -- .../Runner/ApiCompatWorkItemTests.cs | 3 -- .../TypoCorrectionTests.cs | 3 -- .../BodyBlockCSharpSyntaxRewriterTests.cs | 2 - .../CSharpSyntaxRewriterTestBase.cs | 2 - ...eLineStatementCSharpSyntaxRewriterTests.cs | 2 - ...ypeDeclarationCSharpSyntaxRewriterTests.cs | 2 - .../InMemoryLoggerProvider.cs | 3 -- .../TestLoggerFactory.cs | 3 -- .../Utilities/BufferedReporter.cs | 2 - .../XunitLoggerProvider.cs | 3 -- .../NuGetSignatureVerificationEnablerTests.cs | 2 - .../CapabilityExpressionEvaluationTests.cs | 2 - .../dotnet-new/DotnetAddPostActionTests.cs | 2 - .../DotnetRestorePostActionTests.cs | 2 - .../dotnet-new/DotnetSlnPostActionTests.cs | 2 - .../dotnet-new/SdkInfoProviderTests.cs | 2 - .../dotnet-new/WorkloadsInfoProviderTests.cs | 2 - 107 files changed, 176 insertions(+), 367 deletions(-) diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/BlockingMemoryStream.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/BlockingMemoryStream.cs index d19788a7b2ca..a4cf601adf96 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/BlockingMemoryStream.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/BlockingMemoryStream.cs @@ -29,7 +29,7 @@ public override int Read(byte[] buffer, int offset, int count) if (_remaining.Count == 0) { - byte[] tmp; + byte[]? tmp; if (!_buffers.TryTake(out tmp, Timeout.Infinite) || tmp.Length == 0) { return 0; @@ -40,13 +40,13 @@ public override int Read(byte[] buffer, int offset, int count) if (_remaining.Count <= count) { count = _remaining.Count; - Buffer.BlockCopy(_remaining.Array, _remaining.Offset, buffer, offset, count); - _remaining = default(ArraySegment); + Buffer.BlockCopy(_remaining.Array!, _remaining.Offset, buffer, offset, count); + _remaining = default; } else { - Buffer.BlockCopy(_remaining.Array, _remaining.Offset, buffer, offset, count); - _remaining = new ArraySegment(_remaining.Array, _remaining.Offset + count, _remaining.Count - count); + Buffer.BlockCopy(_remaining.Array!, _remaining.Offset, buffer, offset, count); + _remaining = new ArraySegment(_remaining.Array!, _remaining.Offset + count, _remaining.Count - count); } return count; } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs index 279e86d30261..1f3eba55f381 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs @@ -15,7 +15,7 @@ public class BuiltInCommand : ICommand private readonly IBuiltInCommandEnvironment _environment; private readonly StreamForwarder _stdOut; private readonly StreamForwarder _stdErr; - private string _workingDirectory; + private string? _workingDirectory; public string CommandName { get; } public string CommandArgs => string.Join(" ", _commandArgs); @@ -57,7 +57,7 @@ public CommandResult Execute() if (!string.IsNullOrEmpty(_workingDirectory)) { - _environment.SetWorkingDirectory(_workingDirectory); + _environment.SetWorkingDirectory(_workingDirectory!); } var taskOut = _stdOut.BeginRead(new StreamReader(outStream)); @@ -168,12 +168,12 @@ public ICommand EnvironmentVariable(string name, string value) throw new NotImplementedException(); } - public ICommand ForwardStdErr(TextWriter to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true) + public ICommand ForwardStdErr(TextWriter? to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true) { throw new NotImplementedException(); } - public ICommand ForwardStdOut(TextWriter to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true) + public ICommand ForwardStdOut(TextWriter? to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true) { throw new NotImplementedException(); } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs index b69ef82b6ea9..92e53984ff8c 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs @@ -10,9 +10,9 @@ public class Command : ICommand { private readonly Process _process; - private StreamForwarder _stdOut; + private StreamForwarder? _stdOut; - private StreamForwarder _stdErr; + private StreamForwarder? _stdErr; private bool _running = false; @@ -108,7 +108,7 @@ public ICommand CaptureStdOut() { ThrowIfRunning(); EnsureStdOut(); - _stdOut.Capture(_trimTrailingNewlines); + _stdOut?.Capture(_trimTrailingNewlines); return this; } @@ -116,11 +116,11 @@ public ICommand CaptureStdErr() { ThrowIfRunning(); EnsureStdErr(); - _stdErr.Capture(_trimTrailingNewlines); + _stdErr?.Capture(_trimTrailingNewlines); return this; } - public ICommand ForwardStdOut(TextWriter to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true) + public ICommand ForwardStdOut(TextWriter? to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true) { ThrowIfRunning(); if (!onlyIfVerbose || CommandLoggingContext.IsVerbose) @@ -129,18 +129,18 @@ public ICommand ForwardStdOut(TextWriter to = null, bool onlyIfVerbose = false, if (to == null) { - _stdOut.ForwardTo(writeLine: Reporter.Output.WriteLine); + _stdOut?.ForwardTo(writeLine: Reporter.Output.WriteLine); EnvironmentVariable(CommandLoggingContext.Variables.AnsiPassThru, ansiPassThrough.ToString()); } else { - _stdOut.ForwardTo(writeLine: to.WriteLine); + _stdOut?.ForwardTo(writeLine: to.WriteLine); } } return this; } - public ICommand ForwardStdErr(TextWriter to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true) + public ICommand ForwardStdErr(TextWriter? to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true) { ThrowIfRunning(); if (!onlyIfVerbose || CommandLoggingContext.IsVerbose) @@ -149,12 +149,12 @@ public ICommand ForwardStdErr(TextWriter to = null, bool onlyIfVerbose = false, if (to == null) { - _stdErr.ForwardTo(writeLine: Reporter.Error.WriteLine); + _stdErr?.ForwardTo(writeLine: Reporter.Error.WriteLine); EnvironmentVariable(CommandLoggingContext.Variables.AnsiPassThru, ansiPassThrough.ToString()); } else { - _stdErr.ForwardTo(writeLine: to.WriteLine); + _stdErr?.ForwardTo(writeLine: to.WriteLine); } } return this; @@ -165,7 +165,7 @@ public ICommand OnOutputLine(Action handler) ThrowIfRunning(); EnsureStdOut(); - _stdOut.ForwardTo(writeLine: handler); + _stdOut?.ForwardTo(writeLine: handler); return this; } @@ -174,7 +174,7 @@ public ICommand OnErrorLine(Action handler) ThrowIfRunning(); EnsureStdErr(); - _stdErr.ForwardTo(writeLine: handler); + _stdErr?.ForwardTo(writeLine: handler); return this; } @@ -210,7 +210,7 @@ private void EnsureStdErr() _process.StartInfo.RedirectStandardError = true; } - private void ThrowIfRunning([CallerMemberName] string memberName = null) + private void ThrowIfRunning([CallerMemberName] string? memberName = null) { if (_running) { diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/CommandResult.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/CommandResult.cs index 2b7717792a18..6700a22b26ee 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/CommandResult.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/CommandResult.cs @@ -11,10 +11,10 @@ public struct CommandResult public ProcessStartInfo StartInfo { get; } public int ExitCode { get; } - public string StdOut { get; } - public string StdErr { get; } + public string? StdOut { get; } + public string? StdErr { get; } - public CommandResult(ProcessStartInfo startInfo, int exitCode, string stdOut, string stdErr) + public CommandResult(ProcessStartInfo startInfo, int exitCode, string? stdOut, string? stdErr) { StartInfo = startInfo; ExitCode = exitCode; diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/DangerousFileDetector.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/DangerousFileDetector.cs index f9e76169815d..65ac501b4378 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/DangerousFileDetector.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/DangerousFileDetector.cs @@ -26,7 +26,7 @@ private static class InternetSecurity private const uint ZoneInternet = 3; private const uint ZoneUntrusted = 4; private const int REGDB_E_CLASSNOTREG = unchecked((int)0x80040154); - private static IInternetSecurityManager internetSecurityManager = null; + private static IInternetSecurityManager? internetSecurityManager = null; #if NETCOREAPP [SupportedOSPlatform("windows")] @@ -38,11 +38,11 @@ public static bool IsDangerous(string filename) // First check the zone, if they are not an untrusted zone, they aren't dangerous if (internetSecurityManager == null) { - Type iismType = Type.GetTypeFromCLSID(new Guid(CLSID_InternetSecurityManager)); - internetSecurityManager = (IInternetSecurityManager)Activator.CreateInstance(iismType); + Type iismType = Type.GetTypeFromCLSID(new Guid(CLSID_InternetSecurityManager))!; + internetSecurityManager = Activator.CreateInstance(iismType!) as IInternetSecurityManager; } int zone = 0; - internetSecurityManager.MapUrlToZone(Path.GetFullPath(filename), out zone, 0); + internetSecurityManager?.MapUrlToZone(Path.GetFullPath(filename), out zone, 0); if (zone < ZoneInternet) { return false; diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/DependencyProvider.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/DependencyProvider.cs index 89cfa926049e..ebe7cd44cd55 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/DependencyProvider.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/DependencyProvider.cs @@ -72,7 +72,7 @@ public sealed class DependencyProvider /// /// The product code of the MSI associated with the dependency provider. /// - public string ProductCode => GetProductCode(); + public string? ProductCode => GetProductCode(); /// /// The path of the provider key, relative to the . @@ -143,12 +143,12 @@ public void RemoveDependent(string dependent, bool removeProvider) throw new ArgumentException($"{nameof(dependent)} cannot be empty."); } - using RegistryKey dependentsKey = BaseKey.OpenSubKey(DependentsKeyPath, writable: true); + using RegistryKey? dependentsKey = BaseKey.OpenSubKey(DependentsKeyPath, writable: true); dependentsKey?.DeleteSubKeyTree(dependent); if ((removeProvider) && (Dependents.Count() == 0)) { - using RegistryKey providerKey = BaseKey.OpenSubKey(DependenciesKeyRelativePath, writable: true); + using RegistryKey? providerKey = BaseKey.OpenSubKey(DependenciesKeyRelativePath, writable: true); providerKey?.DeleteSubKeyTree(ProviderKeyName); } } @@ -159,7 +159,7 @@ public void RemoveDependent(string dependent, bool removeProvider) /// All dependents of the provider key. private IEnumerable GetDependents() { - using RegistryKey dependentsKey = BaseKey.OpenSubKey(DependentsKeyPath); + using RegistryKey? dependentsKey = BaseKey.OpenSubKey(DependentsKeyPath); return dependentsKey?.GetSubKeyNames() ?? Enumerable.Empty(); } @@ -169,22 +169,22 @@ private IEnumerable GetDependents() /// value. /// /// The ProductCode associated with this dependency provider or if it does not exist. - private string GetProductCode() + private string? GetProductCode() { - using RegistryKey providerKey = BaseKey.OpenSubKey(ProviderKeyPath); + using RegistryKey? providerKey = BaseKey.OpenSubKey(ProviderKeyPath); return providerKey?.GetValue(null) as string ?? null; } public override string ToString() => ProviderKeyName; - public static DependencyProvider GetFromProductCode(string productCode, bool allUsers = true) + public static DependencyProvider? GetFromProductCode(string productCode, bool allUsers = true) { var baseKey = allUsers ? Registry.LocalMachine : Registry.CurrentUser; - using RegistryKey dependenciesKey = baseKey.OpenSubKey(DependenciesKeyRelativePath); + using RegistryKey? dependenciesKey = baseKey.OpenSubKey(DependenciesKeyRelativePath); - foreach (var providerKeyName in dependenciesKey.GetSubKeyNames()) + foreach (var providerKeyName in dependenciesKey!.GetSubKeyNames()) { - using RegistryKey providerKey = dependenciesKey.OpenSubKey(providerKeyName); + using RegistryKey? providerKey = dependenciesKey.OpenSubKey(providerKeyName); var thisProductCode = providerKey?.GetValue(null) as string ?? null; if (string.Equals(thisProductCode, productCode, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/DotDefaultPathCorrector.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/DotDefaultPathCorrector.cs index a50352d6465e..f528cb8941d6 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/DotDefaultPathCorrector.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/DotDefaultPathCorrector.cs @@ -15,17 +15,14 @@ public static class DotDefaultPathCorrector public static void Correct() { var pathEditor = new WindowsRegistryEnvironmentPathEditor(); - var dotDefaultPath = - pathEditor.Get( - SdkEnvironmentVariableTarget.DotDefault); + var dotDefaultPath = pathEditor.Get(SdkEnvironmentVariableTarget.DotDefault); if (NeedCorrection(dotDefaultPath, out var correctedPath)) { - pathEditor.Set(correctedPath, - SdkEnvironmentVariableTarget.DotDefault); + pathEditor.Set(correctedPath, SdkEnvironmentVariableTarget.DotDefault); } } - internal static bool NeedCorrection(string existingPath, out string correctedPath) + internal static bool NeedCorrection(string? existingPath, out string correctedPath) { correctedPath = string.Empty; if (string.IsNullOrWhiteSpace(existingPath)) @@ -33,7 +30,7 @@ internal static bool NeedCorrection(string existingPath, out string correctedPat return false; } - IEnumerable paths = existingPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + IEnumerable paths = existingPath!.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var inCorrectToolsPaths = paths.Where(p => p.EndsWith(DotnetToolsSuffix, StringComparison.OrdinalIgnoreCase)); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/DotnetVersionFile.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/DotnetVersionFile.cs index 42d363b92508..a3aa77fb1dc5 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/DotnetVersionFile.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/DotnetVersionFile.cs @@ -7,13 +7,13 @@ internal class DotnetVersionFile { public bool Exists { get; init; } - public string CommitSha { get; init; } + public string? CommitSha { get; init; } - public string BuildNumber { get; init; } + public string? BuildNumber { get; init; } - public string FullNugetVersion { get; init; } + public string? FullNugetVersion { get; init; } - public string SdkFeatureBand { get; init; } + public string? SdkFeatureBand { get; init; } /// /// The runtime identifier (rid) that this CLI was built for. @@ -24,7 +24,7 @@ internal class DotnetVersionFile /// RuntimeInformation.RuntimeIdentifier may be for a new version of the OS that /// doesn't have full support yet. /// - public string BuildRid { get; init; } + public string? BuildRid { get; init; } public DotnetVersionFile(string versionFilePath) { diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Env.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Env.cs index 5fff4f7447e2..8593276385fd 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Env.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Env.cs @@ -15,17 +15,17 @@ public static IEnumerable ExecutableExtensions } } - public static string GetCommandPath(string commandName, params string[] extensions) + public static string? GetCommandPath(string commandName, params string[] extensions) { return _environment.GetCommandPath(commandName, extensions); } - public static string GetCommandPathFromRootPath(string rootPath, string commandName, params string[] extensions) + public static string? GetCommandPathFromRootPath(string rootPath, string commandName, params string[] extensions) { return _environment.GetCommandPathFromRootPath(rootPath, commandName, extensions); } - public static string GetCommandPathFromRootPath(string rootPath, string commandName, IEnumerable extensions) + public static string? GetCommandPathFromRootPath(string rootPath, string commandName, IEnumerable extensions) { return _environment.GetCommandPathFromRootPath(rootPath, commandName, extensions); } @@ -40,7 +40,7 @@ public static bool GetEnvironmentVariableAsBool(string name, bool defaultValue = return _environment.GetEnvironmentVariableAsNullableInt(name); } - public static string GetEnvironmentVariable(string name) + public static string? GetEnvironmentVariable(string name) { return _environment.GetEnvironmentVariable(name); } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/EnvironmentProvider.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/EnvironmentProvider.cs index aa23691e82ad..cace01528c29 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/EnvironmentProvider.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/EnvironmentProvider.cs @@ -7,9 +7,9 @@ public class EnvironmentProvider : IEnvironmentProvider { private static char[] s_pathSeparator = new char[] { Path.PathSeparator }; private static char[] s_quote = new char[] { '"' }; - private IEnumerable _searchPaths; + private IEnumerable? _searchPaths; private readonly Lazy _userHomeDirectory = new(() => Environment.GetEnvironmentVariable("HOME") ?? string.Empty); - private IEnumerable _executableExtensions; + private IEnumerable? _executableExtensions; public IEnumerable ExecutableExtensions { @@ -17,12 +17,11 @@ public IEnumerable ExecutableExtensions { if (_executableExtensions == null) { - _executableExtensions = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? Environment.GetEnvironmentVariable("PATHEXT") + ? Environment.GetEnvironmentVariable("PATHEXT")? .Split(';') - .Select(e => e.ToLower().Trim('"')) - : new[] { string.Empty }; + .Select(e => e.ToLower().Trim('"')) ?? [string.Empty] + : [string.Empty]; } return _executableExtensions; @@ -38,11 +37,11 @@ private IEnumerable SearchPaths var searchPaths = new List { AppContext.BaseDirectory }; searchPaths.AddRange(Environment - .GetEnvironmentVariable("PATH") + .GetEnvironmentVariable("PATH")? .Split(s_pathSeparator) .Select(p => p.Trim(s_quote)) .Where(p => !string.IsNullOrWhiteSpace(p)) - .Select(p => ExpandTildeSlash(p))); + .Select(p => ExpandTildeSlash(p)) ?? [string.Empty]); _searchPaths = searchPaths; } @@ -65,14 +64,14 @@ private string ExpandTildeSlash(string path) } public EnvironmentProvider( - IEnumerable extensionsOverride = null, - IEnumerable searchPathsOverride = null) + IEnumerable? extensionsOverride = null, + IEnumerable? searchPathsOverride = null) { _executableExtensions = extensionsOverride; _searchPaths = searchPathsOverride; } - public string GetCommandPath(string commandName, params string[] extensions) + public string? GetCommandPath(string commandName, params string[] extensions) { if (!extensions.Any()) { @@ -88,7 +87,7 @@ public string GetCommandPath(string commandName, params string[] extensions) return commandPath; } - public string GetCommandPathFromRootPath(string rootPath, string commandName, params string[] extensions) + public string? GetCommandPathFromRootPath(string rootPath, string commandName, params string[] extensions) { if (!extensions.Any()) { @@ -101,14 +100,14 @@ public string GetCommandPathFromRootPath(string rootPath, string commandName, pa return commandPath; } - public string GetCommandPathFromRootPath(string rootPath, string commandName, IEnumerable extensions) + public string? GetCommandPathFromRootPath(string rootPath, string commandName, IEnumerable extensions) { var extensionsArr = extensions.OrEmptyIfNull().ToArray(); return GetCommandPathFromRootPath(rootPath, commandName, extensionsArr); } - public string GetEnvironmentVariable(string name) + public string? GetEnvironmentVariable(string name) { return Environment.GetEnvironmentVariable(name); } @@ -136,7 +135,7 @@ public bool GetEnvironmentVariableAsBool(string name, bool defaultValue) } } - public string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) + public string? GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) { return Environment.GetEnvironmentVariable(variable, target); } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs index 1b81e1cef57f..9c702c971917 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs @@ -40,7 +40,7 @@ public static async Task ExecuteAsyncWithRetry(Func> action, foreach (var t in timer()) { await t; - T result = default; + T? result = default; count++; result = await action(); @@ -70,7 +70,7 @@ public static async Task ExecuteWithRetry(Func action, public static async Task ExecuteWithRetryOnFailure(Func> action, int maxRetryCount = 3, - Func> timer = null) + Func>? timer = null) { timer = timer == null ? () => Timer(Intervals) : timer; return await ExecuteAsyncWithRetry(action, result => result != null && !result.Equals(default), maxRetryCount, timer); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessExtensions.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessExtensions.cs index 2bdea2698f1a..dd849efe6fca 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessExtensions.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessExtensions.cs @@ -21,7 +21,7 @@ public static class ProcessExtensions /// /// The process component. /// The parent process or if the parent process cannot be found. - public static Process GetParentProcess(this Process process) + public static Process? GetParentProcess(this Process process) { int ppid = process.GetParentProcessId(); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs index c83369ef56cf..9dd01cb95e27 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs @@ -15,9 +15,9 @@ internal class ForwardingAppImplementation { private readonly string _forwardApplicationPath; private readonly IEnumerable _argsToForward; - private readonly string _depsFile; - private readonly string _runtimeConfig; - private readonly string _additionalProbingPath; + private readonly string? _depsFile; + private readonly string? _runtimeConfig; + private readonly string? _additionalProbingPath; private Dictionary _environmentVariables; private readonly string[] _allArgs; @@ -25,10 +25,10 @@ internal class ForwardingAppImplementation public ForwardingAppImplementation( string forwardApplicationPath, IEnumerable argsToForward, - string depsFile = null, - string runtimeConfig = null, - string additionalProbingPath = null, - Dictionary environmentVariables = null) + string? depsFile = null, + string? runtimeConfig = null, + string? additionalProbingPath = null, + Dictionary? environmentVariables = null) { _forwardApplicationPath = forwardApplicationPath; _argsToForward = argsToForward; @@ -96,7 +96,7 @@ public ForwardingAppImplementation WithEnvironmentVariable(string name, string v private string GetHostExeName() { // Should instead make this a full path to dotnet - return Environment.ProcessPath; + return Environment.ProcessPath!; } } } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/FrameworkDependencyFile.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/FrameworkDependencyFile.cs index c5db45a331c3..eee9307f3ab2 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/FrameworkDependencyFile.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/FrameworkDependencyFile.cs @@ -11,7 +11,7 @@ namespace Microsoft.DotNet.Cli.Utils /// internal class FrameworkDependencyFile { - private readonly string _depsFilePath; + private readonly string? _depsFilePath; private readonly Lazy _dependencyContext; private DependencyContext DependencyContext => _dependencyContext.Value; @@ -27,7 +27,7 @@ public bool IsRuntimeSupported(string runtimeIdentifier) return DependencyContext.RuntimeGraph.Any(g => g.Runtime == runtimeIdentifier); } - public string GetNetStandardLibraryVersion() + public string? GetNetStandardLibraryVersion() { return DependencyContext .RuntimeLibraries @@ -39,7 +39,7 @@ public string GetNetStandardLibraryVersion() public bool TryGetMostFitRuntimeIdentifier( string alternativeCurrentRuntimeIdentifier, string[] candidateRuntimeIdentifiers, - out string mostFitRuntimeIdentifier) + out string? mostFitRuntimeIdentifier) { return TryGetMostFitRuntimeIdentifier( RuntimeInformation.RuntimeIdentifier, @@ -55,7 +55,7 @@ internal static bool TryGetMostFitRuntimeIdentifier( string alternativeCurrentRuntimeIdentifier, IReadOnlyList runtimeGraph, string[] candidateRuntimeIdentifiers, - out string mostFitRuntimeIdentifier) + out string? mostFitRuntimeIdentifier) { mostFitRuntimeIdentifier = null; RuntimeFallbacks[] runtimeFallbacksCandidates; @@ -87,21 +87,19 @@ internal static bool TryGetMostFitRuntimeIdentifier( RuntimeFallbacks runtimeFallbacks = runtimeFallbacksCandidates[0]; - var runtimeFallbacksIncludesRuntime = new List(); + var runtimeFallbacksIncludesRuntime = new List(); runtimeFallbacksIncludesRuntime.Add(runtimeFallbacks.Runtime); runtimeFallbacksIncludesRuntime.AddRange(runtimeFallbacks.Fallbacks); - var candidateMap = candidateRuntimeIdentifiers .Distinct(comparer: StringComparer.OrdinalIgnoreCase) .ToDictionary(x => x, StringComparer.OrdinalIgnoreCase); foreach (var fallback in runtimeFallbacksIncludesRuntime) { - if (candidateMap.TryGetValue(fallback, out string match)) + if (fallback is not null && candidateMap.TryGetValue(fallback, out string? match)) { mostFitRuntimeIdentifier = match; - return true; } } @@ -111,7 +109,7 @@ internal static bool TryGetMostFitRuntimeIdentifier( private DependencyContext CreateDependencyContext() { - using (Stream depsFileStream = File.OpenRead(_depsFilePath)) + using (Stream depsFileStream = File.OpenRead(_depsFilePath!)) using (DependencyContextJsonReader reader = new()) { return reader.Read(depsFileStream); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/GracefulException.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/GracefulException.cs index 8de30ca1a06f..f7baa03a7701 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/GracefulException.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/GracefulException.cs @@ -18,7 +18,7 @@ public GracefulException(string message) : base(message) } - public GracefulException(IEnumerable messages, IEnumerable verboseMessages = null, + public GracefulException(IEnumerable messages, IEnumerable? verboseMessages = null, bool isUserError = true) : this(string.Join(Environment.NewLine, messages), isUserError: isUserError) { @@ -32,7 +32,7 @@ public GracefulException(string format, params string[] args) : this(string.Form { } - public GracefulException(string message, Exception innerException = null, bool isUserError = true) : base(message, innerException) + public GracefulException(string message, Exception? innerException = null, bool isUserError = true) : base(message, innerException) { IsUserError = isUserError; Data.Add(ExceptionExtensions.CLI_User_Displayed_Exception, isUserError); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs index 31fdaa008ef5..8c6af48001e9 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs @@ -15,9 +15,9 @@ public interface ICommand ICommand CaptureStdErr(); - ICommand ForwardStdOut(TextWriter to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true); + ICommand ForwardStdOut(TextWriter? to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true); - ICommand ForwardStdErr(TextWriter to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true); + ICommand ForwardStdErr(TextWriter? to = null, bool onlyIfVerbose = false, bool ansiPassThrough = true); ICommand OnOutputLine(Action handler); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/IEnvironmentProvider.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/IEnvironmentProvider.cs index 6229d975bbc9..7c48a4711a64 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/IEnvironmentProvider.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/IEnvironmentProvider.cs @@ -7,19 +7,19 @@ public interface IEnvironmentProvider { IEnumerable ExecutableExtensions { get; } - string GetCommandPath(string commandName, params string[] extensions); + string? GetCommandPath(string commandName, params string[] extensions); - string GetCommandPathFromRootPath(string rootPath, string commandName, params string[] extensions); + string? GetCommandPathFromRootPath(string rootPath, string commandName, params string[] extensions); - string GetCommandPathFromRootPath(string rootPath, string commandName, IEnumerable extensions); + string? GetCommandPathFromRootPath(string rootPath, string commandName, IEnumerable extensions); bool GetEnvironmentVariableAsBool(string name, bool defaultValue); int? GetEnvironmentVariableAsNullableInt(string name); - string GetEnvironmentVariable(string name); + string? GetEnvironmentVariable(string name); - string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target); + string? GetEnvironmentVariable(string variable, EnvironmentVariableTarget target); void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target); } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/IReporter.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/IReporter.cs index 3322ae7edf1a..d74c3bfe5f00 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/IReporter.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/IReporter.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace Microsoft.DotNet.Cli.Utils { public interface IReporter diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/IWindowsRegistryEnvironmentPathEditor.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/IWindowsRegistryEnvironmentPathEditor.cs index 8cd1506cce12..bf3b8d760a43 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/IWindowsRegistryEnvironmentPathEditor.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/IWindowsRegistryEnvironmentPathEditor.cs @@ -5,7 +5,7 @@ namespace Microsoft.DotNet.Cli.Utils { internal interface IWindowsRegistryEnvironmentPathEditor { - string Get(SdkEnvironmentVariableTarget sdkEnvironmentVariableTarget); + string? Get(SdkEnvironmentVariableTarget sdkEnvironmentVariableTarget); void Set(string value, SdkEnvironmentVariableTarget sdkEnvironmentVariableTarget); } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs index 8d362d64ec23..36515612598d 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs @@ -17,7 +17,7 @@ internal class MSBuildForwardingAppWithoutLogging { private static readonly bool AlwaysExecuteMSBuildOutOfProc = Env.GetEnvironmentVariableAsBool("DOTNET_CLI_RUN_MSBUILD_OUTOFPROC"); private static readonly bool UseMSBuildServer = Env.GetEnvironmentVariableAsBool("DOTNET_CLI_USE_MSBUILD_SERVER", false); - private static readonly string TerminalLoggerDefault = Env.GetEnvironmentVariable("DOTNET_CLI_CONFIGURE_MSBUILD_TERMINAL_LOGGER"); + private static readonly string? TerminalLoggerDefault = Env.GetEnvironmentVariable("DOTNET_CLI_CONFIGURE_MSBUILD_TERMINAL_LOGGER"); public static string MSBuildVersion { @@ -28,12 +28,12 @@ public static string MSBuildVersion private const string SdksDirectoryName = "Sdks"; // Null if we're running MSBuild in-proc. - private ForwardingAppImplementation _forwardingApp; + private ForwardingAppImplementation? _forwardingApp; // Command line arguments we're asked to forward to MSBuild. private readonly IEnumerable _argsToForward; - internal static string MSBuildExtensionsPathTestHook = null; + internal static string? MSBuildExtensionsPathTestHook = null; // Path to the MSBuild binary to use. public string MSBuildPath { get; } @@ -52,12 +52,12 @@ public static string MSBuildVersion private readonly List _msbuildRequiredParameters = [ "-maxcpucount", "-verbosity:m" ]; - public MSBuildForwardingAppWithoutLogging(IEnumerable argsToForward, string msbuildPath = null, bool includeLogo = false) + public MSBuildForwardingAppWithoutLogging(IEnumerable argsToForward, string? msbuildPath = null, bool includeLogo = false) { string defaultMSBuildPath = GetMSBuildExePath(); _argsToForward = includeLogo ? argsToForward : ["-nologo", ..argsToForward]; - string tlpDefault = TerminalLoggerDefault; + string? tlpDefault = TerminalLoggerDefault; // new for .NET 9 - default TL to auto (aka enable in non-CI scenarios) if (string.IsNullOrWhiteSpace(tlpDefault)) { @@ -137,7 +137,7 @@ public int Execute() public int ExecuteInProc(string[] arguments) { // Save current environment variables before overwriting them. - Dictionary savedEnvironmentVariables = new(); + Dictionary savedEnvironmentVariables = new(); try { foreach (KeyValuePair kvp in _msbuildRequiredEnvironmentVariables) @@ -165,7 +165,7 @@ public int ExecuteInProc(string[] arguments) finally { // Restore saved environment variables. - foreach (KeyValuePair kvp in savedEnvironmentVariables) + foreach (KeyValuePair kvp in savedEnvironmentVariables) { Environment.SetEnvironmentVariable(kvp.Key, kvp.Value); } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildProjectExtensions.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildProjectExtensions.cs index 20c11baa4404..d22d032ad4f8 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildProjectExtensions.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildProjectExtensions.cs @@ -10,7 +10,7 @@ internal static class MSBuildProjectExtensions { public static bool IsConditionalOnFramework(this ProjectElement el, string framework) { - string conditionStr; + string? conditionStr; if (!TryGetFrameworkConditionString(framework, out conditionStr)) { return el.ConditionChain().Count == 0; @@ -40,7 +40,7 @@ public static ISet ConditionChain(this ProjectElement projectElement) return conditionChainSet; } - public static ProjectItemGroupElement LastItemGroup(this ProjectRootElement root) + public static ProjectItemGroupElement? LastItemGroup(this ProjectRootElement root) { return root.ItemGroupsReversed.FirstOrDefault(); } @@ -55,7 +55,7 @@ public static ProjectItemGroupElement FindUniformOrCreateItemGroupWithCondition( } ProjectItemGroupElement ret = root.CreateItemGroupElement(); - string condStr; + string? condStr; if (TryGetFrameworkConditionString(framework, out condStr)) { ret.Condition = condStr; @@ -65,7 +65,7 @@ public static ProjectItemGroupElement FindUniformOrCreateItemGroupWithCondition( return ret; } - public static ProjectItemGroupElement FindExistingUniformItemGroupWithCondition(this ProjectRootElement root, string projectItemElementType, string framework) + public static ProjectItemGroupElement? FindExistingUniformItemGroupWithCondition(this ProjectRootElement root, string projectItemElementType, string framework) { return root.ItemGroupsReversed.FirstOrDefault((itemGroup) => itemGroup.IsConditionalOnFramework(framework) && itemGroup.IsUniformItemElementType(projectItemElementType)); } @@ -116,7 +116,7 @@ private static IEnumerable SplitSemicolonDelimitedValues(string combined } - private static bool TryGetFrameworkConditionString(string framework, out string condition) + private static bool TryGetFrameworkConditionString(string framework, out string? condition) { if (string.IsNullOrEmpty(framework)) { diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildPropertyParser.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildPropertyParser.cs index f3fda527a9b1..a84fdfec1715 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildPropertyParser.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildPropertyParser.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. - -#nullable enable - namespace Microsoft.DotNet.Cli.Utils; /// diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Microsoft.DotNet.Cli.Utils.csproj b/src/Cli/Microsoft.DotNet.Cli.Utils/Microsoft.DotNet.Cli.Utils.csproj index fa12a6ababd3..6c0d6aaf28fa 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Microsoft.DotNet.Cli.Utils.csproj +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Microsoft.DotNet.Cli.Utils.csproj @@ -13,6 +13,7 @@ true true true + enable diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Muxer.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Muxer.cs index 0417d0e5a823..7797d0487284 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Muxer.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Muxer.cs @@ -9,16 +9,9 @@ public class Muxer { public static readonly string MuxerName = "dotnet"; - private readonly string _muxerPath; + private readonly string? _muxerPath; - internal string SharedFxVersion - { - get - { - var depsFile = new FileInfo(GetDataFromAppDomain("FX_DEPS_FILE")); - return depsFile.Directory.Name; - } - } + internal string SharedFxVersion => new FileInfo(GetDataFromAppDomain("FX_DEPS_FILE")!).Directory!.Name; public string MuxerPath { @@ -41,7 +34,7 @@ public Muxer() #endif } - public static string GetDataFromAppDomain(string propertyName) + public static string? GetDataFromAppDomain(string propertyName) { return AppContext.GetData(propertyName) as string; } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.cs index 2467eb6166ea..7f6f766049dd 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.cs @@ -70,7 +70,7 @@ internal struct PROCESS_BASIC_INFORMATION } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern SafeWaitHandle CreateJobObjectW(IntPtr lpJobAttributes, string lpName); + internal static extern SafeWaitHandle CreateJobObjectW(IntPtr lpJobAttributes, string? lpName); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoClass jobObjectInformationClass, IntPtr lpJobObjectInformation, uint cbJobObjectInformationLength); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/PathUtility.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/PathUtility.cs index f641cdcd5b73..f1231dbb2206 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/PathUtility.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/PathUtility.cs @@ -70,9 +70,8 @@ public static string EnsureNoTrailingDirectorySeparator(string path) public static void EnsureParentDirectoryExists(string filePath) { - string directory = Path.GetDirectoryName(filePath); - - EnsureDirectoryExists(directory); + string? directory = Path.GetDirectoryName(filePath); + EnsureDirectoryExists(directory!); } public static void EnsureDirectoryExists(string directoryPath) @@ -88,7 +87,6 @@ public static bool TryDeleteDirectory(string directoryPath) try { Directory.Delete(directoryPath, true); - return true; } catch @@ -237,7 +235,7 @@ public static string GetAbsolutePath(string basePath, string relativePath) public static string GetDirectoryName(string path) { path = path.TrimEnd(Path.DirectorySeparatorChar); - return path.Substring(Path.GetDirectoryName(path).Length).Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + return path.Substring(Path.GetDirectoryName(path)!.Length).Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); } public static string GetPathWithForwardSlashes(string path) diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs index 504f9d630299..f9d97e8242d4 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.Diagnostics; using Microsoft.Win32.SafeHandles; diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessStartInfoExtensions.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessStartInfoExtensions.cs index 4ba88507b531..e1dfa7b71203 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessStartInfoExtensions.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessStartInfoExtensions.cs @@ -29,7 +29,7 @@ public static int Execute(this ProcessStartInfo startInfo) return process.ExitCode; } - public static int ExecuteAndCaptureOutput(this ProcessStartInfo startInfo, out string stdOut, out string stdErr) + public static int ExecuteAndCaptureOutput(this ProcessStartInfo startInfo, out string? stdOut, out string? stdErr) { var outStream = new StreamForwarder().Capture(); var errStream = new StreamForwarder().Capture(); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Reporter.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Reporter.cs index 30d76d8e8e1e..4fd35a563a68 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Reporter.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Reporter.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - - namespace Microsoft.DotNet.Cli.Utils { // Stupid-simple console manager diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/RuntimeEnvironment.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/RuntimeEnvironment.cs index 31dfe90dad6d..451e7555ecde 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/RuntimeEnvironment.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/RuntimeEnvironment.cs @@ -18,7 +18,7 @@ internal enum Platform internal static class RuntimeEnvironment { private static readonly Lazy _platform = new(DetermineOSPlatform); - private static readonly Lazy _distroInfo = new(LoadDistroInfo); + private static readonly Lazy _distroInfo = new(LoadDistroInfo); public static Platform OperatingSystemPlatform { get; } = GetOSPlatform(); public static string OperatingSystemVersion { get; } = GetOSVersion(); @@ -26,8 +26,8 @@ internal static class RuntimeEnvironment private class DistroInfo { - public string Id; - public string VersionId; + public string? Id; + public string? VersionId; } private static string GetOSName() @@ -99,17 +99,17 @@ private static Platform GetOSPlatform() return _platform.Value; } - private static string GetDistroId() + private static string? GetDistroId() { return _distroInfo.Value?.Id; } - private static string GetDistroVersionId() + private static string? GetDistroVersionId() { return _distroInfo.Value?.VersionId; } - private static DistroInfo LoadDistroInfo() + private static DistroInfo? LoadDistroInfo() { switch (GetOSPlatform()) { @@ -122,9 +122,9 @@ private static DistroInfo LoadDistroInfo() return null; } - private static DistroInfo LoadDistroInfoFromLinux() + private static DistroInfo? LoadDistroInfoFromLinux() { - DistroInfo result = null; + DistroInfo? result = null; // Sample os-release file: // NAME="Ubuntu" @@ -163,9 +163,9 @@ private static DistroInfo LoadDistroInfoFromLinux() return result; } - private static DistroInfo LoadDistroInfoFromIllumos() + private static DistroInfo? LoadDistroInfoFromIllumos() { - DistroInfo result = null; + DistroInfo? result = null; // examples: // on OmniOS // SunOS 5.11 omnios-r151018-95eaa7e @@ -218,12 +218,12 @@ private static DistroInfo NormalizeDistroInfo(DistroInfo distroInfo) if (lastVersionNumberSeparatorIndex != -1 && distroInfo.Id == "alpine") { // For Alpine, the version reported has three components, so we need to find the second version separator - lastVersionNumberSeparatorIndex = distroInfo.VersionId.IndexOf('.', lastVersionNumberSeparatorIndex + 1); + lastVersionNumberSeparatorIndex = distroInfo.VersionId!.IndexOf('.', lastVersionNumberSeparatorIndex + 1); } if (lastVersionNumberSeparatorIndex != -1 && (distroInfo.Id == "rhel" || distroInfo.Id == "alpine")) { - distroInfo.VersionId = distroInfo.VersionId.Substring(0, lastVersionNumberSeparatorIndex); + distroInfo.VersionId = distroInfo.VersionId!.Substring(0, lastVersionNumberSeparatorIndex); } return distroInfo; diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Sha256Hasher.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Sha256Hasher.cs index a25272acac75..55d5a671bc14 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Sha256Hasher.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Sha256Hasher.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - #if NET using System; diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/StreamForwarder.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/StreamForwarder.cs index 6b91322f9e69..0e137f111207 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/StreamForwarder.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/StreamForwarder.cs @@ -8,12 +8,12 @@ public sealed class StreamForwarder private static readonly char[] s_ignoreCharacters = new char[] { '\r' }; private static readonly char s_flushBuilderCharacter = '\n'; - private StringBuilder _builder; - private StringWriter _capture; - private Action _writeLine; + private StringBuilder? _builder; + private StringWriter? _capture; + private Action? _writeLine; private bool _trimTrailingCapturedNewline; - public string CapturedOutput + public string? CapturedOutput { get { @@ -88,8 +88,8 @@ public void Read(TextReader reader) private void WriteBuilder() { - WriteLine(_builder.ToString()); - _builder.Clear(); + WriteLine(_builder?.ToString() ?? string.Empty); + _builder?.Clear(); } private void WriteLine(string str) diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/TelemetryEventEntry.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/TelemetryEventEntry.cs index 24fb69578bbf..033112bc996f 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/TelemetryEventEntry.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/TelemetryEventEntry.cs @@ -7,19 +7,19 @@ namespace Microsoft.DotNet.Cli.Utils { public static class TelemetryEventEntry { - public static event EventHandler EntryPosted; + public static event EventHandler? EntryPosted; public static ITelemetryFilter TelemetryFilter { get; set; } = new BlockFilter(); public static void TrackEvent( - string eventName = null, - IDictionary properties = null, - IDictionary measurements = null) + string? eventName = null, + IDictionary? properties = null, + IDictionary? measurements = null) { EntryPosted?.Invoke(typeof(TelemetryEventEntry), new InstrumentationEventArgs(eventName, properties, measurements)); } - public static void SendFiltered(object o = null) + public static void SendFiltered(object? o = null) { if (o == null) { @@ -32,11 +32,9 @@ public static void SendFiltered(object o = null) } } - public static void Subscribe(Action, - IDictionary> subscriber) + public static void Subscribe(Action?, IDictionary?> subscriber) { - void Handler(object sender, InstrumentationEventArgs eventArgs) + void Handler(object? sender, InstrumentationEventArgs eventArgs) { subscriber(eventArgs.EventName, eventArgs.Properties, eventArgs.Measurements); } @@ -47,9 +45,9 @@ void Handler(object sender, InstrumentationEventArgs eventArgs) public sealed class PerformanceMeasurement : IDisposable { - private readonly Stopwatch _timer; - private readonly Dictionary _data; - private readonly string _name; + private readonly Stopwatch? _timer; + private readonly Dictionary? _data; + private readonly string? _name; public PerformanceMeasurement(Dictionary data, string name) { @@ -64,7 +62,7 @@ public PerformanceMeasurement(Dictionary data, string name) _timer = Stopwatch.StartNew(); } - public void Dispose() => _data?.Add(_name, _timer.Elapsed.TotalMilliseconds); + public void Dispose() => _data?.Add(_name!, _timer!.Elapsed.TotalMilliseconds); } public class BlockFilter : ITelemetryFilter @@ -78,39 +76,39 @@ public IEnumerable Filter(object o) public class InstrumentationEventArgs : EventArgs { internal InstrumentationEventArgs( - string eventName, - IDictionary properties, - IDictionary measurements) + string? eventName, + IDictionary? properties, + IDictionary? measurements) { EventName = eventName; Properties = properties; Measurements = measurements; } - public string EventName { get; } - public IDictionary Properties { get; } - public IDictionary Measurements { get; } + public string? EventName { get; } + public IDictionary? Properties { get; } + public IDictionary? Measurements { get; } } public class ApplicationInsightsEntryFormat { public ApplicationInsightsEntryFormat( - string eventName = null, - IDictionary properties = null, - IDictionary measurements = null) + string? eventName = null, + IDictionary? properties = null, + IDictionary? measurements = null) { EventName = eventName; Properties = properties; Measurements = measurements; } - public string EventName { get; } - public IDictionary Properties { get; } - public IDictionary Measurements { get; } + public string? EventName { get; } + public IDictionary? Properties { get; } + public IDictionary? Measurements { get; } public ApplicationInsightsEntryFormat WithAppliedToPropertiesValue(Func func) { - var appliedProperties = Properties.ToDictionary(p => p.Key, p => func(p.Value)); + var appliedProperties = Properties?.ToDictionary(p => p.Key, p => func(p.Value)); return new ApplicationInsightsEntryFormat(EventName, appliedProperties, Measurements); } } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ToolCommandName.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ToolCommandName.cs index dd174851e01d..aa2d04a81e4c 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ToolCommandName.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ToolCommandName.cs @@ -29,7 +29,7 @@ public bool Equals(ToolCommandName other) return string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ToolCommandName name && Equals(name); } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/TypoCorrection.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/TypoCorrection.cs index 4b529a1def1f..d5964d48235d 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/TypoCorrection.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/TypoCorrection.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - - namespace Microsoft.DotNet.Cli.Utils { public static class TypoCorrection diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/UILanguageOverride.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/UILanguageOverride.cs index 59e37dc038dd..7297e4df08da 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/UILanguageOverride.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/UILanguageOverride.cs @@ -17,7 +17,7 @@ internal static class UILanguageOverride public static void Setup() { - CultureInfo language = GetOverriddenUILanguage(); + CultureInfo? language = GetOverriddenUILanguage(); if (language != null) { ApplyOverrideToCurrentProcess(language); @@ -54,10 +54,10 @@ private static void FlowOverrideToChildProcesses(CultureInfo language) /// /// The custom language that was set by the user. /// DOTNET_CLI_UI_LANGUAGE > VSLANG. Returns null if none are set. - private static CultureInfo GetOverriddenUILanguage() + private static CultureInfo? GetOverriddenUILanguage() { // DOTNET_CLI_UI_LANGUAGE= is the main way for users to customize the CLI's UI language. - string dotnetCliLanguage = Environment.GetEnvironmentVariable(DOTNET_CLI_UI_LANGUAGE); + string? dotnetCliLanguage = Environment.GetEnvironmentVariable(DOTNET_CLI_UI_LANGUAGE); if (dotnetCliLanguage != null) { try @@ -69,7 +69,7 @@ private static CultureInfo GetOverriddenUILanguage() // VSLANG= is set by VS and we respect that as well so that we will respect the VS // language preference if we're invoked by VS. - string vsLang = Environment.GetEnvironmentVariable(VSLANG); + string? vsLang = Environment.GetEnvironmentVariable(VSLANG); if (vsLang != null && int.TryParse(vsLang, out int vsLcid)) { try @@ -85,7 +85,7 @@ private static CultureInfo GetOverriddenUILanguage() private static void SetIfNotAlreadySet(string environmentVariableName, string value) { - string currentValue = Environment.GetEnvironmentVariable(environmentVariableName); + string? currentValue = Environment.GetEnvironmentVariable(environmentVariableName); if (currentValue == null) { Environment.SetEnvironmentVariable(environmentVariableName, value); @@ -111,10 +111,10 @@ private static bool CurrentPlatformOfficiallySupportsUTF8Encoding() Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); try { - using RegistryKey windowsVersionRegistry = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); - var buildNumber = windowsVersionRegistry.GetValue("CurrentBuildNumber").ToString(); + using RegistryKey? windowsVersionRegistry = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); + var buildNumber = windowsVersionRegistry?.GetValue("CurrentBuildNumber")?.ToString(); const int buildNumberThatOfficialySupportsUTF8 = 18363; - return int.Parse(buildNumber) >= buildNumberThatOfficialySupportsUTF8 || ForceUniversalEncodingOptInEnabled(); + return int.Parse(buildNumber!) >= buildNumberThatOfficialySupportsUTF8 || ForceUniversalEncodingOptInEnabled(); } catch (Exception ex) when (ex is SecurityException || ex is ObjectDisposedException) { diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Windows.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Windows.cs index e31f6a9a489d..49f43fe2ed64 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Windows.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Windows.cs @@ -40,7 +40,7 @@ public static bool InstallRunning() /// Returns the commandline of the currently executing process. /// /// The commandline of the current process. - public static string GetProcessCommandLine() + public static string? GetProcessCommandLine() { return Marshal.PtrToStringAuto(NativeMethods.Windows.GetCommandLine()); } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/WindowsRegistryEnvironmentPathEditor.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/WindowsRegistryEnvironmentPathEditor.cs index 67113fe3e251..86516ef63441 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/WindowsRegistryEnvironmentPathEditor.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/WindowsRegistryEnvironmentPathEditor.cs @@ -9,9 +9,9 @@ namespace Microsoft.DotNet.Cli.Utils internal class WindowsRegistryEnvironmentPathEditor : IWindowsRegistryEnvironmentPathEditor { private static string Path = "PATH"; - public string Get(SdkEnvironmentVariableTarget currentUserBeforeEvaluation) + public string? Get(SdkEnvironmentVariableTarget currentUserBeforeEvaluation) { - using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(writable: false, sdkEnvironmentVariableTarget: currentUserBeforeEvaluation)) + using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(writable: false, sdkEnvironmentVariableTarget: currentUserBeforeEvaluation)) { return environmentKey?.GetValue(Path, "", RegistryValueOptions.DoNotExpandEnvironmentNames) as string; } @@ -19,7 +19,7 @@ public string Get(SdkEnvironmentVariableTarget currentUserBeforeEvaluation) public void Set(string value, SdkEnvironmentVariableTarget sdkEnvironmentVariableTarget) { - using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(writable: true, sdkEnvironmentVariableTarget: sdkEnvironmentVariableTarget)) + using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(writable: true, sdkEnvironmentVariableTarget: sdkEnvironmentVariableTarget)) { environmentKey?.SetValue(Path, value, RegistryValueKind.ExpandString); } @@ -37,7 +37,7 @@ public void Set(string value, SdkEnvironmentVariableTarget sdkEnvironmentVariabl }); } - private static RegistryKey OpenEnvironmentKeyIfExists(bool writable, SdkEnvironmentVariableTarget sdkEnvironmentVariableTarget) + private static RegistryKey? OpenEnvironmentKeyIfExists(bool writable, SdkEnvironmentVariableTarget sdkEnvironmentVariableTarget) { RegistryKey baseKey; string keyName; diff --git a/src/Cli/dotnet/CommonOptionsFactory.cs b/src/Cli/dotnet/CommonOptionsFactory.cs index e29b1acf5de8..82ef38d3af63 100644 --- a/src/Cli/dotnet/CommonOptionsFactory.cs +++ b/src/Cli/dotnet/CommonOptionsFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.CommandLine; namespace Microsoft.DotNet.Cli diff --git a/src/Cli/dotnet/NuGetSignatureVerificationEnabler.cs b/src/Cli/dotnet/NuGetSignatureVerificationEnabler.cs index 1762bd11fea8..acff39030a56 100644 --- a/src/Cli/dotnet/NuGetSignatureVerificationEnabler.cs +++ b/src/Cli/dotnet/NuGetSignatureVerificationEnabler.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Tools.MSBuild; diff --git a/src/Cli/dotnet/ReleasePropertyProjectLocator.cs b/src/Cli/dotnet/ReleasePropertyProjectLocator.cs index 6e08a281c671..dd59f29aa2ca 100644 --- a/src/Cli/dotnet/ReleasePropertyProjectLocator.cs +++ b/src/Cli/dotnet/ReleasePropertyProjectLocator.cs @@ -22,7 +22,6 @@ class ReleasePropertyProjectLocator { public struct DependentCommandOptions { -#nullable enable public IEnumerable SlnOrProjectArgs = Enumerable.Empty(); public string? FrameworkOption; public string? ConfigurationOption; diff --git a/src/Cli/dotnet/commands/dotnet-new/DotnetCommandCallbacks.cs b/src/Cli/dotnet/commands/dotnet-new/DotnetCommandCallbacks.cs index 04b66358ce05..b06cf1af0a53 100644 --- a/src/Cli/dotnet/commands/dotnet-new/DotnetCommandCallbacks.cs +++ b/src/Cli/dotnet/commands/dotnet-new/DotnetCommandCallbacks.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Cli; using Microsoft.DotNet.Tools.Add.PackageReference; using Microsoft.DotNet.Tools.Add.ProjectToProjectReference; diff --git a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/CapabilityExpressionEvaluator.cs b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/CapabilityExpressionEvaluator.cs index 2c52c73634dd..5baac01f5787 100644 --- a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/CapabilityExpressionEvaluator.cs +++ b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/CapabilityExpressionEvaluator.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using LocalizableStrings = Microsoft.DotNet.Tools.New.LocalizableStrings; namespace Microsoft.TemplateEngine.MSBuildEvaluation diff --git a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MSBuildEvaluationResult.cs b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MSBuildEvaluationResult.cs index 8e1eebdd0afe..908ca6d1f4d2 100644 --- a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MSBuildEvaluationResult.cs +++ b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MSBuildEvaluationResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.Build.Evaluation; using LocalizableStrings = Microsoft.DotNet.Tools.New.LocalizableStrings; diff --git a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MSBuildEvaluator.cs b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MSBuildEvaluator.cs index f00a9d1d4a68..951847dcab05 100644 --- a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MSBuildEvaluator.cs +++ b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MSBuildEvaluator.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.Diagnostics; using Microsoft.Build.Evaluation; using Microsoft.DotNet.Cli.Utils; diff --git a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MultiTargetEvaluationResult.cs b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MultiTargetEvaluationResult.cs index 9079b1691aa2..f4a11517abe3 100644 --- a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MultiTargetEvaluationResult.cs +++ b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MultiTargetEvaluationResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.Build.Evaluation; namespace Microsoft.TemplateEngine.MSBuildEvaluation diff --git a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MultipleProjectsEvaluationResult.cs b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MultipleProjectsEvaluationResult.cs index 80433161908b..823f15788651 100644 --- a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MultipleProjectsEvaluationResult.cs +++ b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/MultipleProjectsEvaluationResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using LocalizableStrings = Microsoft.DotNet.Tools.New.LocalizableStrings; namespace Microsoft.TemplateEngine.MSBuildEvaluation diff --git a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/NonSDKStyleEvaluationResult.cs b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/NonSDKStyleEvaluationResult.cs index 8348cda35b50..fac89ff71ee8 100644 --- a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/NonSDKStyleEvaluationResult.cs +++ b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/NonSDKStyleEvaluationResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.Build.Evaluation; namespace Microsoft.TemplateEngine.MSBuildEvaluation diff --git a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/ProjectCapabilityConstraint.cs b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/ProjectCapabilityConstraint.cs index 541f6fea756d..457254013d2a 100644 --- a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/ProjectCapabilityConstraint.cs +++ b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/ProjectCapabilityConstraint.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.Build.Evaluation; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/ProjectContextSymbolSource.cs b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/ProjectContextSymbolSource.cs index 7a077d2555ec..7d5789c39e0a 100644 --- a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/ProjectContextSymbolSource.cs +++ b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/ProjectContextSymbolSource.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.Build.Evaluation; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/SDKStyleEvaluationResult.cs b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/SDKStyleEvaluationResult.cs index 4e9515836399..b05041973b4c 100644 --- a/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/SDKStyleEvaluationResult.cs +++ b/src/Cli/dotnet/commands/dotnet-new/MSBuildEvaluation/SDKStyleEvaluationResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.Build.Evaluation; namespace Microsoft.TemplateEngine.MSBuildEvaluation diff --git a/src/Cli/dotnet/commands/dotnet-new/NewCommandParser.cs b/src/Cli/dotnet/commands/dotnet-new/NewCommandParser.cs index e70fb6147ad9..0f9955f71f4e 100644 --- a/src/Cli/dotnet/commands/dotnet-new/NewCommandParser.cs +++ b/src/Cli/dotnet/commands/dotnet-new/NewCommandParser.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.CommandLine; using System.CommandLine.Parsing; using Microsoft.DotNet.Cli.Utils; diff --git a/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetAddPostActionProcessor.cs b/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetAddPostActionProcessor.cs index 3f128d4c06d1..18e457c310a7 100644 --- a/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetAddPostActionProcessor.cs +++ b/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetAddPostActionProcessor.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Cli.Utils; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; diff --git a/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetRestorePostActionProcessor.cs b/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetRestorePostActionProcessor.cs index 9d1122dad14e..8d14d0a227af 100644 --- a/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetRestorePostActionProcessor.cs +++ b/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetRestorePostActionProcessor.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Cli.Utils; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Cli.PostActionProcessors; diff --git a/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetSlnPostActionProcessor.cs b/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetSlnPostActionProcessor.cs index 9aaf48c4f900..634e0366d264 100644 --- a/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetSlnPostActionProcessor.cs +++ b/src/Cli/dotnet/commands/dotnet-new/PostActions/DotnetSlnPostActionProcessor.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.Diagnostics.CodeAnalysis; using Microsoft.DotNet.Cli.Utils; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/ILaunchSettingsProvider.cs b/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/ILaunchSettingsProvider.cs index 232fccc8813e..09acaa08a0c3 100644 --- a/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/ILaunchSettingsProvider.cs +++ b/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/ILaunchSettingsProvider.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.Text.Json; namespace Microsoft.DotNet.Tools.Run.LaunchSettings diff --git a/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/LaunchSettingsManager.cs b/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/LaunchSettingsManager.cs index 9e4aa74970e1..84540e2919a3 100644 --- a/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/LaunchSettingsManager.cs +++ b/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/LaunchSettingsManager.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.Diagnostics.CodeAnalysis; using System.Text.Json; using Microsoft.DotNet.Cli.Utils; diff --git a/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/ProjectLaunchSettingsProvider.cs b/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/ProjectLaunchSettingsProvider.cs index 80c2035cc056..352b85a04375 100644 --- a/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/ProjectLaunchSettingsProvider.cs +++ b/src/Cli/dotnet/commands/dotnet-run/LaunchSettings/ProjectLaunchSettingsProvider.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.Text.Json; namespace Microsoft.DotNet.Tools.Run.LaunchSettings diff --git a/src/Cli/dotnet/commands/dotnet-sdk/check/BundleOutputWriter.cs b/src/Cli/dotnet/commands/dotnet-sdk/check/BundleOutputWriter.cs index a31777420abc..f187db312cef 100644 --- a/src/Cli/dotnet/commands/dotnet-sdk/check/BundleOutputWriter.cs +++ b/src/Cli/dotnet/commands/dotnet-sdk/check/BundleOutputWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using Microsoft.Deployment.DotNet.Releases; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.NativeWrapper; diff --git a/src/Cli/dotnet/commands/dotnet-sdk/check/RuntimeOutputWriter.cs b/src/Cli/dotnet/commands/dotnet-sdk/check/RuntimeOutputWriter.cs index f88992c2f89e..9258f9b97a0e 100644 --- a/src/Cli/dotnet/commands/dotnet-sdk/check/RuntimeOutputWriter.cs +++ b/src/Cli/dotnet/commands/dotnet-sdk/check/RuntimeOutputWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using Microsoft.Deployment.DotNet.Releases; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.Utils; diff --git a/src/Cli/dotnet/commands/dotnet-sdk/check/SdkOutputWriter.cs b/src/Cli/dotnet/commands/dotnet-sdk/check/SdkOutputWriter.cs index 15f771fafb9e..3917f0cb4caf 100644 --- a/src/Cli/dotnet/commands/dotnet-sdk/check/SdkOutputWriter.cs +++ b/src/Cli/dotnet/commands/dotnet-sdk/check/SdkOutputWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using Microsoft.Deployment.DotNet.Releases; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.Utils; diff --git a/src/Cli/dotnet/commands/dotnet-workload/WorkloadException.cs b/src/Cli/dotnet/commands/dotnet-workload/WorkloadException.cs index 08b2ff2a5280..3f8893878690 100644 --- a/src/Cli/dotnet/commands/dotnet-workload/WorkloadException.cs +++ b/src/Cli/dotnet/commands/dotnet-workload/WorkloadException.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - - namespace Microsoft.DotNet.Workloads.Workload { internal class WorkloadException : Exception diff --git a/src/Cli/dotnet/commands/dotnet-workload/clean/WorkloadCleanCommand.cs b/src/Cli/dotnet/commands/dotnet-workload/clean/WorkloadCleanCommand.cs index 5ccc9998f91f..c2cfbee19b15 100644 --- a/src/Cli/dotnet/commands/dotnet-workload/clean/WorkloadCleanCommand.cs +++ b/src/Cli/dotnet/commands/dotnet-workload/clean/WorkloadCleanCommand.cs @@ -10,8 +10,6 @@ using Microsoft.DotNet.Workloads.Workload.List; using Microsoft.NET.Sdk.WorkloadManifestReader; -#nullable enable - namespace Microsoft.DotNet.Workloads.Workload.Clean { internal class WorkloadCleanCommand : WorkloadCommandBase diff --git a/src/Cli/dotnet/commands/dotnet-workload/install/NullReporter.cs b/src/Cli/dotnet/commands/dotnet-workload/install/NullReporter.cs index 15c7fe8ef83d..25d6453fb118 100644 --- a/src/Cli/dotnet/commands/dotnet-workload/install/NullReporter.cs +++ b/src/Cli/dotnet/commands/dotnet-workload/install/NullReporter.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.Workloads.Workload.Install diff --git a/src/Common/CliFolderPathCalculatorCore.cs b/src/Common/CliFolderPathCalculatorCore.cs index 20c5cd7ecd4a..fad9b944281d 100644 --- a/src/Common/CliFolderPathCalculatorCore.cs +++ b/src/Common/CliFolderPathCalculatorCore.cs @@ -1,12 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. - -//only Microsoft.DotNet.MSBuildSdkResolver (net7.0) has nullables enabled -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive - namespace Microsoft.DotNet.Configurer { static class CliFolderPathCalculatorCore diff --git a/src/Common/EnvironmentVariableNames.cs b/src/Common/EnvironmentVariableNames.cs index 0340aec5ec91..07a19c1fdc8a 100644 --- a/src/Common/EnvironmentVariableNames.cs +++ b/src/Common/EnvironmentVariableNames.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#pragma warning disable IDE0240 // Nullable directive is redundant (when file is included to a project that already enables nullable - -#nullable enable - - namespace Microsoft.DotNet.Cli { static class EnvironmentVariableNames diff --git a/src/Common/PathUtilities.cs b/src/Common/PathUtilities.cs index 5163844ab26c..04e6a6cf78fa 100644 --- a/src/Common/PathUtilities.cs +++ b/src/Common/PathUtilities.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#pragma warning disable IDE0240 // Nullable directive is redundant (when file is included to a project that already enables nullable - -#nullable enable - - namespace Microsoft.DotNet; static class PathUtilities diff --git a/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net472/PublicAPI.Shipped.txt b/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net472/PublicAPI.Shipped.txt index ab058de62d44..5f282702bb03 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net472/PublicAPI.Shipped.txt +++ b/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net472/PublicAPI.Shipped.txt @@ -1 +1 @@ -#nullable enable + \ No newline at end of file diff --git a/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net9.0/PublicAPI.Shipped.txt b/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net9.0/PublicAPI.Shipped.txt index ab058de62d44..5f282702bb03 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net9.0/PublicAPI.Shipped.txt +++ b/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net9.0/PublicAPI.Shipped.txt @@ -1 +1 @@ -#nullable enable + \ No newline at end of file diff --git a/src/Resolvers/Microsoft.DotNet.MSBuildSdkResolver/FXVersion.cs b/src/Resolvers/Microsoft.DotNet.MSBuildSdkResolver/FXVersion.cs index 16f4427b48cd..c1b76e8ed3d4 100644 --- a/src/Resolvers/Microsoft.DotNet.MSBuildSdkResolver/FXVersion.cs +++ b/src/Resolvers/Microsoft.DotNet.MSBuildSdkResolver/FXVersion.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directivee namespace Microsoft.DotNet.MSBuildSdkResolver { // Note: This is SemVer 2.0.0 https://semver.org/spec/v2.0.0.html diff --git a/src/Resolvers/Microsoft.DotNet.NativeWrapper/EnvironmentProvider.cs b/src/Resolvers/Microsoft.DotNet.NativeWrapper/EnvironmentProvider.cs index fa5dd74be789..96c203cc3f4d 100644 --- a/src/Resolvers/Microsoft.DotNet.NativeWrapper/EnvironmentProvider.cs +++ b/src/Resolvers/Microsoft.DotNet.NativeWrapper/EnvironmentProvider.cs @@ -3,9 +3,6 @@ using System.Diagnostics; -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive namespace Microsoft.DotNet.NativeWrapper { public class EnvironmentProvider diff --git a/src/Resolvers/Microsoft.DotNet.NativeWrapper/Interop.cs b/src/Resolvers/Microsoft.DotNet.NativeWrapper/Interop.cs index 98769e68e2df..3ce65639989e 100644 --- a/src/Resolvers/Microsoft.DotNet.NativeWrapper/Interop.cs +++ b/src/Resolvers/Microsoft.DotNet.NativeWrapper/Interop.cs @@ -3,16 +3,6 @@ using System.Reflection; -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive - -// Work around https://github.com/dotnet/roslyn-analyzers/issues/6094 -#pragma warning disable CA1420 - -// Work around https://github.com/dotnet/roslyn-analyzers/issues/6094 -#pragma warning disable CA1420 - namespace Microsoft.DotNet.NativeWrapper { public static partial class Interop diff --git a/src/Resolvers/Microsoft.DotNet.NativeWrapper/Microsoft.DotNet.NativeWrapper.csproj b/src/Resolvers/Microsoft.DotNet.NativeWrapper/Microsoft.DotNet.NativeWrapper.csproj index 6520d5427fcf..c6504d0d68f0 100644 --- a/src/Resolvers/Microsoft.DotNet.NativeWrapper/Microsoft.DotNet.NativeWrapper.csproj +++ b/src/Resolvers/Microsoft.DotNet.NativeWrapper/Microsoft.DotNet.NativeWrapper.csproj @@ -7,6 +7,7 @@ win-x86;win-x64 true Microsoft.DotNet.NativeWrapper + enable diff --git a/src/Resolvers/Microsoft.DotNet.NativeWrapper/NETCoreSdkResolverNativeWrapper.cs b/src/Resolvers/Microsoft.DotNet.NativeWrapper/NETCoreSdkResolverNativeWrapper.cs index 340d5c042f26..160346fbccfc 100644 --- a/src/Resolvers/Microsoft.DotNet.NativeWrapper/NETCoreSdkResolverNativeWrapper.cs +++ b/src/Resolvers/Microsoft.DotNet.NativeWrapper/NETCoreSdkResolverNativeWrapper.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. - -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive - using System.Diagnostics; namespace Microsoft.DotNet.NativeWrapper diff --git a/src/Resolvers/Microsoft.DotNet.NativeWrapper/SdkResolutionResult.cs b/src/Resolvers/Microsoft.DotNet.NativeWrapper/SdkResolutionResult.cs index feeab926c1bd..fac99ad2caa8 100644 --- a/src/Resolvers/Microsoft.DotNet.NativeWrapper/SdkResolutionResult.cs +++ b/src/Resolvers/Microsoft.DotNet.NativeWrapper/SdkResolutionResult.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive - namespace Microsoft.DotNet.NativeWrapper { public class SdkResolutionResult diff --git a/src/Resolvers/Microsoft.DotNet.SdkResolver/Microsoft.DotNet.SdkResolver.csproj b/src/Resolvers/Microsoft.DotNet.SdkResolver/Microsoft.DotNet.SdkResolver.csproj index b5a3bfd041eb..38910eab10bb 100644 --- a/src/Resolvers/Microsoft.DotNet.SdkResolver/Microsoft.DotNet.SdkResolver.csproj +++ b/src/Resolvers/Microsoft.DotNet.SdkResolver/Microsoft.DotNet.SdkResolver.csproj @@ -9,6 +9,7 @@ true Microsoft.DotNet.DotNetSdkResolver + enable diff --git a/src/Resolvers/Microsoft.DotNet.SdkResolver/NETCoreSdkResolver.cs b/src/Resolvers/Microsoft.DotNet.SdkResolver/NETCoreSdkResolver.cs index c7daef849ff2..59ae5f5b187b 100644 --- a/src/Resolvers/Microsoft.DotNet.SdkResolver/NETCoreSdkResolver.cs +++ b/src/Resolvers/Microsoft.DotNet.SdkResolver/NETCoreSdkResolver.cs @@ -4,9 +4,6 @@ using System.Collections.Concurrent; using Microsoft.DotNet.NativeWrapper; -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive namespace Microsoft.DotNet.DotNetSdkResolver { diff --git a/src/Resolvers/Microsoft.DotNet.SdkResolver/VSSettings.cs b/src/Resolvers/Microsoft.DotNet.SdkResolver/VSSettings.cs index 5bd263e08932..e72403408031 100644 --- a/src/Resolvers/Microsoft.DotNet.SdkResolver/VSSettings.cs +++ b/src/Resolvers/Microsoft.DotNet.SdkResolver/VSSettings.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive - using System.Diagnostics; using Microsoft.DotNet.NativeWrapper; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs index de96ac2de97d..dc8976ad53c7 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs @@ -11,7 +11,6 @@ using Microsoft.DotNet.DotNetSdkResolver; #endif -#nullable enable namespace Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver { diff --git a/src/Tasks/Common/Logger.cs b/src/Tasks/Common/Logger.cs index 691c3bb7e299..b586bdfa9070 100644 --- a/src/Tasks/Common/Logger.cs +++ b/src/Tasks/Common/Logger.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive - using System.Diagnostics; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; diff --git a/src/Tasks/Common/Message.cs b/src/Tasks/Common/Message.cs index bb7bbab9ace6..f16e4c12d79c 100644 --- a/src/Tasks/Common/Message.cs +++ b/src/Tasks/Common/Message.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive - namespace Microsoft.NET.Build.Tasks { internal readonly struct Message diff --git a/src/Tasks/Common/TaskBase.cs b/src/Tasks/Common/TaskBase.cs index a8239b3bdd0c..48192ff0b47c 100644 --- a/src/Tasks/Common/TaskBase.cs +++ b/src/Tasks/Common/TaskBase.cs @@ -1,8 +1,5 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#pragma warning disable IDE0240 // Remove redundant nullable directive -#nullable enable -#pragma warning restore IDE0240 // Remove redundant nullable directive using System.Globalization; using Microsoft.Build.Framework; diff --git a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj index c09f4cd532d5..315a95696ae8 100644 --- a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj +++ b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj @@ -27,6 +27,7 @@ true true + enable diff --git a/src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAAllowEmptyTelemetry.cs b/src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAAllowEmptyTelemetry.cs index 38b3dbc1ae4c..3b5677518a0c 100644 --- a/src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAAllowEmptyTelemetry.cs +++ b/src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAAllowEmptyTelemetry.cs @@ -7,8 +7,6 @@ using Microsoft.Build.Utilities; using Xunit; -#nullable enable - namespace Microsoft.NET.Build.Tasks.UnitTests { public class GivenAAllowEmptyTelemetry diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblyMapperTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblyMapperTests.cs index f74473deae16..1ebe43d3e73f 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblyMapperTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblyMapperTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.CodeAnalysis; using Microsoft.DotNet.ApiCompatibility.Mapping; using Microsoft.DotNet.ApiCompatibility.Rules; diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblySetMapperTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblySetMapperTests.cs index 2ccc34d7e8cb..5e3084e2b10e 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblySetMapperTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblySetMapperTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.CodeAnalysis; using Microsoft.DotNet.ApiCompatibility.Mapping; using Microsoft.DotNet.ApiCompatibility.Rules; diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/MemberMapperTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/MemberMapperTests.cs index 00a7d0fff2a3..4d38fc885a54 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/MemberMapperTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/MemberMapperTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.ApiCompatibility.Mapping; using Microsoft.DotNet.ApiCompatibility.Rules; using Moq; diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/NamespaceMapperTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/NamespaceMapperTests.cs index c1a5a139bc12..b8b11b47ee6e 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/NamespaceMapperTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/NamespaceMapperTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.CodeAnalysis; using Microsoft.DotNet.ApiCompatibility.Mapping; using Microsoft.DotNet.ApiCompatibility.Rules; diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/TypeMapperTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/TypeMapperTests.cs index 2d51d7756188..d9c631d44d4e 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/TypeMapperTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/TypeMapperTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.CodeAnalysis; using Microsoft.DotNet.ApiCompatibility.Mapping; using Microsoft.DotNet.ApiCompatibility.Rules; diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Runner/ApiCompatOptionsTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Runner/ApiCompatOptionsTests.cs index c9e788696c83..008184acbf91 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Runner/ApiCompatOptionsTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Runner/ApiCompatOptionsTests.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - - namespace Microsoft.DotNet.ApiCompatibility.Runner.Tests { public class ApiCompatOptionsTests diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Runner/ApiCompatWorkItemTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Runner/ApiCompatWorkItemTests.cs index 8c905c2eeba9..5ce9e0d7a980 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Runner/ApiCompatWorkItemTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Runner/ApiCompatWorkItemTests.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - - namespace Microsoft.DotNet.ApiCompatibility.Runner.Tests { public class ApiCompatWorkItemTests diff --git a/test/Microsoft.DotNet.Cli.Utils.Tests/TypoCorrectionTests.cs b/test/Microsoft.DotNet.Cli.Utils.Tests/TypoCorrectionTests.cs index b58a85fffdcc..de5d5c38b5a2 100644 --- a/test/Microsoft.DotNet.Cli.Utils.Tests/TypoCorrectionTests.cs +++ b/test/Microsoft.DotNet.Cli.Utils.Tests/TypoCorrectionTests.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - - namespace Microsoft.DotNet.Cli.Utils.Tests { public class TypoCorrectionTests diff --git a/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/BodyBlockCSharpSyntaxRewriterTests.cs b/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/BodyBlockCSharpSyntaxRewriterTests.cs index 6cdd51d9a271..0b367620e62d 100644 --- a/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/BodyBlockCSharpSyntaxRewriterTests.cs +++ b/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/BodyBlockCSharpSyntaxRewriterTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.GenAPI.SyntaxRewriter; namespace Microsoft.DotNet.GenAPI.Tests.SyntaxRewriter diff --git a/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/CSharpSyntaxRewriterTestBase.cs b/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/CSharpSyntaxRewriterTestBase.cs index a23b1018bced..8bf24699fdc7 100644 --- a/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/CSharpSyntaxRewriterTestBase.cs +++ b/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/CSharpSyntaxRewriterTestBase.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; diff --git a/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/SingleLineStatementCSharpSyntaxRewriterTests.cs b/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/SingleLineStatementCSharpSyntaxRewriterTests.cs index c3c2e5f2e997..e4b4bc66dd6c 100644 --- a/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/SingleLineStatementCSharpSyntaxRewriterTests.cs +++ b/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/SingleLineStatementCSharpSyntaxRewriterTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.GenAPI.SyntaxRewriter; namespace Microsoft.DotNet.GenAPI.Tests.SyntaxRewriter diff --git a/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/TypeDeclarationCSharpSyntaxRewriterTests.cs b/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/TypeDeclarationCSharpSyntaxRewriterTests.cs index 8ab46c53a721..c2f498c1651c 100644 --- a/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/TypeDeclarationCSharpSyntaxRewriterTests.cs +++ b/test/Microsoft.DotNet.GenAPI.Tests/SyntaxRewriter/TypeDeclarationCSharpSyntaxRewriterTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.GenAPI.SyntaxRewriter; namespace Microsoft.DotNet.GenAPI.Tests.SyntaxRewriter diff --git a/test/Microsoft.NET.TestFramework/InMemoryLoggerProvider.cs b/test/Microsoft.NET.TestFramework/InMemoryLoggerProvider.cs index bddb608c52ca..e97c2ed7e68e 100644 --- a/test/Microsoft.NET.TestFramework/InMemoryLoggerProvider.cs +++ b/test/Microsoft.NET.TestFramework/InMemoryLoggerProvider.cs @@ -1,8 +1,5 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -#nullable enable using Microsoft.Extensions.Logging; diff --git a/test/Microsoft.NET.TestFramework/TestLoggerFactory.cs b/test/Microsoft.NET.TestFramework/TestLoggerFactory.cs index c324cb14d33d..0995a260e6cf 100644 --- a/test/Microsoft.NET.TestFramework/TestLoggerFactory.cs +++ b/test/Microsoft.NET.TestFramework/TestLoggerFactory.cs @@ -1,8 +1,5 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -#nullable enable using Microsoft.Extensions.Logging; diff --git a/test/Microsoft.NET.TestFramework/Utilities/BufferedReporter.cs b/test/Microsoft.NET.TestFramework/Utilities/BufferedReporter.cs index 0412faff72a0..c54607a9f03f 100644 --- a/test/Microsoft.NET.TestFramework/Utilities/BufferedReporter.cs +++ b/test/Microsoft.NET.TestFramework/Utilities/BufferedReporter.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Cli.Utils; namespace Microsoft.NET.TestFramework.Utilities diff --git a/test/Microsoft.NET.TestFramework/XunitLoggerProvider.cs b/test/Microsoft.NET.TestFramework/XunitLoggerProvider.cs index 3b5823e8f7a5..080e6be34b03 100644 --- a/test/Microsoft.NET.TestFramework/XunitLoggerProvider.cs +++ b/test/Microsoft.NET.TestFramework/XunitLoggerProvider.cs @@ -1,8 +1,5 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -#nullable enable using Microsoft.Extensions.Logging; using ILogger = Microsoft.Extensions.Logging.ILogger; diff --git a/test/dotnet.Tests/NuGetSignatureVerificationEnablerTests.cs b/test/dotnet.Tests/NuGetSignatureVerificationEnablerTests.cs index 63f724b7adc6..246abf721406 100644 --- a/test/dotnet.Tests/NuGetSignatureVerificationEnablerTests.cs +++ b/test/dotnet.Tests/NuGetSignatureVerificationEnablerTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using System.Diagnostics; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.Utils; diff --git a/test/dotnet.Tests/dotnet-new/CapabilityExpressionEvaluationTests.cs b/test/dotnet.Tests/dotnet-new/CapabilityExpressionEvaluationTests.cs index 91614ac3d079..a7b24b4b59ba 100644 --- a/test/dotnet.Tests/dotnet-new/CapabilityExpressionEvaluationTests.cs +++ b/test/dotnet.Tests/dotnet-new/CapabilityExpressionEvaluationTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.TemplateEngine.MSBuildEvaluation; namespace Microsoft.DotNet.Cli.New.Tests diff --git a/test/dotnet.Tests/dotnet-new/DotnetAddPostActionTests.cs b/test/dotnet.Tests/dotnet-new/DotnetAddPostActionTests.cs index 6fee5e315574..6ea3150dbf62 100644 --- a/test/dotnet.Tests/dotnet-new/DotnetAddPostActionTests.cs +++ b/test/dotnet.Tests/dotnet-new/DotnetAddPostActionTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Tools.New.PostActionProcessors; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Mocks; diff --git a/test/dotnet.Tests/dotnet-new/DotnetRestorePostActionTests.cs b/test/dotnet.Tests/dotnet-new/DotnetRestorePostActionTests.cs index 23f1347a668c..a4c85a4b31fd 100644 --- a/test/dotnet.Tests/dotnet-new/DotnetRestorePostActionTests.cs +++ b/test/dotnet.Tests/dotnet-new/DotnetRestorePostActionTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Tools.New.PostActionProcessors; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Mocks; diff --git a/test/dotnet.Tests/dotnet-new/DotnetSlnPostActionTests.cs b/test/dotnet.Tests/dotnet-new/DotnetSlnPostActionTests.cs index aed7691ebc8b..9312710159a7 100644 --- a/test/dotnet.Tests/dotnet-new/DotnetSlnPostActionTests.cs +++ b/test/dotnet.Tests/dotnet-new/DotnetSlnPostActionTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Tools.New.PostActionProcessors; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Mocks; diff --git a/test/dotnet.Tests/dotnet-new/SdkInfoProviderTests.cs b/test/dotnet.Tests/dotnet-new/SdkInfoProviderTests.cs index 21ca583c9e66..c6a38738cef4 100644 --- a/test/dotnet.Tests/dotnet-new/SdkInfoProviderTests.cs +++ b/test/dotnet.Tests/dotnet-new/SdkInfoProviderTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Tools.New; using Microsoft.TemplateEngine.Abstractions.Components; diff --git a/test/dotnet.Tests/dotnet-new/WorkloadsInfoProviderTests.cs b/test/dotnet.Tests/dotnet-new/WorkloadsInfoProviderTests.cs index d8657a82cef8..900a419bc8ec 100644 --- a/test/dotnet.Tests/dotnet-new/WorkloadsInfoProviderTests.cs +++ b/test/dotnet.Tests/dotnet-new/WorkloadsInfoProviderTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - using Microsoft.DotNet.Tools.New; using Microsoft.DotNet.Workloads.Workload.Install.InstallRecord; using Microsoft.DotNet.Workloads.Workload.List; From 1240664f5b0418fb7bbb04c80f76916307b8d39f Mon Sep 17 00:00:00 2001 From: Michael Yanni Date: Thu, 28 Mar 2024 09:36:37 -0700 Subject: [PATCH 2/7] Got the Microsoft.NET.Sdk.Publish.Tasks.csproj building with nullable enable. --- src/WebSdk/Publish/Tasks/AppSettingsModel.cs | 4 +- .../Publish/Tasks/AppSettingsTransform.cs | 10 +- src/WebSdk/Publish/Tasks/EnvironmentHelper.cs | 2 +- src/WebSdk/Publish/Tasks/Kudu/KuduMetadata.cs | 8 +- .../Publish/Tasks/Kudu/KuduVfsDeploy.cs | 8 +- .../Publish/Tasks/Kudu/KuduZipDeploy.cs | 6 +- .../Microsoft.NET.Sdk.Publish.Tasks.csproj | 1 + .../Publish/Tasks/MsDeploy/CommonUtility.cs | 552 ++++++++---------- .../Publish/Tasks/MsDeploy/DynamicAssembly.cs | 86 ++- .../Publish/Tasks/MsDeploy/FileSkipData.cs | 9 +- .../Publish/Tasks/MsDeploy/IVSMSDeployTask.cs | 2 +- .../Publish/Tasks/MsDeploy/VSHostObject.cs | 8 +- .../Tasks/MsDeploy/VSMSDeployHostObject.cs | 4 +- .../Tasks/MsDeploy/VsMSDeployObject.cs | 249 ++++---- .../Tasks/Tasks/GenerateEFSQLScripts.cs | 27 +- .../Tasks/Tasks/GenerateEnvTransform.cs | 18 +- .../Publish/Tasks/Tasks/Kudu/KuduDeploy.cs | 27 +- .../Tasks/MsDeploy/CreateMSDeployScript.cs | 16 +- .../Tasks/MsDeploy/CreateManifestFile.cs | 34 +- .../Tasks/MsDeploy/CreateParameterFile.cs | 75 ++- .../Tasks/Tasks/MsDeploy/GetPassword.cs | 6 +- .../Tasks/MsDeploy/ImportParameterFile.cs | 67 +-- .../Publish/Tasks/Tasks/MsDeploy/MSDeploy.cs | 269 ++++----- .../Tasks/MsDeploy/NormalizeServiceUrl.cs | 2 +- .../Tasks/Tasks/MsDeploy/VsMsdeploy.cs | 272 ++++----- .../Tasks/Tasks/TransformAppSettings.cs | 17 +- .../Publish/Tasks/Tasks/TransformWebConfig.cs | 41 +- .../Publish/Tasks/Tasks/ValidateParameter.cs | 6 +- .../Tasks/WebJobs/GenerateRunCommandFile.cs | 12 +- .../Tasks/Xdt/TaskTransformationLogger.cs | 6 +- .../Publish/Tasks/Tasks/Xdt/TransformXml.cs | 28 +- .../Tasks/Tasks/ZipDeploy/CreateZipFile.cs | 12 +- .../Tasks/ZipDeploy/DeploymentResponse.cs | 8 +- .../Tasks/ZipDeploy/HttpClientHelpers.cs | 6 +- .../ZipDeploy/HttpResponseMessageWrapper.cs | 2 +- .../Tasks/Tasks/ZipDeploy/ZipDeploy.cs | 30 +- .../Tasks/ZipDeploy/ZipDeploymentStatus.cs | 14 +- .../Publish/Tasks/WebConfigTelemetry.cs | 14 +- .../Publish/Tasks/WebConfigTransform.cs | 64 +- .../Publish/Tasks/WebJobsCommandGenerator.cs | 6 +- 40 files changed, 941 insertions(+), 1087 deletions(-) diff --git a/src/WebSdk/Publish/Tasks/AppSettingsModel.cs b/src/WebSdk/Publish/Tasks/AppSettingsModel.cs index 4b9baa24ae28..27c93048e9ed 100644 --- a/src/WebSdk/Publish/Tasks/AppSettingsModel.cs +++ b/src/WebSdk/Publish/Tasks/AppSettingsModel.cs @@ -8,9 +8,9 @@ namespace Microsoft.NET.Sdk.Publish.Tasks public partial class AppSettingsModel { [JsonPropertyName("ConnectionStrings")] - public IDictionary ConnectionStrings { get; set; } + public IDictionary? ConnectionStrings { get; set; } [JsonExtensionDataAttribute] - public IDictionary ExtensionData { get; set; } + public IDictionary? ExtensionData { get; set; } } } diff --git a/src/WebSdk/Publish/Tasks/AppSettingsTransform.cs b/src/WebSdk/Publish/Tasks/AppSettingsTransform.cs index b3ac4be3a1d2..dad9899a7fc1 100644 --- a/src/WebSdk/Publish/Tasks/AppSettingsTransform.cs +++ b/src/WebSdk/Publish/Tasks/AppSettingsTransform.cs @@ -25,7 +25,7 @@ public static string GenerateDefaultAppSettingsJsonFile() return tempFileFullPath; } - public static bool UpdateDestinationConnectionStringEntries(string destinationAppSettingsFilePath, ITaskItem[] destinationConnectionStrings) + public static bool UpdateDestinationConnectionStringEntries(string destinationAppSettingsFilePath, ITaskItem[]? destinationConnectionStrings) { if (!File.Exists(destinationAppSettingsFilePath)) { @@ -39,16 +39,16 @@ public static bool UpdateDestinationConnectionStringEntries(string destinationAp string appSettingsJsonContent = File.ReadAllText(destinationAppSettingsFilePath); var appSettingsModel = FromJson(appSettingsJsonContent); - if (appSettingsModel.ConnectionStrings == null) + if (appSettingsModel?.ConnectionStrings == null) { - appSettingsModel.ConnectionStrings = new Dictionary(); + appSettingsModel!.ConnectionStrings = new Dictionary(); } foreach (ITaskItem destinationConnectionString in destinationConnectionStrings) { string key = destinationConnectionString.ItemSpec; string Value = destinationConnectionString.GetMetadata("Value"); - appSettingsModel.ConnectionStrings[key] = Value; + appSettingsModel!.ConnectionStrings[key] = Value; } File.WriteAllText(destinationAppSettingsFilePath, ToJson(appSettingsModel)); @@ -65,7 +65,7 @@ private static string ToJson(T obj) }); } - private static T FromJson(string jsonString) + private static T? FromJson(string jsonString) { return JsonSerializer.Deserialize(jsonString, new JsonSerializerOptions diff --git a/src/WebSdk/Publish/Tasks/EnvironmentHelper.cs b/src/WebSdk/Publish/Tasks/EnvironmentHelper.cs index c0ec36aeb075..1fce2fdb72b3 100644 --- a/src/WebSdk/Publish/Tasks/EnvironmentHelper.cs +++ b/src/WebSdk/Publish/Tasks/EnvironmentHelper.cs @@ -5,7 +5,7 @@ namespace Microsoft.NET.Sdk.Publish.Tasks { public class EnvironmentHelper { - public static string GetEnvironmentVariable(string name) + public static string? GetEnvironmentVariable(string name) { return Environment.GetEnvironmentVariable(name); } diff --git a/src/WebSdk/Publish/Tasks/Kudu/KuduMetadata.cs b/src/WebSdk/Publish/Tasks/Kudu/KuduMetadata.cs index 71e95df7878e..2e862106c2d0 100644 --- a/src/WebSdk/Publish/Tasks/Kudu/KuduMetadata.cs +++ b/src/WebSdk/Publish/Tasks/Kudu/KuduMetadata.cs @@ -5,12 +5,12 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.Kudu { public class KuduConnectionInfo { - public string UserName { get; set; } + public string? UserName { get; set; } - public string Password { get; set; } + public string? Password { get; set; } - public string SiteName { get; set; } + public string? SiteName { get; set; } - public string DestinationUrl { get; set; } + public string? DestinationUrl { get; set; } } } diff --git a/src/WebSdk/Publish/Tasks/Kudu/KuduVfsDeploy.cs b/src/WebSdk/Publish/Tasks/Kudu/KuduVfsDeploy.cs index beaa0b723489..48f05810232b 100644 --- a/src/WebSdk/Publish/Tasks/Kudu/KuduVfsDeploy.cs +++ b/src/WebSdk/Publish/Tasks/Kudu/KuduVfsDeploy.cs @@ -24,11 +24,11 @@ public override string DestinationUrl { get { - return string.Format(ConnectionInfo.DestinationUrl, ConnectionInfo.SiteName, "vfs/site/wwwroot/"); + return string.Format(ConnectionInfo.DestinationUrl!, ConnectionInfo.SiteName, "vfs/site/wwwroot/"); } } - public System.Threading.Tasks.Task DeployAsync(string sourcePath) + public System.Threading.Tasks.Task? DeployAsync(string? sourcePath) { if (!Directory.Exists(sourcePath)) { @@ -46,12 +46,12 @@ public System.Threading.Tasks.Task DeployAsync(string sourcePath) return System.Threading.Tasks.Task.WhenAll(_postTasks); } - private System.Threading.Tasks.Task PostFilesAsync(string file, string sourcePath) + private System.Threading.Tasks.Task PostFilesAsync(string file, string? sourcePath) { return System.Threading.Tasks.Task.Run( async () => { - string relPath = file.Replace(sourcePath, string.Empty); + string relPath = file.Replace(sourcePath!, string.Empty); string relUrl = relPath.Replace(Path.DirectorySeparatorChar, '/'); string apiUrl = DestinationUrl + relUrl; diff --git a/src/WebSdk/Publish/Tasks/Kudu/KuduZipDeploy.cs b/src/WebSdk/Publish/Tasks/Kudu/KuduZipDeploy.cs index ce1b7db559a2..a2817ea0fee6 100644 --- a/src/WebSdk/Publish/Tasks/Kudu/KuduZipDeploy.cs +++ b/src/WebSdk/Publish/Tasks/Kudu/KuduZipDeploy.cs @@ -21,11 +21,11 @@ public override string DestinationUrl { get { - return string.Format(ConnectionInfo.DestinationUrl, ConnectionInfo.SiteName, "zip/site/wwwroot/"); + return string.Format(ConnectionInfo.DestinationUrl!, ConnectionInfo.SiteName, "zip/site/wwwroot/"); } } - public async System.Threading.Tasks.Task DeployAsync(string zipFileFullPath) + public async Task DeployAsync(string? zipFileFullPath) { if (!File.Exists(zipFileFullPath)) @@ -39,7 +39,7 @@ public async System.Threading.Tasks.Task DeployAsync(string zipFileFullPat return success; } - private async System.Threading.Tasks.Task PostZipAsync(string zipFilePath) + private async Task PostZipAsync(string? zipFilePath) { if (string.IsNullOrEmpty(zipFilePath)) { diff --git a/src/WebSdk/Publish/Tasks/Microsoft.NET.Sdk.Publish.Tasks.csproj b/src/WebSdk/Publish/Tasks/Microsoft.NET.Sdk.Publish.Tasks.csproj index dd4fd7975a05..8cd0ff60b39b 100644 --- a/src/WebSdk/Publish/Tasks/Microsoft.NET.Sdk.Publish.Tasks.csproj +++ b/src/WebSdk/Publish/Tasks/Microsoft.NET.Sdk.Publish.Tasks.csproj @@ -4,6 +4,7 @@ $(RepoRoot)\src\WebSdk\Publish\ Microsoft.NET.Sdk.Publish $(Configuration)\Sdks\$(PackageId)\tools + enable diff --git a/src/WebSdk/Publish/Tasks/MsDeploy/CommonUtility.cs b/src/WebSdk/Publish/Tasks/MsDeploy/CommonUtility.cs index 793960d7ce51..028864a6ea50 100644 --- a/src/WebSdk/Publish/Tasks/MsDeploy/CommonUtility.cs +++ b/src/WebSdk/Publish/Tasks/MsDeploy/CommonUtility.cs @@ -8,24 +8,18 @@ /// /// Copyright(c) 2006 Microsoft Corporation ///-------------------------------------------------------------------------------------------- + +using System.Diagnostics; +using System.Reflection; +using System.Xml; +using Microsoft.NET.Sdk.Publish.Tasks.Properties; +using CultureInfo = System.Globalization.CultureInfo; +using Framework = Microsoft.Build.Framework; +using RegularExpressions = System.Text.RegularExpressions; +using Utilities = Microsoft.Build.Utilities; + namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy { - using System.Diagnostics; - using System.IO; - using System.Linq; - using System.Reflection; - using System.Xml; - using Microsoft.NET.Sdk.Publish.Tasks.Properties; - using CultureInfo = System.Globalization.CultureInfo; - using Framework = Microsoft.Build.Framework; - using Generic = System.Collections.Generic; - using IO = System.IO; - using RegularExpressions = System.Text.RegularExpressions; - using Text = System.Text; - using Utilities = Microsoft.Build.Utilities; - using Win32 = Microsoft.Win32; - using Xml = System.Xml; - internal enum PipelineMetadata { // @@ -42,8 +36,6 @@ internal enum PipelineMetadata Category, }; - - internal enum ReplaceRuleMetadata { // @@ -64,9 +56,6 @@ internal enum ReplaceRuleMetadata Replace, }; - - - internal enum SkipRuleMetadata { // @@ -104,7 +93,6 @@ internal enum DeclareParameterMetadata Tags, }; - internal enum ExistingDeclareParameterMetadata { // @@ -136,17 +124,17 @@ internal enum SqlCommandVariableMetaData Value, IsDeclared, SourcePath, - SourcePath_RegExExcaped, + SourcePath_RegExEscaped, DestinationGroup } - - internal enum ExistingParameterValiationMetadata + internal enum ExistingParameterValidationMetadata { Element, Kind, ValidationString, } + internal enum SyncParameterMetadata { // @@ -182,9 +170,6 @@ internal enum ExistingSyncParameterMetadata Value, }; - - - internal class ParameterInfo { public string Name; @@ -206,7 +191,6 @@ public ProviderOption(string factorName, string parameterName, string parameterS } } - internal class ParameterInfoWithEntry : ParameterInfo { //Kind, @@ -235,16 +219,13 @@ public ParameterInfoWithEntry(string name, string value, string kind, string sco Tags = tags; Element = element; ValidationString = validationString; - } } - internal static class Utility { - static System.Collections.Generic.Dictionary m_wellKnownNamesDict = null; - static System.Collections.Generic.Dictionary m_wellKnownNamesMsdeployDict = null; - + static Dictionary? s_wellKnownNamesDict = null; + static Dictionary? s_wellKnownNamesMsdeployDict = null; internal enum IISExpressMetadata { @@ -253,8 +234,7 @@ internal enum IISExpressMetadata public static bool IsInternalMsdeployWellKnownItemMetadata(string name) { - IISExpressMetadata iisExpressMetadata; - if (Enum.TryParse(name, out iisExpressMetadata)) + if (Enum.TryParse(name, out _)) { return true; } @@ -268,7 +248,7 @@ public static bool IsInternalMsdeployWellKnownItemMetadata(string name) // Utility function to filter out known MSBuild Metatdata public static bool IsMSBuildWellKnownItemMetadata(string name) { - if (m_wellKnownNamesDict == null) + if (s_wellKnownNamesDict == null) { string[] wellKnownNames = { @@ -291,19 +271,19 @@ public static bool IsMSBuildWellKnownItemMetadata(string name) "DefiningProjectFullPath", "DefiningProjectName" }; - m_wellKnownNamesDict = new System.Collections.Generic.Dictionary(wellKnownNames.GetLength(0), StringComparer.OrdinalIgnoreCase); + s_wellKnownNamesDict = new Dictionary(wellKnownNames.GetLength(0), StringComparer.OrdinalIgnoreCase); foreach (string wellKnownName in wellKnownNames) { - m_wellKnownNamesDict.Add(wellKnownName, null); + s_wellKnownNamesDict.Add(wellKnownName, null); } } - return m_wellKnownNamesDict.ContainsKey(name); + return s_wellKnownNamesDict.ContainsKey(name); } public static bool IsMsDeployWellKnownLocationInfo(string name) { - if (m_wellKnownNamesMsdeployDict == null) + if (s_wellKnownNamesMsdeployDict == null) { string[] wellKnownNames = { @@ -316,44 +296,44 @@ public static bool IsMsDeployWellKnownLocationInfo(string name) "authType", "prefetchPayload", }; - m_wellKnownNamesMsdeployDict = new System.Collections.Generic.Dictionary(wellKnownNames.GetLength(0), StringComparer.OrdinalIgnoreCase); + s_wellKnownNamesMsdeployDict = new Dictionary(wellKnownNames.GetLength(0), StringComparer.OrdinalIgnoreCase); foreach (string wellKnownName in wellKnownNames) { - m_wellKnownNamesMsdeployDict.Add(wellKnownName, null); + s_wellKnownNamesMsdeployDict.Add(wellKnownName, null); } } - return m_wellKnownNamesMsdeployDict.ContainsKey(name); + return s_wellKnownNamesMsdeployDict.ContainsKey(name); } - static Text.StringBuilder m_stringBuilder = null; + static StringBuilder? s_stringBuilder = null; /// - /// commong utility for Clean share common builder + /// common utility for Clean share common builder /// - private static Text.StringBuilder StringBuilder + private static StringBuilder StringBuilder { get { - if (m_stringBuilder == null) + if (s_stringBuilder == null) { - m_stringBuilder = new System.Text.StringBuilder(1024); + s_stringBuilder = new StringBuilder(1024); } - return m_stringBuilder; + return s_stringBuilder; } } /// /// This is the simple share clean build. Since this is an share instance - /// make sure you don't call this on complex operation or it will be zero out unexpectly - /// Use this you need to be simple function which doesn't call any functiont that use this property + /// make sure you don't call this on complex operation or it will be zero out unexpectedly + /// Use this you need to be simple function which doesn't call any function that use this property /// Sde dev10 bug 699893 /// - public static Text.StringBuilder CleanStringBuilder + public static StringBuilder CleanStringBuilder { get { - Text.StringBuilder sb = StringBuilder; + StringBuilder sb = StringBuilder; sb.Remove(0, sb.Length); return sb; } @@ -402,7 +382,7 @@ public enum IisMainVersion /// Return true if MSDeploy is installed /// private static bool _isMSDeployInstalled = false; - private static string _strErrorMessage = null; + private static string? _strErrorMessage = null; public static bool IsMSDeployInstalled { get @@ -421,7 +401,7 @@ public static bool IsMSDeployInstalled { _isMSDeployInstalled = CheckMSDeploymentVersion(); } - catch (System.IO.FileNotFoundException ex) + catch (FileNotFoundException ex) { _strErrorMessage = string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_MSDEPLOYLOADFAIL, Resources.VSMSDEPLOY_MSDEPLOY32bit, @@ -439,7 +419,7 @@ public static bool IsMSDeployInstalled /// /// Return true if MSDeploy is installed, and report an error to task.Log if it's not /// - public static bool CheckMSDeploymentVersion(Utilities.TaskLoggingHelper log, out string errorMessage) + public static bool CheckMSDeploymentVersion(Utilities.TaskLoggingHelper log, out string? errorMessage) { errorMessage = null; if (!IsMSDeployInstalled) @@ -454,15 +434,14 @@ public static bool CheckMSDeploymentVersion(Utilities.TaskLoggingHelper log, out } } - /// /// Utility function to save the given XML document in UTF8 and indented /// /// - public static void SaveDocument(Xml.XmlDocument document, string outputFileName, System.Text.Encoding encode) + public static void SaveDocument(XmlDocument document, string outputFileName, Encoding encode) { #if NET472 - Xml.XmlTextWriter textWriter = new(outputFileName, encode) + XmlTextWriter textWriter = new(outputFileName, encode) { Formatting = Formatting.Indented }; @@ -478,7 +457,7 @@ public static void SaveDocument(Xml.XmlDocument document, string outputFileName, xmldecl.Encoding = "utf-8"; // Add the new node to the document. - XmlElement root = document.DocumentElement; + XmlElement? root = document.DocumentElement; document.InsertBefore(xmldecl, root); document.Save(writer); @@ -490,7 +469,7 @@ public static void SaveDocument(Xml.XmlDocument document, string outputFileName, /// /// Utility to check the MinimumVersion of Msdeploy /// - static string s_strMinimumVersion; + static string? s_strMinimumVersion; /// /// Helper function to determine installed MSDeploy version @@ -498,14 +477,14 @@ public static void SaveDocument(Xml.XmlDocument document, string outputFileName, private static bool CheckMSDeploymentVersion() { // Find the MinimumVersionRequirement - System.Version currentMinVersion; + Version currentMinVersion; if (!string.IsNullOrEmpty(s_strMinimumVersion)) { - currentMinVersion = new System.Version(s_strMinimumVersion); + currentMinVersion = new Version(s_strMinimumVersion); } else { - currentMinVersion = new System.Version(7, 1, 614); // current drop + currentMinVersion = new Version(7, 1, 614); // current drop { string strMinimumVersion = string.Empty; #if NET472 @@ -529,7 +508,7 @@ private static bool CheckMSDeploymentVersion() #endif if (!string.IsNullOrEmpty(s_strMinimumVersion)) { - currentMinVersion = new System.Version(strMinimumVersion); + currentMinVersion = new Version(strMinimumVersion); } else { @@ -541,9 +520,9 @@ private static bool CheckMSDeploymentVersion() Debug.Assert(MSWebDeploymentAssembly.DynamicAssembly != null && MSWebDeploymentAssembly.DynamicAssembly.Assembly != null); if (MSWebDeploymentAssembly.DynamicAssembly != null && MSWebDeploymentAssembly.DynamicAssembly.Assembly != null) { - System.Reflection.AssemblyName assemblyName = MSWebDeploymentAssembly.DynamicAssembly.Assembly.GetName(); - System.Version minVersion = new(currentMinVersion.Major, currentMinVersion.Minor); - System.Version assemblyVersion = assemblyName.Version; // assembly version only accurate to the minor version + AssemblyName assemblyName = MSWebDeploymentAssembly.DynamicAssembly.Assembly.GetName(); + Version minVersion = new(currentMinVersion.Major, currentMinVersion.Minor); + Version? assemblyVersion = assemblyName.Version; // assembly version only accurate to the minor version bool fMinVersionNotMeet = false; if (assemblyVersion < minVersion) @@ -569,7 +548,7 @@ private static bool CheckMSDeploymentVersion() _strErrorMessage = string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_MSDEPLOYLOADFAIL, Resources.VSMSDEPLOY_MSDEPLOY32bit, Resources.VSMSDEPLOY_MSDEPLOY64bit, - new System.Version(), + new Version(), currentMinVersion); #else _strErrorMessage = string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_MSDEPLOYLOADFAIL, @@ -590,7 +569,7 @@ private static bool CheckMSDeploymentVersion() /// /// /// - public static string GetNodeFromProjectFile(Xml.XmlDocument doc, Xml.XmlNamespaceManager xmlnsManager, + public static string? GetNodeFromProjectFile(XmlDocument doc, XmlNamespaceManager xmlnsManager, string xmlPath, string defaultNamespace) { if (doc == null) @@ -603,7 +582,7 @@ public static string GetNodeFromProjectFile(Xml.XmlDocument doc, Xml.XmlNamespac searchPath = regex.Replace(xmlPath, defaultNamespace + @":$1"); } - Xml.XmlNode xmlNode = doc.SelectSingleNode(searchPath, xmlnsManager); + XmlNode xmlNode = doc.SelectSingleNode(searchPath, xmlnsManager); if (xmlNode != null) { return xmlNode.InnerText; @@ -617,7 +596,7 @@ public static string GetNodeFromProjectFile(Xml.XmlDocument doc, Xml.XmlNamespac /// /// /// - internal static void BuildArgumentsBaseOnEnumTypeName(Framework.ITaskItem item, System.Collections.Generic.List arguments, System.Type enumType, string valueQuote) + internal static void BuildArgumentsBaseOnEnumTypeName(Framework.ITaskItem item, List arguments, Type enumType, string? valueQuote) { string[] enumNames = Enum.GetNames(enumType); foreach (string enumName in enumNames) @@ -635,7 +614,7 @@ internal static void BuildArgumentsBaseOnEnumTypeName(Framework.ITaskItem item, } } - internal static string AlternativeQuote(string valueQuote) + internal static string AlternativeQuote(string? valueQuote) { if (string.IsNullOrEmpty(valueQuote) || valueQuote == "\"") { @@ -648,13 +627,13 @@ internal static string AlternativeQuote(string valueQuote) } public static char[] s_specialCharactersForCmd = @"&()[]{}^=;!'+,`~".ToArray(); - internal static string PutValueInQuote(string value, string quote) + internal static string PutValueInQuote(string value, string? quote) { if (string.IsNullOrEmpty(quote)) { - if (value != null && value.IndexOfAny(s_specialCharactersForCmd) >= 0) + if (value is not null && value.IndexOfAny(s_specialCharactersForCmd) >= 0) { - // any command line special characters, we use doubld quote by default + // any command line special characters, we use double quote by default quote = "\""; } else @@ -664,7 +643,7 @@ internal static string PutValueInQuote(string value, string quote) } if (!string.IsNullOrEmpty(value)) { - if (value.Contains(quote)) + if (value!.Contains(quote)) { quote = AlternativeQuote(quote); } @@ -674,10 +653,9 @@ internal static string PutValueInQuote(string value, string quote) return string.Concat(quote, value, quote); } - - public static bool IsOneof(string source, string[] listOfItems, System.StringComparison comparsion) + public static bool IsOneOf(string source, string[] listOfItems, StringComparison comparsion) { - if (listOfItems != null && !string.IsNullOrEmpty(source)) + if (listOfItems is not null && !string.IsNullOrEmpty(source)) { foreach (string item in listOfItems) { @@ -691,7 +669,7 @@ public static bool IsOneof(string source, string[] listOfItems, System.StringCom } /// - /// Utiilty function to prompt commom end of Execution message for msdeploy.exe + /// Utility function to prompt common end of Execution message for msdeploy.exe /// /// /// @@ -707,20 +685,20 @@ public static void MsDeployExeEndOfExecuteMessage(bool bSuccess, string destType if (bSuccess) { #if NET472 - if (IsOneof(destType, packageArchivedir, StringComparison.InvariantCultureIgnoreCase)) + if (IsOneOf(destType, packageArchivedir, StringComparison.InvariantCultureIgnoreCase)) #else - if (IsOneof(destType, packageArchivedir, StringComparison.OrdinalIgnoreCase)) + if (IsOneOf(destType, packageArchivedir, StringComparison.OrdinalIgnoreCase)) #endif { //strip off the trailing slash, so IO.Path.GetDirectoryName/GetFileName will return values correctly destRoot = StripOffTrailingSlashes(destRoot); - string dir = Path.GetDirectoryName(destRoot); + string? dir = Path.GetDirectoryName(destRoot); string dirUri = ConvertAbsPhysicalPathToAbsUriPath(dir); #if NET472 - if (IsOneof(destType, ArchiveDirOnly, StringComparison.InvariantCultureIgnoreCase)) + if (IsOneOf(destType, ArchiveDirOnly, StringComparison.InvariantCultureIgnoreCase)) #else - if (IsOneof(destType, ArchiveDirOnly, StringComparison.OrdinalIgnoreCase)) + if (IsOneOf(destType, ArchiveDirOnly, StringComparison.OrdinalIgnoreCase)) #endif strSucceedFailMsg = string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_SucceedArchiveDir, string.IsNullOrEmpty(dirUri) ? destRoot : dirUri); else @@ -735,9 +713,9 @@ public static void MsDeployExeEndOfExecuteMessage(bool bSuccess, string destType else { #if NET472 - if (IsOneof(destType, packageArchivedir, StringComparison.InvariantCultureIgnoreCase)) + if (IsOneOf(destType, packageArchivedir, StringComparison.InvariantCultureIgnoreCase)) #else - if (IsOneof(destType, packageArchivedir, StringComparison.OrdinalIgnoreCase)) + if (IsOneOf(destType, packageArchivedir, StringComparison.OrdinalIgnoreCase)) #endif { strSucceedFailMsg = Resources.VSMSDEPLOY_FailedPackage; @@ -756,7 +734,7 @@ public static void MsDeployExeEndOfExecuteMessage(bool bSuccess, string destType } /// - /// Utiilty function to prompt commom end of Execution message + /// Utility function to prompt common end of Execution message /// /// /// @@ -765,8 +743,8 @@ public static void MsDeployExeEndOfExecuteMessage(bool bSuccess, string destType public static void MsDeployEndOfExecuteMessage(bool bSuccess, string destType, string destRoot, Utilities.TaskLoggingHelper Log) { // Deployment.DeploymentWellKnownProvider wellKnownProvider = Deployment.DeploymentWellKnownProvider.Unknown; - System.Type DeploymentWellKnownProviderType = MSWebDeploymentAssembly.DynamicAssembly.GetType(MSDeploy.TypeName.DeploymentWellKnownProvider); - dynamic wellKnownProvider = MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, "Unknown"); + Type? DeploymentWellKnownProviderType = MSWebDeploymentAssembly.DynamicAssembly?.GetType(MSDeploy.TypeName.DeploymentWellKnownProvider); + dynamic? wellKnownProvider = MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, "Unknown"); #if NET472 if (string.Compare(destType, MSDeploy.Provider.DbDacFx, StringComparison.InvariantCultureIgnoreCase) != 0) #else @@ -775,7 +753,7 @@ public static void MsDeployEndOfExecuteMessage(bool bSuccess, string destType, s { try { - wellKnownProvider = Enum.Parse(DeploymentWellKnownProviderType, destType, true); + wellKnownProvider = Enum.Parse(DeploymentWellKnownProviderType!, destType, true); } catch { @@ -786,15 +764,15 @@ public static void MsDeployEndOfExecuteMessage(bool bSuccess, string destType, s string strSucceedFailMsg; if (bSuccess) { - if (wellKnownProvider.Equals(MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.ArchiveDir)) || - wellKnownProvider.Equals(MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.Package))) + if (wellKnownProvider?.Equals(MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.ArchiveDir)) ?? false || + wellKnownProvider?.Equals(MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.Package)) ?? false) { //strip off the trailing slash, so IO.Path.GetDirectoryName/GetFileName will return values correctly destRoot = StripOffTrailingSlashes(destRoot); - string dir = Path.GetDirectoryName(destRoot); + string? dir = Path.GetDirectoryName(destRoot); string dirUri = ConvertAbsPhysicalPathToAbsUriPath(dir); - if (wellKnownProvider.Equals(MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.ArchiveDir))) + if (wellKnownProvider?.Equals(MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.ArchiveDir)) ?? false) strSucceedFailMsg = string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_SucceedArchiveDir, string.IsNullOrEmpty(dirUri) ? destRoot : dirUri); else strSucceedFailMsg = string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_SucceedPackage, Path.GetFileName(destRoot), string.IsNullOrEmpty(dirUri) ? destRoot : dirUri); @@ -804,13 +782,11 @@ public static void MsDeployEndOfExecuteMessage(bool bSuccess, string destType, s { strSucceedFailMsg = Resources.VSMSDEPLOY_SucceedDeploy; } - - } else { - if (wellKnownProvider.Equals(MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.ArchiveDir)) || - wellKnownProvider.Equals(MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.Package))) + if (wellKnownProvider?.Equals(MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.ArchiveDir)) ?? false || + wellKnownProvider?.Equals(MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.Package)) ?? false) { strSucceedFailMsg = Resources.VSMSDEPLOY_FailedPackage; } @@ -827,12 +803,12 @@ public static void MsDeployEndOfExecuteMessage(bool bSuccess, string destType, s } } - public static string ConvertAbsPhysicalPathToAbsUriPath(string physicalPath) + public static string ConvertAbsPhysicalPathToAbsUriPath(string? physicalPath) { string absUriPath = string.Empty; try { - System.Uri uri = new(physicalPath); + Uri uri = new(physicalPath!); if (uri.IsAbsoluteUri) absUriPath = uri.AbsoluteUri; } @@ -843,7 +819,7 @@ public static string ConvertAbsPhysicalPathToAbsUriPath(string physicalPath) // utility function to add the replace rule for the option public static void AddReplaceRulesToOptions(/*Deployment.DeploymentRuleCollection*/ dynamic syncConfigRules, Framework.ITaskItem[] replaceRuleItems) { - if (syncConfigRules != null && replaceRuleItems != null)// Dev10 bug 496639 foreach will throw the exception if the replaceRuleItem is null + if (syncConfigRules is not null && replaceRuleItems is not null)// Dev10 bug 496639 foreach will throw the exception if the replaceRuleItem is null { foreach (Framework.ITaskItem item in replaceRuleItems) { @@ -855,19 +831,16 @@ public static void AddReplaceRulesToOptions(/*Deployment.DeploymentRuleCollectio string scopeAttributeValue = item.GetMetadata(ReplaceRuleMetadata.ScopeAttributeValue.ToString()); string targetAttributeName = item.GetMetadata(ReplaceRuleMetadata.TargetAttributeName.ToString()); - ///*Deployment.DeploymentReplaceRule*/ dynamic replaceRule = // new Deployment.DeploymentReplaceRule(ruleName, objectName, scopeAttributeName, // scopeAttributeValue, targetAttributeName, matchRegularExpression, replaceWith); - /*Deployment.DeploymentReplaceRule*/ - dynamic replaceRule = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentReplaceRule", + dynamic? replaceRule = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentReplaceRule", new object[]{ruleName, objectName, scopeAttributeName, scopeAttributeValue, targetAttributeName, matchRegularExpression, replaceWith}); - - syncConfigRules.Add(replaceRule); + syncConfigRules!.Add(replaceRule); } } } @@ -879,13 +852,13 @@ public static void AddReplaceRulesToOptions(/*Deployment.DeploymentRuleCollectio /// /// /// - internal static void AdjsutSkipDirectives(/*Deployment.DeploymentBaseOptions*/ dynamic baseOptions, Generic.List stringList, bool enabled, Utilities.TaskLoggingHelper log) + internal static void AdjustSkipDirectives(/*Deployment.DeploymentBaseOptions*/ dynamic baseOptions, List stringList, bool enabled, Utilities.TaskLoggingHelper log) { - if (stringList != null && baseOptions != null) + if (stringList is not null && baseOptions is not null) { foreach (string name in stringList) { - foreach (/*Deployment.DeploymentSkipDirective*/ dynamic skipDirective in baseOptions.SkipDirectives) + foreach (/*Deployment.DeploymentSkipDirective*/ dynamic skipDirective in baseOptions!.SkipDirectives) { if (string.Compare(skipDirective.Name, name, StringComparison.OrdinalIgnoreCase) == 0) { @@ -905,13 +878,13 @@ internal static void AdjsutSkipDirectives(/*Deployment.DeploymentBaseOptions*/ d // utility function to add the skip rule for the option public static void AddSkipDirectiveToBaseOptions(/*Deployment.DeploymentBaseOptions*/ dynamic baseOptions, Framework.ITaskItem[] skipRuleItems, - Generic.List enableSkipDirectiveList, - Generic.List disableSkipDirectiveList, + List enableSkipDirectiveList, + List disableSkipDirectiveList, Utilities.TaskLoggingHelper log) { - if (baseOptions != null && skipRuleItems != null) + if (baseOptions is not null && skipRuleItems is not null) { - System.Collections.Generic.List arguments = new(6); + List arguments = new(6); foreach (Framework.ITaskItem item in skipRuleItems) { @@ -923,29 +896,28 @@ public static void AddSkipDirectiveToBaseOptions(/*Deployment.DeploymentBaseOpti ///*Deployment.DeploymentSkipDirective*/ dynamic skipDirective = new Microsoft.Web.Deployment.DeploymentSkipDirective(name, string.Join(",", arguments.ToArray()), true); /*Deployment.DeploymentSkipDirective*/ - dynamic skipDirective = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentSkipDirective", new object[] { name, string.Join(",", arguments.ToArray()), true }); - baseOptions.SkipDirectives.Add(skipDirective); + dynamic? skipDirective = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentSkipDirective", new object[] { name, string.Join(",", arguments.ToArray()), true }); + baseOptions!.SkipDirectives.Add(skipDirective); } } - AdjsutSkipDirectives(baseOptions, enableSkipDirectiveList, true, log); - AdjsutSkipDirectives(baseOptions, disableSkipDirectiveList, false, log); + AdjustSkipDirectives(baseOptions, enableSkipDirectiveList, true, log); + AdjustSkipDirectives(baseOptions, disableSkipDirectiveList, false, log); } } - /// /// Utility to add single DeclareParameter to the list /// /// /// - public static void AddDeclarParameterToOptions(/*VSMSDeploySyncOption*/ dynamic vSMSDeploySyncOption, Framework.ITaskItem item) + public static void AddDeclareParameterToOptions(/*VSMSDeploySyncOption*/ dynamic vSMSDeploySyncOption, Framework.ITaskItem item) { - if (item != null && vSMSDeploySyncOption != null) + if (item is not null && vSMSDeploySyncOption is not null) { string name = item.ItemSpec; - string elemment = item.GetMetadata(ExistingParameterValiationMetadata.Element.ToString()); - if (string.IsNullOrEmpty(elemment)) - elemment = "parameterEntry"; + string element = item.GetMetadata(ExistingParameterValidationMetadata.Element.ToString()); + if (string.IsNullOrEmpty(element)) + element = "parameterEntry"; string kind = item.GetMetadata(DeclareParameterMetadata.Kind.ToString()); string scope = item.GetMetadata(DeclareParameterMetadata.Scope.ToString()); string matchRegularExpression = item.GetMetadata(DeclareParameterMetadata.Match.ToString()); @@ -953,7 +925,7 @@ public static void AddDeclarParameterToOptions(/*VSMSDeploySyncOption*/ dynamic string defaultValue = item.GetMetadata(DeclareParameterMetadata.DefaultValue.ToString()); string tags = item.GetMetadata(DeclareParameterMetadata.Tags.ToString()); - dynamic deploymentSyncParameter = null; + dynamic? deploymentSyncParameter = null; // the following have out argument, can't use dynamic on it // vSMSDeploySyncOption.DeclaredParameters.TryGetValue(name, out deploymentSyncParameter); MSWebDeploymentAssembly.DeploymentTryGetValueContains(vSMSDeploySyncOption.DeclaredParameters, name, out deploymentSyncParameter); @@ -961,15 +933,15 @@ public static void AddDeclarParameterToOptions(/*VSMSDeploySyncOption*/ dynamic if (deploymentSyncParameter == null) { deploymentSyncParameter = - MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameter", new object[] { name, description, defaultValue, tags }); + MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameter", new object[] { name, description, defaultValue, tags }); vSMSDeploySyncOption.DeclaredParameters.Add(deploymentSyncParameter); } if (!string.IsNullOrEmpty(kind)) { - if (string.Compare(elemment, "parameterEntry", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(element, "parameterEntry", StringComparison.OrdinalIgnoreCase) == 0) { bool fAddEntry = true; - foreach (dynamic entry in deploymentSyncParameter.Entries) + foreach (dynamic entry in deploymentSyncParameter?.Entries ?? Array.Empty()) { if (scope.Equals(entry.Scope) && matchRegularExpression.Equals(entry.Match) && @@ -980,38 +952,37 @@ public static void AddDeclarParameterToOptions(/*VSMSDeploySyncOption*/ dynamic } if (fAddEntry) { - dynamic parameterEntry = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameterEntry", + dynamic? parameterEntry = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameterEntry", new object[] { kind, scope, matchRegularExpression, string.Empty }); - deploymentSyncParameter.Add(parameterEntry); + deploymentSyncParameter?.Add(parameterEntry); } } - else if (string.Compare(elemment, "parameterValidation", StringComparison.OrdinalIgnoreCase) == 0) + else if (string.Compare(element, "parameterValidation", StringComparison.OrdinalIgnoreCase) == 0) { // this is bogus assertion because by default msdeploy always setup the validation which is never be null // System.Diagnostics.Debug.Assert(deploymentSyncParameter.Validation == null, "deploymentSyncParameter.Validation is already set"); - string validationString = item.GetMetadata(ExistingParameterValiationMetadata.ValidationString.ToString()); - - object validationKindNone = MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue("Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind", "None"); - dynamic validationKind = validationKindNone; - System.Type validationKindType = validationKind.GetType(); - dynamic currentvalidationKind = validationKindNone; + string validationString = item.GetMetadata(ExistingParameterValidationMetadata.ValidationString.ToString()); + object? validationKindNone = MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue("Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind", "None"); + dynamic? validationKind = validationKindNone; + Type? validationKindType = validationKind?.GetType(); string[] validationKinds = kind.Split(new char[] { ',' }); foreach (string strValidationKind in validationKinds) { - if (MSWebDeploymentAssembly.DynamicAssembly.TryGetEnumValue("Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind", strValidationKind, out currentvalidationKind)) + dynamic? currentValidationKind; + if (MSWebDeploymentAssembly.DynamicAssembly?.TryGetEnumValue("Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind", strValidationKind, out currentValidationKind) ?? false) { - validationKind = Enum.ToObject(validationKindType, ((int)(validationKind)) | ((int)(currentvalidationKind))); + validationKind = Enum.ToObject(validationKindType!, ((int)(validationKind)) | ((int)(currentValidationKind))); } } // dynamic doesn't compare, since this is enum, cast to int to compare - if ((int)validationKind != (int)validationKindNone) + if ((int)validationKind != (int)(validationKindNone ?? 0)) { // due to the reflection the we can't // $exception {"Cannot implicitly convert type 'object' to 'Microsoft.Web.Deployment.DeploymentSyncParameterValidation'. An explicit conversion exists (are you missing a cast?)"} System.Exception {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException} - object parameterValidation = - MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameterValidation", new object[] { validationKind, validationString }); + object? parameterValidation = + MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameterValidation", new object[] { validationKind!, validationString }); SetDynamicProperty(deploymentSyncParameter, "Validation", parameterValidation); } } @@ -1026,12 +997,11 @@ public static void AddDeclarParameterToOptions(/*VSMSDeploySyncOption*/ dynamic /// /// /// - public static void SetDynamicProperty(dynamic thisObj, string propertyName, object value) + public static void SetDynamicProperty(dynamic? thisObj, string propertyName, object value) { - thisObj.GetType().GetProperty(propertyName).SetValue(thisObj, value, null); + thisObj?.GetType().GetProperty(propertyName).SetValue(thisObj, value, null); } - /// /// Utility function to add DeclareParameter in line /// @@ -1039,26 +1009,25 @@ public static void SetDynamicProperty(dynamic thisObj, string propertyName, obje /// public static void AddDeclareParametersToOptions(/*VSMSDeploySyncOption*/ dynamic vSMSDeploySyncOption, Framework.ITaskItem[] originalItems, bool fOptimisticPickNextDefaultValue) { - System.Collections.Generic.IList items = SortParametersTaskItems(originalItems, fOptimisticPickNextDefaultValue, DeclareParameterMetadata.DefaultValue.ToString()); - if (vSMSDeploySyncOption != null && items != null) + IList items = SortParametersTaskItems(originalItems, fOptimisticPickNextDefaultValue, DeclareParameterMetadata.DefaultValue.ToString()); + if (vSMSDeploySyncOption is not null && items is not null) { foreach (Framework.ITaskItem item in items) { - AddDeclarParameterToOptions(vSMSDeploySyncOption, item); + AddDeclareParameterToOptions(vSMSDeploySyncOption, item); } } } - // MSDeploy change -- Deprecate ///// - ///// Utility function to support DeclarParametersFromFile + ///// Utility function to support DeclareParametersFromFile ///// ///// ///// public static void AddImportDeclareParametersFileOptions(/*VSMSDeploySyncOption*/ dynamic vSMSDeploySyncOption, Framework.ITaskItem[] items) { - if (vSMSDeploySyncOption != null && items != null) + if (vSMSDeploySyncOption is not null && items is not null) { foreach (Framework.ITaskItem item in items) { @@ -1068,9 +1037,9 @@ public static void AddImportDeclareParametersFileOptions(/*VSMSDeploySyncOption* } } - public static void AddSetParametersFilesToObject(/*Deployment.DeploymentObject*/ dynamic deploymentObject, Generic.IList filenames, IVSMSDeployHost host) + public static void AddSetParametersFilesToObject(/*Deployment.DeploymentObject*/ dynamic deploymentObject, IList filenames, IVSMSDeployHost host) { - if (deploymentObject != null && filenames != null) + if (deploymentObject is not null && filenames is not null) { foreach (string filename in filenames) { @@ -1080,7 +1049,7 @@ public static void AddSetParametersFilesToObject(/*Deployment.DeploymentObject*/ { deploymentObject.SyncParameters.Load(filename); } - catch (System.Exception e) + catch (Exception e) { if (host != null) host.Log.LogErrorFromException(e); @@ -1093,14 +1062,14 @@ public static void AddSetParametersFilesToObject(/*Deployment.DeploymentObject*/ } /// - /// Utility function to set SimpleeSyncParameter Name/Value + /// Utility function to set SimpleSyncParameter Name/Value /// /// /// - public static void AddSimpleSetParametersVsMsDeployObject(MsDeploy.VSMSDeployObject srcVsMsDeployobject, Framework.ITaskItem[] originalItems, bool fOptimisticPickNextDefaultValue) + public static void AddSimpleSetParametersVsMsDeployObject(VSMSDeployObject srcVsMsDeployobject, Framework.ITaskItem[]? originalItems, bool fOptimisticPickNextDefaultValue) { - System.Collections.Generic.IList items = SortParametersTaskItems(originalItems, fOptimisticPickNextDefaultValue, SimpleSyncParameterMetadata.Value.ToString()); - if (srcVsMsDeployobject != null && items != null) + IList items = SortParametersTaskItems(originalItems, fOptimisticPickNextDefaultValue, SimpleSyncParameterMetadata.Value.ToString()); + if (srcVsMsDeployobject is not null && items is not null) { string lastItemName = string.Empty; foreach (Framework.ITaskItem item in items) @@ -1116,9 +1085,9 @@ public static void AddSimpleSetParametersVsMsDeployObject(MsDeploy.VSMSDeployObj } } - public static void AddProviderOptions(/*Deployment.DeploymentProviderOptions*/ dynamic deploymentProviderOptions, Generic.IList providerOptions, IVSMSDeployHost host) + public static void AddProviderOptions(/*Deployment.DeploymentProviderOptions*/ dynamic deploymentProviderOptions, IList providerOptions, IVSMSDeployHost host) { - if (deploymentProviderOptions != null && providerOptions != null) + if (deploymentProviderOptions is not null && providerOptions is not null) { foreach (ProviderOption item in providerOptions) { @@ -1129,7 +1098,7 @@ public static void AddProviderOptions(/*Deployment.DeploymentProviderOptions*/ d // providerOptions list contains metadata from MSBuild and this may be different from deploymentProviderOptions.ProviderSettings. if (string.Compare(factoryName, deploymentProviderOptions.Factory.Name, StringComparison.OrdinalIgnoreCase) == 0) { - dynamic setting = null; + dynamic? setting = null; // deploymentProviderOptions.ProviderSettings.TryGetValue(name, out setting); MSWebDeploymentAssembly.DeploymentTryGetValueForEach(deploymentProviderOptions.ProviderSettings, name, out setting); @@ -1142,31 +1111,30 @@ public static void AddProviderOptions(/*Deployment.DeploymentProviderOptions*/ d } } - /// - /// Utility function to set SimpleeSyncParameter Name/Value + /// Utility function to set SimpleSyncParameter Name/Value /// /// /// - public static void AddSimpleSetParametersToObject(/*Deployment.DeploymentObject*/ dynamic deploymentObject, Generic.IList parameters, IVSMSDeployHost host) + public static void AddSimpleSetParametersToObject(/*Deployment.DeploymentObject*/ dynamic deploymentObject, IList parameters, IVSMSDeployHost host) { - if (deploymentObject != null && parameters != null) + if (deploymentObject is not null && parameters is not null) { - Generic.Dictionary nameValueDictionary = new(parameters.Count, StringComparer.OrdinalIgnoreCase); + Dictionary nameValueDictionary = new(parameters.Count, StringComparer.OrdinalIgnoreCase); foreach (ParameterInfo item in parameters) { string name = item.Name; - string value; + string? value; if (!nameValueDictionary.TryGetValue(name, out value)) { value = item.Value; } - dynamic parameter = null; + dynamic? parameter = null; // deploymentObject.SyncParameters.TryGetValue(name, out parameter); MSWebDeploymentAssembly.DeploymentTryGetValueContains(deploymentObject.SyncParameters, name, out parameter); string msg = string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_AddParameterIntoObject, name, value, deploymentObject.Name); - host.Log.LogMessage(msg); + host?.Log.LogMessage(msg); if (parameter != null) { parameter.Value = value; @@ -1174,7 +1142,7 @@ public static void AddSimpleSetParametersToObject(/*Deployment.DeploymentObject* else { // Try to get error message to show. - Text.StringBuilder sb = CleanStringBuilder; + StringBuilder sb = CleanStringBuilder; foreach (dynamic param in deploymentObject.SyncParameters) { if (sb.Length != 0) @@ -1187,40 +1155,39 @@ public static void AddSimpleSetParametersToObject(/*Deployment.DeploymentObject* string errMessage = string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_UnknownParameter, name, sb.ToString()); if (host != null) { - throw new System.InvalidOperationException(errMessage); + throw new InvalidOperationException(errMessage); } } } } } - /// /// Utility function to setParameters in type, scope, match, value of SyncParameter /// /// /// - public static void AddSetParametersToObject(/*Deployment.DeploymentObject*/ dynamic deploymentObject, Generic.IList parameters, IVSMSDeployHost host) + public static void AddSetParametersToObject(/*Deployment.DeploymentObject*/ dynamic deploymentObject, IList parameters, IVSMSDeployHost host) { - if (deploymentObject != null && parameters != null) + if (deploymentObject is not null && parameters is not null) { - Generic.Dictionary nameValueDictionary = new(parameters.Count, StringComparer.OrdinalIgnoreCase); - Generic.Dictionary entryIdentityDictionary = new(parameters.Count); + Dictionary nameValueDictionary = new(parameters.Count, StringComparer.OrdinalIgnoreCase); + Dictionary entryIdentityDictionary = new(parameters.Count); foreach (ParameterInfoWithEntry item in parameters) { try { - string data = null; + string? data = null; if (!nameValueDictionary.TryGetValue(item.Name, out data)) { nameValueDictionary.Add(item.Name, item.Value); data = item.Value; } - dynamic parameter = null; - dynamic parameterEntry = null; - dynamic parameterValidation = null; + dynamic? parameter = null; + dynamic? parameterEntry = null; + dynamic? parameterValidation = null; if (!string.IsNullOrEmpty(item.Kind)) { string identityString = string.Join(";", new string[] { item.Name, item.Kind, item.Scope, item.Match, item.Element, item.ValidationString }); @@ -1228,49 +1195,45 @@ public static void AddSetParametersToObject(/*Deployment.DeploymentObject*/ dyna { if (string.Compare(item.Element, "parameterEntry", StringComparison.OrdinalIgnoreCase) == 0) { - parameterEntry = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameterEntry", + parameterEntry = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameterEntry", new object[] { item.Kind, item.Scope, item.Match, string.Empty }); } else if (string.Compare(item.Element, "parameterValidation", StringComparison.OrdinalIgnoreCase) == 0) { - // this is bogus assertion because by default msdeploy always setup the validation which is never be null // System.Diagnostics.Debug.Assert(deploymentSyncParameter.Validation == null, "deploymentSyncParameter.Validation is already set"); string validationString = item.ValidationString; - object validationKindNone = MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue("Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind", "None"); - dynamic validationKind = validationKindNone; - System.Type validationKindType = validationKind.GetType(); - dynamic currentvalidationKind = validationKindNone; + object? validationKindNone = MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue("Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind", "None"); + dynamic? validationKind = validationKindNone; + Type? validationKindType = validationKind?.GetType(); + dynamic? currentvalidationKind = validationKindNone; string[] validationKinds = item.Kind.Split(new char[] { ',' }); foreach (string strValidationKind in validationKinds) { - if (MSWebDeploymentAssembly.DynamicAssembly.TryGetEnumValue("Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind", strValidationKind, out currentvalidationKind)) + if (MSWebDeploymentAssembly.DynamicAssembly?.TryGetEnumValue("Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind", strValidationKind, out currentvalidationKind) ?? false) { - validationKind = Enum.ToObject(validationKindType, ((int)(validationKind)) | ((int)(currentvalidationKind))); + validationKind = Enum.ToObject(validationKindType!, ((int)(validationKind)) | ((int)(currentvalidationKind))); } } // dynamic doesn't compare, since this is enum, cast to int to compare - if ((int)validationKind != (int)validationKindNone) + if ((int)validationKind != (int)(validationKindNone ?? 0)) { parameterValidation = - MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameterValidation", new object[] { validationKind, validationString }); + MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameterValidation", new object[] { validationKind!, validationString }); } - - - //Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind validationKind = Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind.None; - //Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind currentvalidationKind; + //Microsoft.Web.Deployment.DeploymentSyncParameterValidationKind currentValidationKind; //string[] validationKinds = item.Kind.Split(new char[] { ',' }); //foreach (string strValidationKind in validationKinds) //{ - // if (System.Enum.TryParse(strValidationKind, out currentvalidationKind)) + // if (System.Enum.TryParse(strValidationKind, out currentValidationKind)) // { - // validationKind |= currentvalidationKind; + // validationKind |= currentValidationKind; // } //} @@ -1286,23 +1249,23 @@ public static void AddSetParametersToObject(/*Deployment.DeploymentObject*/ dyna if (!MSWebDeploymentAssembly.DeploymentTryGetValueContains(deploymentObject.SyncParameters, item.Name, out parameter)) { - parameter = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameter", + parameter = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentSyncParameter", new object[] { item.Name, item.Description, item.DefaultValue, item.Tags }); deploymentObject.SyncParameters.Add(parameter); - parameter.Value = data; + parameter!.Value = data; } if (parameterEntry != null) { - parameter.Add(parameterEntry); + parameter?.Add(parameterEntry); } if (parameterValidation != null) { - // due to the reflection, compiler complain on assign a object to type without explicit convertion + // due to the reflection, compiler complain on assign a object to type without explicit conversion // parameter.Validation = parameterValidation; SetDynamicProperty(parameter, "Validation", parameterValidation); } } - catch (System.Exception e) + catch (Exception e) { if (host != null) host.Log.LogErrorFromException(e); @@ -1313,17 +1276,15 @@ public static void AddSetParametersToObject(/*Deployment.DeploymentObject*/ dyna } } - - /// /// Utility function to setParameters in type, scope, match, value of SyncParameter /// /// /// - public static void AddSetParametersVsMsDeployObject(MsDeploy.VSMSDeployObject srcVsMsDeployobject, Framework.ITaskItem[] originalItems, bool fOptimisticPickNextDefaultValue) + public static void AddSetParametersVsMsDeployObject(VSMSDeployObject srcVsMsDeployobject, Framework.ITaskItem[]? originalItems, bool fOptimisticPickNextDefaultValue) { - System.Collections.Generic.IList items = SortParametersTaskItems(originalItems, fOptimisticPickNextDefaultValue, SyncParameterMetadata.DefaultValue.ToString()); - if (srcVsMsDeployobject != null && items != null) + IList items = SortParametersTaskItems(originalItems, fOptimisticPickNextDefaultValue, SyncParameterMetadata.DefaultValue.ToString()); + if (srcVsMsDeployobject is not null && items is not null) { foreach (Framework.ITaskItem item in items) { @@ -1335,11 +1296,10 @@ public static void AddSetParametersVsMsDeployObject(MsDeploy.VSMSDeployObject sr string description = item.GetMetadata(SyncParameterMetadata.Description.ToString()); string defaultValue = item.GetMetadata(SyncParameterMetadata.DefaultValue.ToString()); string tags = item.GetMetadata(SyncParameterMetadata.Tags.ToString()); - string element = item.GetMetadata(ExistingParameterValiationMetadata.Element.ToString()); + string element = item.GetMetadata(ExistingParameterValidationMetadata.Element.ToString()); if (string.IsNullOrEmpty(element)) element = "parameterEntry"; - string validationString = item.GetMetadata(ExistingParameterValiationMetadata.ValidationString.ToString()); - + string validationString = item.GetMetadata(ExistingParameterValidationMetadata.ValidationString.ToString()); if (string.IsNullOrEmpty(value)) { @@ -1347,14 +1307,13 @@ public static void AddSetParametersVsMsDeployObject(MsDeploy.VSMSDeployObject sr } srcVsMsDeployobject.SyncParameter(name, value, kind, scope, matchRegularExpression, description, defaultValue, tags, element, validationString); - } } } - public static void AddSetParametersFilesVsMsDeployObject(VSMSDeployObject srcVsMsDeployobject, Framework.ITaskItem[] items) + public static void AddSetParametersFilesVsMsDeployObject(VSMSDeployObject srcVsMsDeployobject, Framework.ITaskItem[]? items) { - if (srcVsMsDeployobject != null && items != null) + if (srcVsMsDeployobject is not null && items is not null) { foreach (Framework.ITaskItem item in items) { @@ -1364,15 +1323,12 @@ public static void AddSetParametersFilesVsMsDeployObject(VSMSDeployObject srcVsM } } - - - - public static string DumpITeaskItem(Framework.ITaskItem iTaskItem) + public static string DumpITaskItem(Framework.ITaskItem iTaskItem) { - Text.StringBuilder sb = CleanStringBuilder; - string itemspec = iTaskItem.ItemSpec; + StringBuilder sb = CleanStringBuilder; + string itemSpec = iTaskItem.ItemSpec; sb.Append(""); foreach (string name in iTaskItem.MetadataNames) @@ -1391,8 +1347,6 @@ public static string DumpITeaskItem(Framework.ITaskItem iTaskItem) return sb.ToString(); } - - public static bool IsDeploymentWellKnownProvider(string strProvider) { #if NET472 @@ -1403,13 +1357,13 @@ public static bool IsDeploymentWellKnownProvider(string strProvider) { return true; } - object DeploymentWellKnownProviderUnknown = MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.Unknown); - object deploymentProvider = DeploymentWellKnownProviderUnknown; + object? DeploymentWellKnownProviderUnknown = MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.Unknown); + object? deploymentProvider = DeploymentWellKnownProviderUnknown; try { - deploymentProvider = MSWebDeploymentAssembly.DynamicAssembly.GetEnumValueIgnoreCase(MSDeploy.TypeName.DeploymentWellKnownProvider, strProvider); + deploymentProvider = MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValueIgnoreCase(MSDeploy.TypeName.DeploymentWellKnownProvider, strProvider); } - catch (System.Exception) + catch (Exception) { } return deploymentProvider != DeploymentWellKnownProviderUnknown; @@ -1424,17 +1378,17 @@ internal static void RemoveAllEmptyDirectories(string dirPath, Utilities.TaskLog { if (!string.IsNullOrEmpty(dirPath) && Directory.Exists(dirPath)) { - IO.DirectoryInfo dirInfo = new(dirPath); + DirectoryInfo dirInfo = new(dirPath); RemoveAllEmptyDirectories(dirInfo, Log); } } - internal static void RemoveAllEmptyDirectories(IO.DirectoryInfo dirinfo, Utilities.TaskLoggingHelper log) + internal static void RemoveAllEmptyDirectories(DirectoryInfo dirinfo, Utilities.TaskLoggingHelper log) { - if (dirinfo != null && dirinfo.Exists) + if (dirinfo is not null && dirinfo.Exists) { //Depth first search. - foreach (IO.DirectoryInfo subDirInfo in dirinfo.GetDirectories()) + foreach (DirectoryInfo subDirInfo in dirinfo.GetDirectories()) { RemoveAllEmptyDirectories(subDirInfo, log); } @@ -1446,12 +1400,11 @@ internal static void RemoveAllEmptyDirectories(IO.DirectoryInfo dirinfo, Utiliti { log.LogMessage(Framework.MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, Resources.BUILDTASK_RemoveEmptyDirectories_Deleting, dirinfo.FullName)); } - } } } - static PriorityIndexComparer s_PriorityIndexComparer = null; + static PriorityIndexComparer? s_PriorityIndexComparer = null; internal static PriorityIndexComparer ParameterTaskComparer { get @@ -1464,9 +1417,9 @@ internal static PriorityIndexComparer ParameterTaskComparer } } - public static Generic.IList SortParametersTaskItems(Framework.ITaskItem[] taskItems, bool fOptimisticPickNextNonNullDefaultValue, string PropertyName) + public static IList SortParametersTaskItems(Framework.ITaskItem[]? taskItems, bool fOptimisticPickNextNonNullDefaultValue, string PropertyName) { - Generic.IList sortedList = SortTaskItemsByPriority(taskItems); + IList sortedList = SortTaskItemsByPriority(taskItems); if (!fOptimisticPickNextNonNullDefaultValue || string.IsNullOrEmpty(PropertyName) || taskItems == null || taskItems.GetLength(0) <= 0) { @@ -1474,9 +1427,9 @@ internal static PriorityIndexComparer ParameterTaskComparer } else { - Generic.List optimizedValueList = new(sortedList); + List optimizedValueList = new(sortedList); - Generic.Dictionary FoundDictionary = new(optimizedValueList.Count, StringComparer.OrdinalIgnoreCase); + Dictionary FoundDictionary = new(optimizedValueList.Count, StringComparer.OrdinalIgnoreCase); int maxCount = sortedList.Count; int i = 0; @@ -1488,7 +1441,7 @@ internal static PriorityIndexComparer ParameterTaskComparer string itemSpec = item.ItemSpec; if (FoundDictionary.ContainsKey(itemSpec)) { - continue; // already scaned, move on to the next + continue; // already scanned, move on to the next } else { @@ -1504,10 +1457,10 @@ internal static PriorityIndexComparer ParameterTaskComparer bool found = false; while (next < maxCount) { - Framework.ITaskItem nextitem = optimizedValueList[next++]; - if (string.Compare(itemSpec, nextitem.ItemSpec, StringComparison.OrdinalIgnoreCase) == 0) + Framework.ITaskItem nextItem = optimizedValueList[next++]; + if (string.Compare(itemSpec, nextItem.ItemSpec, StringComparison.OrdinalIgnoreCase) == 0) { - string itemData = nextitem.GetMetadata(PropertyName); + string itemData = nextItem.GetMetadata(PropertyName); if (!string.IsNullOrEmpty(itemData)) { // Get the data from the next best data @@ -1531,7 +1484,6 @@ internal static PriorityIndexComparer ParameterTaskComparer } } - static string strMsdeployFwlink1 = @"http://go.microsoft.com/fwlink/?LinkId=178034"; static string strMsdeployFwlink2 = @"http://go.microsoft.com/fwlink/?LinkId=178035"; static string strMsdeployFwlink3 = @"http://go.microsoft.com/fwlink/?LinkId=178036"; @@ -1541,7 +1493,7 @@ internal static PriorityIndexComparer ParameterTaskComparer static string[] strMsdeployFwlinks = { strMsdeployFwlink1, strMsdeployFwlink2, strMsdeployFwlink3, strMsdeployFwlink4, strMsdeployFwlink5 }; - static int ContainMsdeployFwlink(string errorMessage, out string provider) + static int ContainMsdeployFwlink(string errorMessage, out string? provider) { int index = -1; provider = null; @@ -1571,11 +1523,10 @@ static int ContainMsdeployFwlink(string errorMessage, out string provider) return index; } - internal static bool IsType(System.Type type, System.Type checkType) + internal static bool IsType(Type type, Type? checkType) { #if NET472 - if (checkType!=null && - (type == checkType || type.IsSubclassOf(checkType))) + if (checkType != null && (type == checkType || type.IsSubclassOf(checkType))) { return true; } @@ -1583,7 +1534,7 @@ internal static bool IsType(System.Type type, System.Type checkType) return false; } - internal static string EnsureTrailingSlash(string str) + internal static string? EnsureTrailingSlash(string str) { if (str != null && !str.EndsWith("/", StringComparison.Ordinal)) { @@ -1591,7 +1542,7 @@ internal static string EnsureTrailingSlash(string str) } return str; } - internal static string EnsureTrailingBackSlash(string str) + internal static string? EnsureTrailingBackSlash(string str) { if (str != null && !str.EndsWith("\\", StringComparison.Ordinal)) { @@ -1601,29 +1552,29 @@ internal static string EnsureTrailingBackSlash(string str) } // Utility to log VsMsdeploy Exception - internal static void LogVsMsDeployException(Utilities.TaskLoggingHelper Log, System.Exception e) + internal static void LogVsMsDeployException(Utilities.TaskLoggingHelper Log, Exception e) { - if (e is System.Reflection.TargetInvocationException) + if (e is TargetInvocationException) { if (e.InnerException != null) e = e.InnerException; } - System.Text.StringBuilder strBuilder = new(e.Message.Length * 4); - System.Type t = e.GetType(); - if (IsType(t, MSWebDeploymentAssembly.DynamicAssembly.GetType(MSDeploy.TypeName.DeploymentEncryptionException))) + StringBuilder strBuilder = new(e.Message.Length * 4); + Type t = e.GetType(); + if (IsType(t, MSWebDeploymentAssembly.DynamicAssembly?.GetType(MSDeploy.TypeName.DeploymentEncryptionException))) { // dev10 695263 OGF: Encryption Error message needs more information for packaging strBuilder.Append(Resources.VSMSDEPLOY_EncryptionExceptionMessage); } - else if (IsType(t, MSWebDelegationAssembly.DynamicAssembly.GetType(MSDeploy.TypeName.DeploymentException))) + else if (IsType(t, MSWebDelegationAssembly.DynamicAssembly?.GetType(MSDeploy.TypeName.DeploymentException))) { - System.Exception rootException = e; + Exception rootException = e; dynamic lastDeploymentException = e; while (rootException != null && rootException.InnerException != null) { rootException = rootException.InnerException; - if (IsType(rootException.GetType(), MSWebDelegationAssembly.DynamicAssembly.GetType(MSDeploy.TypeName.DeploymentException))) + if (IsType(rootException.GetType(), MSWebDelegationAssembly.DynamicAssembly?.GetType(MSDeploy.TypeName.DeploymentException))) lastDeploymentException = rootException; } @@ -1631,10 +1582,10 @@ internal static void LogVsMsDeployException(Utilities.TaskLoggingHelper Log, Sys bool isWebException = rootException is System.Net.WebException; if (isWebException) { - System.Net.WebException webException = rootException as System.Net.WebException; + System.Net.WebException? webException = rootException as System.Net.WebException; // 404 come in as ProtocolError - if (webException.Status == System.Net.WebExceptionStatus.ProtocolError) + if (webException?.Status == System.Net.WebExceptionStatus.ProtocolError) { if (webException.Message.LastIndexOf("401", StringComparison.Ordinal) >= 0) { @@ -1657,7 +1608,7 @@ internal static void LogVsMsDeployException(Utilities.TaskLoggingHelper Log, Sys strBuilder.Append(Resources.VSMSDEPLOY_WebException551Message); } } - else if (webException.Status == System.Net.WebExceptionStatus.ConnectFailure) + else if (webException?.Status == System.Net.WebExceptionStatus.ConnectFailure) { strBuilder.Append(Resources.VSMSDEPLOY_WebExceptionConnectFailureMessage); } @@ -1669,18 +1620,18 @@ internal static void LogVsMsDeployException(Utilities.TaskLoggingHelper Log, Sys else { string strMsg = lastDeploymentException.Message; - string provider; + string? provider; int index = ContainMsdeployFwlink(strMsg, out provider); if (index >= 0) { - object DeploymentWellKnownProviderUnknown = MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.Unknown); + object? DeploymentWellKnownProviderUnknown = MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.Unknown); - dynamic wellKnownProvider = DeploymentWellKnownProviderUnknown; + dynamic? wellKnownProvider = DeploymentWellKnownProviderUnknown; // fwdlink1 if (index == 0) { string srErrorMessage = Resources.VSMSDEPLOY_MsDeployExceptionFwlink1Message; - if (provider.LastIndexOf("sql", StringComparison.OrdinalIgnoreCase) >= 0) + if (provider?.LastIndexOf("sql", StringComparison.OrdinalIgnoreCase) >= 0) { srErrorMessage = Resources.VSMSDEPLOY_MsDeployExceptionFwlink1SQLMessage; } @@ -1688,15 +1639,15 @@ internal static void LogVsMsDeployException(Utilities.TaskLoggingHelper Log, Sys { try { - wellKnownProvider = MSWebDeploymentAssembly.DynamicAssembly.GetEnumValueIgnoreCase(MSDeploy.TypeName.DeploymentWellKnownProvider, provider); + wellKnownProvider = MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValueIgnoreCase(MSDeploy.TypeName.DeploymentWellKnownProvider, provider); } catch { // don't cause the failure; } - if (wellKnownProvider.Equals(MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.MetaKey)) - || wellKnownProvider.Equals(MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.AppHostConfig))) + if (wellKnownProvider?.Equals(MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.MetaKey)) ?? false + || wellKnownProvider?.Equals(MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.AppHostConfig)) ?? false) { srErrorMessage = Resources.VSMSDEPLOY_MsDeployExceptionFwlink1SiteMessage; } @@ -1732,7 +1683,7 @@ internal static void LogVsMsDeployException(Utilities.TaskLoggingHelper Log, Sys else { // Dev10 bug we sometime need better error message to show user what do do - System.Exception currentException = e; + Exception? currentException = e; while (currentException != null) { strBuilder.Append(Environment.NewLine); @@ -1746,25 +1697,24 @@ internal static void LogVsMsDeployException(Utilities.TaskLoggingHelper Log, Sys Log.LogMessage(Framework.MessageImportance.Low, strBuilder.ToString()); } - public static Generic.IList SortTaskItemsByPriority(Framework.ITaskItem[] taskItems) + public static IList SortTaskItemsByPriority(Framework.ITaskItem[]? taskItems) { int count = taskItems != null ? taskItems.GetLength(0) : 0; - Generic.SortedList, Framework.ITaskItem> sortedList = - new(count, ParameterTaskComparer); + SortedList, Framework.ITaskItem> sortedList = new(count, ParameterTaskComparer); for (int i = 0; i < count; i++) { - Framework.ITaskItem iTaskItem = taskItems[i]; + Framework.ITaskItem iTaskItem = taskItems![i]; string priority = iTaskItem.GetMetadata("Priority"); int iPriority = string.IsNullOrEmpty(priority) ? 0 : Convert.ToInt32(priority, CultureInfo.InvariantCulture); - sortedList.Add(new System.Collections.Generic.KeyValuePair(iPriority, i), iTaskItem); + sortedList.Add(new KeyValuePair(iPriority, i), iTaskItem); } return sortedList.Values; } - internal class PriorityIndexComparer : Generic.IComparer> + + internal class PriorityIndexComparer : IComparer> { - #region IComparer> Members - public int Compare(System.Collections.Generic.KeyValuePair x, System.Collections.Generic.KeyValuePair y) + public int Compare(KeyValuePair x, KeyValuePair y) { if (x.Key == y.Key) { @@ -1775,7 +1725,6 @@ public int Compare(System.Collections.Generic.KeyValuePair x, System.C return x.Key - y.Key; } } - #endregion } public static string StripOffTrailingSlashes(string str) @@ -1796,23 +1745,21 @@ public static string EnsureTrailingSlashes(string rootPath, char slash) return rootPathWithSlash; } - - public static string GetFilePathResolution(string source, string sourceRootPath) + public static string? GetFilePathResolution(string? source, string sourceRootPath) { if (Path.IsPathRooted(source) || string.IsNullOrEmpty(sourceRootPath)) return source; else - return Path.Combine(sourceRootPath, source); + return Path.Combine(sourceRootPath, source!); } - /// /// Utility to generate the Ipv6 string address to match with the ServerBinding string /// Ipv6 need the have /// /// /// - internal static string GetIPAddressString(System.Net.IPAddress iPAddress) + internal static string? GetIPAddressString(System.Net.IPAddress iPAddress) { if (iPAddress != null) { @@ -1820,7 +1767,7 @@ internal static string GetIPAddressString(System.Net.IPAddress iPAddress) return iPAddress.ToString(); else if (iPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { - Text.StringBuilder stringBuilder = CleanStringBuilder; + StringBuilder stringBuilder = CleanStringBuilder; stringBuilder.Append("["); stringBuilder.Append(iPAddress.ToString()); stringBuilder.Append("]"); @@ -1852,14 +1799,14 @@ internal static bool MatchOneOfIPAddress(string IISBindingIPString, System.Net.I return false; } - internal static void SetupMSWebDeployDynamicAssemblies(string strVersionsToTry, Utilities.Task task) + internal static void SetupMSWebDeployDynamicAssemblies(string? strVersionsToTry, Task task) { // Mark the assembly version. // System.Version version1_1 = new System.Version("7.1"); - Generic.Dictionary versionsList = new(); + Dictionary versionsList = new(); if (!string.IsNullOrEmpty(strVersionsToTry)) { - foreach (string str in strVersionsToTry.Split(';')) + foreach (string str in strVersionsToTry!.Split(';')) { versionsList[str] = str; } @@ -1868,21 +1815,21 @@ internal static void SetupMSWebDeployDynamicAssemblies(string strVersionsToTry, const string MSDeploymentDllFallback = "9.0"; versionsList[MSDeploymentDllFallback] = MSDeploymentDllFallback; - System.Version[] versionArray = versionsList.Values.Select(p => new System.Version(p)).ToArray(); + Version[] versionArray = versionsList.Values.Select(p => new Version(p)).ToArray(); Array.Sort(versionArray); for (int i = versionArray.GetLength(0) - 1; i >= 0; i--) { - System.Version version = versionArray[i]; + Version version = versionArray[i]; try { MSWebDeploymentAssembly.SetVersion(version); - System.Version webDelegationAssemblyVersion = version; + Version webDelegationAssemblyVersion = version; #if NET472 if (MSWebDeploymentAssembly.DynamicAssembly != null && MSWebDeploymentAssembly.DynamicAssembly.Assembly != null) { - foreach (System.Reflection.AssemblyName assemblyName in MSWebDeploymentAssembly.DynamicAssembly.Assembly.GetReferencedAssemblies()) + foreach (AssemblyName assemblyName in MSWebDeploymentAssembly.DynamicAssembly.Assembly.GetReferencedAssemblies()) { if (string.Compare(assemblyName.Name, 0 , MSWebDelegationAssembly.AssemblyName, 0, MSWebDelegationAssembly.AssemblyName.Length, StringComparison.OrdinalIgnoreCase) == 0) { @@ -1893,25 +1840,24 @@ internal static void SetupMSWebDeployDynamicAssemblies(string strVersionsToTry, } #endif MSWebDelegationAssembly.SetVersion(webDelegationAssemblyVersion); - task.Log.LogMessage(Framework.MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_MSDEPLOYVERSIONLOAD, task.ToString(), MSWebDeploymentAssembly.DynamicAssembly.AssemblyFullName)); - task.Log.LogMessage(Framework.MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_MSDEPLOYVERSIONLOAD, task.ToString(), MSWebDelegationAssembly.DynamicAssembly.AssemblyFullName)); + task.Log.LogMessage(Framework.MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_MSDEPLOYVERSIONLOAD, task.ToString(), MSWebDeploymentAssembly.DynamicAssembly?.AssemblyFullName)); + task.Log.LogMessage(Framework.MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_MSDEPLOYVERSIONLOAD, task.ToString(), MSWebDelegationAssembly.DynamicAssembly?.AssemblyFullName)); return; } - catch (System.Exception e) + catch (Exception e) { task.Log.LogMessage(Framework.MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, Resources.BUILDTASK_FailedToLoadThisVersionMsDeployTryingTheNext, versionArray[i], e.Message)); } } // if it not return by now, it is definite a error - throw new System.InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_MSDEPLOYASSEMBLYLOAD_FAIL, task.ToString())); + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_MSDEPLOYASSEMBLYLOAD_FAIL, task.ToString())); } - - public static string EscapeTextForMSBuildVariable(string text) + public static string? EscapeTextForMSBuildVariable(string? text) { - if (!string.IsNullOrEmpty(text) && text.IndexOfAny(@"$%".ToArray()) >= 0) + if (!string.IsNullOrEmpty(text) && text?.IndexOfAny(@"$%".ToArray()) >= 0) { - System.Text.StringBuilder stringBuilder = new(text.Length * 2); + StringBuilder stringBuilder = new(text.Length * 2); char[] chars = text.ToCharArray(); int i = 0; for (i = 0; i < chars.Count() - 2; i++) @@ -1949,15 +1895,15 @@ public static string EscapeTextForMSBuildVariable(string text) return text; } /// - /// Given a user agant string, it appends :WTE to it if + /// Given a user agent string, it appends :WTE to it if /// the string is not null. /// - public static string GetFullUserAgentString(string userAgent) + public static string? GetFullUserAgentString(string? userAgent) { #if NET472 if(string.IsNullOrEmpty(userAgent)) return null; - try + try { object[] o = typeof(Utility).Assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false); if (o.Length > 0 && o[0] is AssemblyFileVersionAttribute) @@ -1972,10 +1918,8 @@ public static string GetFullUserAgentString(string userAgent) #endif return userAgent; } - } - internal static class ItemFilter { public delegate bool ItemMetadataFilter(Framework.ITaskItem iTaskItem); @@ -1987,7 +1931,6 @@ public static bool ItemFilterPipelineMetadata(Framework.ITaskItem item, string m #else return (string.Compare(item.GetMetadata(metadataName), metadataValue, fIgnoreCase) == 0); #endif - } public static bool ItemFilterExcludeTrue(Framework.ITaskItem iTaskItem) @@ -1995,8 +1938,5 @@ public static bool ItemFilterExcludeTrue(Framework.ITaskItem iTaskItem) string metadataName = PipelineMetadata.Exclude.ToString(); return ItemFilterPipelineMetadata(iTaskItem, metadataName, "true", true); } - } - - } diff --git a/src/WebSdk/Publish/Tasks/MsDeploy/DynamicAssembly.cs b/src/WebSdk/Publish/Tasks/MsDeploy/DynamicAssembly.cs index d5d8a51cb0f9..74bf61a77b38 100644 --- a/src/WebSdk/Publish/Tasks/MsDeploy/DynamicAssembly.cs +++ b/src/WebSdk/Publish/Tasks/MsDeploy/DynamicAssembly.cs @@ -9,7 +9,7 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy { internal class DynamicAssembly { - public DynamicAssembly(string assemblyName, System.Version verToLoad, string publicKeyToken) + public DynamicAssembly(string assemblyName, Version verToLoad, string publicKeyToken) { AssemblyFullName = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}, Version={1}.{2}.0.0, Culture=neutral, PublicKeyToken={3}", assemblyName, verToLoad.Major, verToLoad.Minor, publicKeyToken); #if NET472 @@ -46,42 +46,42 @@ public static string TaskAssemblyDirectory #endif public DynamicAssembly() { } - public string AssemblyFullName { get; set; } - public System.Version Version { get; set; } - public Assembly Assembly { get; set; } + public string? AssemblyFullName { get; set; } + public Version? Version { get; set; } + public Assembly? Assembly { get; set; } - public System.Type GetType(string typeName) + public Type GetType(string? typeName) { - System.Type type = Assembly.GetType(typeName); + Type? type = Assembly?.GetType(typeName!); Debug.Assert(type != null); - return type; + return type!; } - public virtual System.Type TryGetType(string typeName) + public virtual Type? TryGetType(string typeName) { - System.Type type = Assembly.GetType(typeName); + Type? type = Assembly?.GetType(typeName); return type; } - public object GetEnumValue(string enumName, string enumValue) + public object? GetEnumValue(string enumName, string enumValue) { - System.Type enumType = Assembly.GetType(enumName); - FieldInfo enumItem = enumType.GetField(enumValue); - object ret = enumItem.GetValue(enumType); + Type? enumType = Assembly?.GetType(enumName); + FieldInfo? enumItem = enumType?.GetField(enumValue); + object? ret = enumItem?.GetValue(enumType); Debug.Assert(ret != null); return ret; } - public object GetEnumValueIgnoreCase(string enumName, string enumValue) + public object? GetEnumValueIgnoreCase(string enumName, string? enumValue) { - System.Type enumType = Assembly.GetType(enumName); - FieldInfo enumItem = enumType.GetField(enumValue, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); - object ret = enumItem.GetValue(enumType); + Type? enumType = Assembly?.GetType(enumName); + FieldInfo? enumItem = enumType?.GetField(enumValue!, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); + object? ret = enumItem?.GetValue(enumType); Debug.Assert(ret != null); return ret; } - public bool TryGetEnumValue(string enumTypeName, string enumStrValue, out object retValue) + public bool TryGetEnumValue(string enumTypeName, string enumStrValue, out object? retValue) { bool fGetValue = false; retValue = Enum.ToObject(GetType(enumTypeName), 0); @@ -96,16 +96,15 @@ public bool TryGetEnumValue(string enumTypeName, string enumStrValue, out object return fGetValue; } - - public object CreateObject(string typeName) + public object? CreateObject(string typeName) { return CreateObject(typeName, null); } - public object CreateObject(string typeName, object[] arguments) + public object? CreateObject(string typeName, object[]? arguments) { - object createdObject = null; - System.Type[] argumentTypes = null; + object? createdObject = null; + Type[]? argumentTypes = null; if (arguments == null || arguments.GetLength(0) == 0) { argumentTypes = Type.EmptyTypes; @@ -114,8 +113,8 @@ public object CreateObject(string typeName, object[] arguments) { argumentTypes = arguments.Select(p => p.GetType()).ToArray(); } - System.Type typeToConstruct = Assembly.GetType(typeName); - System.Reflection.ConstructorInfo constructorInfoObj = typeToConstruct.GetConstructor(argumentTypes); + Type? typeToConstruct = Assembly?.GetType(typeName); + ConstructorInfo? constructorInfoObj = typeToConstruct?.GetConstructor(argumentTypes); if (constructorInfoObj == null) { @@ -130,12 +129,11 @@ public object CreateObject(string typeName, object[] arguments) } #if NET472 - public object CallStaticMethod(string typeName, string methodName, object[] arguments) + public object? CallStaticMethod(string typeName, string methodName, object[] arguments) { - System.Type t = GetType(typeName); - return t.InvokeMember(methodName, BindingFlags.InvokeMethod, null, t, arguments, System.Globalization.CultureInfo.InvariantCulture); + Type? t = GetType(typeName); + return t?.InvokeMember(methodName, BindingFlags.InvokeMethod, null, t, arguments, System.Globalization.CultureInfo.InvariantCulture); } - #endif /// @@ -144,14 +142,14 @@ public object CallStaticMethod(string typeName, string methodName, object[] argu /// /// public delegate void EventHandlerDynamicDelegate(object sender, dynamic e); - public delegate void EventHandlerEventArgsDelegate(object sender, System.EventArgs e); - internal static System.Delegate CreateEventHandlerDelegate(System.Reflection.EventInfo evt, TDelegate d) + public delegate void EventHandlerEventArgsDelegate(object sender, EventArgs e); + internal static Delegate? CreateEventHandlerDelegate(EventInfo evt, TDelegate d) { var handlerType = evt.EventHandlerType; - var eventParams = handlerType.GetMethod("Invoke").GetParameters(); + var eventParams = handlerType?.GetMethod("Invoke")?.GetParameters(); - ParameterExpression[] parameters = eventParams.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray(); - MethodCallExpression body = Expression.Call(Expression.Constant(d), d.GetType().GetMethod("Invoke"), parameters); + ParameterExpression[] parameters = eventParams?.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray() ?? Array.Empty(); + MethodCallExpression body = Expression.Call(Expression.Constant(d), d?.GetType().GetMethod("Invoke")!, parameters); var lambda = Expression.Lambda(body, parameters); // Diagnostics.Debug.Assert(false, lambda.ToString()); #if NET472 @@ -161,24 +159,24 @@ internal static System.Delegate CreateEventHandlerDelegate(System.Ref #endif } - public static System.Delegate AddEventDeferHandler(dynamic obj, string eventName, System.Delegate deferEventHandler) + public static Delegate? AddEventDeferHandler(dynamic obj, string eventName, Delegate deferEventHandler) { - EventInfo eventinfo = obj.GetType().GetEvent(eventName); - System.Delegate eventHandler = CreateEventHandlerDelegate(eventinfo, deferEventHandler); - eventinfo.AddEventHandler(obj, eventHandler); + EventInfo eventInfo = obj.GetType().GetEvent(eventName); + Delegate? eventHandler = CreateEventHandlerDelegate(eventInfo, deferEventHandler); + eventInfo.AddEventHandler(obj, eventHandler); return eventHandler; } - public static void AddEventHandler(dynamic obj, string eventName, System.Delegate eventHandler) + public static void AddEventHandler(dynamic obj, string eventName, Delegate eventHandler) { - EventInfo eventinfo = obj.GetType().GetEvent(eventName); - eventinfo.AddEventHandler(obj, eventHandler); + EventInfo eventInfo = obj.GetType().GetEvent(eventName); + eventInfo.AddEventHandler(obj, eventHandler); } - public static void RemoveEventHandler(dynamic obj, string eventName, System.Delegate eventHandler) + public static void RemoveEventHandler(dynamic obj, string eventName, Delegate eventHandler) { - EventInfo eventinfo = obj.GetType().GetEvent(eventName); - eventinfo.RemoveEventHandler(obj, eventHandler); + EventInfo eventInfo = obj.GetType().GetEvent(eventName); + eventInfo.RemoveEventHandler(obj, eventHandler); } } } diff --git a/src/WebSdk/Publish/Tasks/MsDeploy/FileSkipData.cs b/src/WebSdk/Publish/Tasks/MsDeploy/FileSkipData.cs index fdf443f66e27..8566caea6b3c 100644 --- a/src/WebSdk/Publish/Tasks/MsDeploy/FileSkipData.cs +++ b/src/WebSdk/Publish/Tasks/MsDeploy/FileSkipData.cs @@ -5,10 +5,9 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy { public class FileSkipData { - public string sourceProvider { get; set; } - public string sourceFilePath { get; set; } - public string destinationProvider { get; set; } - public string destinationFilePath { get; set; } - + public string? sourceProvider { get; set; } + public string? sourceFilePath { get; set; } + public string? destinationProvider { get; set; } + public string? destinationFilePath { get; set; } } } diff --git a/src/WebSdk/Publish/Tasks/MsDeploy/IVSMSDeployTask.cs b/src/WebSdk/Publish/Tasks/MsDeploy/IVSMSDeployTask.cs index 258166c6a10d..312039c8828b 100644 --- a/src/WebSdk/Publish/Tasks/MsDeploy/IVSMSDeployTask.cs +++ b/src/WebSdk/Publish/Tasks/MsDeploy/IVSMSDeployTask.cs @@ -14,7 +14,7 @@ internal interface IVsPublishMsBuildTaskHost IBuildEngine BuildEngine { get; } - object GetProperty(string propertyName); + object? GetProperty(string propertyName); } internal interface IVSMSDeployHost : IVsPublishMsBuildTaskHost diff --git a/src/WebSdk/Publish/Tasks/MsDeploy/VSHostObject.cs b/src/WebSdk/Publish/Tasks/MsDeploy/VSHostObject.cs index 448dad35a880..a7d0a5db1fda 100644 --- a/src/WebSdk/Publish/Tasks/MsDeploy/VSHostObject.cs +++ b/src/WebSdk/Publish/Tasks/MsDeploy/VSHostObject.cs @@ -7,8 +7,8 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy { internal class VSHostObject { - IEnumerable _hostObject; - public VSHostObject(IEnumerable hostObject) + IEnumerable? _hostObject; + public VSHostObject(IEnumerable? hostObject) { _hostObject = hostObject; } @@ -19,7 +19,7 @@ public bool ExtractCredentials(out string username, out string password) username = password = string.Empty; if (_hostObject != null) { - ITaskItem credentialItem = _hostObject.FirstOrDefault(p => p.ItemSpec == VSMsDeployTaskHostObject.CredentailItemSpecName); + ITaskItem? credentialItem = _hostObject.FirstOrDefault(p => p.ItemSpec == VSMsDeployTaskHostObject.CredentailItemSpecName); if (credentialItem != null) { retVal = true; @@ -33,7 +33,7 @@ public bool ExtractCredentials(out string username, out string password) return retVal; } - public void GetFileSkips(out ITaskItem[] srcSkips, out ITaskItem[] destSkips) + public void GetFileSkips(out ITaskItem[]? srcSkips, out ITaskItem[]? destSkips) { srcSkips = null; destSkips = null; diff --git a/src/WebSdk/Publish/Tasks/MsDeploy/VSMSDeployHostObject.cs b/src/WebSdk/Publish/Tasks/MsDeploy/VSMSDeployHostObject.cs index 124ddae28fe4..d909d2aa3d5c 100644 --- a/src/WebSdk/Publish/Tasks/MsDeploy/VSMSDeployHostObject.cs +++ b/src/WebSdk/Publish/Tasks/MsDeploy/VSMSDeployHostObject.cs @@ -48,13 +48,13 @@ public void AddFileSkips(List fileSkipInfos, /*key is src relative { TaskItem srcSkipRuleItem = new(SkipFileItemSpecName); srcSkipRuleItem.SetMetadata("ObjectName", p.sourceProvider); - srcSkipRuleItem.SetMetadata("AbsolutePath", System.Text.RegularExpressions.Regex.Escape(Path.Combine(rootFolderOfFileToPublish, p.sourceFilePath)) + "$"); + srcSkipRuleItem.SetMetadata("AbsolutePath", System.Text.RegularExpressions.Regex.Escape(Path.Combine(rootFolderOfFileToPublish, p.sourceFilePath!)) + "$"); srcSkipRuleItem.SetMetadata(SkipApplyMetadataName, SourceDeployObject); _items.Add(srcSkipRuleItem); TaskItem destSkipRuleItem = new(SkipFileItemSpecName); destSkipRuleItem.SetMetadata("ObjectName", p.destinationProvider); - destSkipRuleItem.SetMetadata("AbsolutePath", System.Text.RegularExpressions.Regex.Escape(p.destinationFilePath) + "$"); + destSkipRuleItem.SetMetadata("AbsolutePath", System.Text.RegularExpressions.Regex.Escape(p.destinationFilePath!) + "$"); destSkipRuleItem.SetMetadata(SkipApplyMetadataName, DestinationDeployObject); _items.Add(destSkipRuleItem); } diff --git a/src/WebSdk/Publish/Tasks/MsDeploy/VsMSDeployObject.cs b/src/WebSdk/Publish/Tasks/MsDeploy/VsMSDeployObject.cs index f1cf6e42960c..f8c1084cfa2e 100644 --- a/src/WebSdk/Publish/Tasks/MsDeploy/VsMSDeployObject.cs +++ b/src/WebSdk/Publish/Tasks/MsDeploy/VsMSDeployObject.cs @@ -8,19 +8,16 @@ /// /// Copyright(c) 2006 Microsoft Corporation ///-------------------------------------------------------------------------------------------- -namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy -{ - using System; - using Microsoft.NET.Sdk.Publish.Tasks.Properties; - using Diagnostics = System.Diagnostics; - using Generic = System.Collections.Generic; - // using Deployment = Microsoft.Web.Deployment; - using RegularExpressions = System.Text.RegularExpressions; - - // we need to think of a way to split the MSDeployment to other dll - // using VSMSDeploySyncOption = Deployment.DeploymentSyncOptions; +using Microsoft.NET.Sdk.Publish.Tasks.Properties; +using Diagnostics = System.Diagnostics; +// using Deployment = Microsoft.Web.Deployment; +using RegularExpressions = System.Text.RegularExpressions; +// we need to think of a way to split the MSDeployment to other dll +// using VSMSDeploySyncOption = Deployment.DeploymentSyncOptions; +namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy +{ static class VSMSDeployObjectFactory { /// @@ -49,7 +46,7 @@ public static VSMSDeployObject CreateVSMSDeployObject(string provider, string pa } /// - /// Utility class to abstract the multiple MSDeploy object for various secnario + /// Utility class to abstract the multiple MSDeploy object for various scenario /// It also make sure the Dispose is called properly for MSDeploy object /// internal static class MSDeployUtility @@ -59,70 +56,73 @@ internal static class MSDeployUtility /// /// /// - public static /*Deployment.DeploymentBaseOptions*/ dynamic CreateBaseOptions(VSMSDeployObject vSMSDeployObject) + public static /*Deployment.DeploymentBaseOptions*/ dynamic? CreateBaseOptions(VSMSDeployObject vSMSDeployObject) { // /*Deployment.DeploymentBaseOptions*/dynamic baseOptions = new Microsoft.Web.Deployment.DeploymentBaseOptions(); /*Deployment.DeploymentBaseOptions*/ - dynamic baseOptions = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentBaseOptions"); + dynamic? baseOptions = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentBaseOptions"); - if (vSMSDeployObject.IsLocal) - { - // do nothing - } - else if (!vSMSDeployObject.UseSeparatedCredential) + if (baseOptions is not null) { - baseOptions.ComputerName = vSMSDeployObject.ComputerName; - } - else - { - baseOptions.ComputerName = vSMSDeployObject.ComputerName; - baseOptions.UserName = vSMSDeployObject.UserName; - baseOptions.Password = vSMSDeployObject.Password; - } + if (vSMSDeployObject.IsLocal) + { + // do nothing + } + else if (!vSMSDeployObject.UseSeparatedCredential) + { + baseOptions.ComputerName = vSMSDeployObject.ComputerName; + } + else + { + baseOptions.ComputerName = vSMSDeployObject.ComputerName; + baseOptions.UserName = vSMSDeployObject.UserName; + baseOptions.Password = vSMSDeployObject.Password; + } - baseOptions.PrefetchPayload = vSMSDeployObject.PrefetchPayload; - baseOptions.IncludeAcls = vSMSDeployObject.IncludeAcls; - if (!string.IsNullOrEmpty(vSMSDeployObject.AuthenticationType)) - { - baseOptions.AuthenticationType = vSMSDeployObject.AuthenticationType; - } + baseOptions.PrefetchPayload = vSMSDeployObject.PrefetchPayload; + baseOptions.IncludeAcls = vSMSDeployObject.IncludeAcls; + if (!string.IsNullOrEmpty(vSMSDeployObject.AuthenticationType)) + { + baseOptions.AuthenticationType = vSMSDeployObject.AuthenticationType; + } - if (string.Equals(Guid.Empty.ToString(), vSMSDeployObject.UserName, StringComparison.OrdinalIgnoreCase)) - { - baseOptions.AuthenticationType = "Bearer"; - } + if (string.Equals(Guid.Empty.ToString(), vSMSDeployObject.UserName, StringComparison.OrdinalIgnoreCase)) + { + baseOptions.AuthenticationType = "Bearer"; + } - if (!string.IsNullOrEmpty(vSMSDeployObject.EncryptPassword)) - baseOptions.EncryptPassword = vSMSDeployObject.EncryptPassword; + if (!string.IsNullOrEmpty(vSMSDeployObject.EncryptPassword)) + baseOptions.EncryptPassword = vSMSDeployObject.EncryptPassword; - if (!string.IsNullOrEmpty(vSMSDeployObject.WebServerManifest)) - baseOptions.WebServerConfiguration.WebServerManifest = Path.GetFileName(vSMSDeployObject.WebServerManifest); - if (!string.IsNullOrEmpty(vSMSDeployObject.WebServerDirectory)) - baseOptions.WebServerConfiguration.WebServerDirectory = vSMSDeployObject.WebServerDirectory; + if (!string.IsNullOrEmpty(vSMSDeployObject.WebServerManifest)) + baseOptions.WebServerConfiguration.WebServerManifest = Path.GetFileName(vSMSDeployObject.WebServerManifest); + if (!string.IsNullOrEmpty(vSMSDeployObject.WebServerDirectory)) + baseOptions.WebServerConfiguration.WebServerDirectory = vSMSDeployObject.WebServerDirectory; - if (!string.IsNullOrEmpty(vSMSDeployObject.WebServerAppHostConfigDirectory)) - baseOptions.WebServerConfiguration.ConfigurationDirectory = vSMSDeployObject.WebServerAppHostConfigDirectory; + if (!string.IsNullOrEmpty(vSMSDeployObject.WebServerAppHostConfigDirectory)) + baseOptions.WebServerConfiguration.ConfigurationDirectory = vSMSDeployObject.WebServerAppHostConfigDirectory; - if (vSMSDeployObject.RetryInterval >= 0) - baseOptions.RetryInterval = vSMSDeployObject.RetryInterval; - if (vSMSDeployObject.RetryAttempts >= 0) - baseOptions.RetryAttempts = vSMSDeployObject.RetryAttempts; + if (vSMSDeployObject.RetryInterval >= 0) + baseOptions.RetryInterval = vSMSDeployObject.RetryInterval; + if (vSMSDeployObject.RetryAttempts >= 0) + baseOptions.RetryAttempts = vSMSDeployObject.RetryAttempts; - if (!string.IsNullOrEmpty(vSMSDeployObject.UserAgent)) - baseOptions.UserAgent = vSMSDeployObject.UserAgent; + if (!string.IsNullOrEmpty(vSMSDeployObject.UserAgent)) + baseOptions.UserAgent = vSMSDeployObject.UserAgent; - //remove duplicate items appearing in both "EnableLinks" and "DisableLinks" caused by the default value set by publish target file - Generic.List enabledLinkList = ConvertStringIntoList(vSMSDeployObject.EnableLinks); - Generic.List disabledLinkList = ConvertStringIntoList(vSMSDeployObject.DisableLinks); - foreach (string link in disabledLinkList) - { - if (LinkContainedInTheCollection(link, enabledLinkList)) - enabledLinkList.Remove(link); - } + //remove duplicate items appearing in both "EnableLinks" and "DisableLinks" caused by the default value set by publish target file + List enabledLinkList = ConvertStringIntoList(vSMSDeployObject.EnableLinks); + List disabledLinkList = ConvertStringIntoList(vSMSDeployObject.DisableLinks); + foreach (string link in disabledLinkList) + { + if (LinkContainedInTheCollection(link, enabledLinkList)) + enabledLinkList.Remove(link); + } - ChangeLinkExtensionEnableStatue(baseOptions, disabledLinkList, false); - ChangeLinkExtensionEnableStatue(baseOptions, enabledLinkList, true); + ChangeLinkExtensionEnableStatue(baseOptions, disabledLinkList, false); + ChangeLinkExtensionEnableStatue(baseOptions, enabledLinkList, true); + } return baseOptions; } @@ -132,19 +132,17 @@ internal static class MSDeployUtility /// /// /// - internal static Generic.List ConvertStringIntoList(string linkExtensionsString) + internal static List ConvertStringIntoList(string? linkExtensionsString) { - string linkExtensionsInfo = ""; if (!string.IsNullOrEmpty(linkExtensionsString)) { - linkExtensionsInfo = linkExtensionsString; + string linkExtensionsInfo = linkExtensionsString!; string[] linksArray = linkExtensionsInfo.Split(new char[] { ';' }); - Generic.List linksList = new(linksArray); + List linksList = new(linksArray); return linksList; } else - return new System.Collections.Generic.List(0); - + return new List(0); } /// @@ -153,7 +151,7 @@ internal static Generic.List ConvertStringIntoList(string linkExtensions /// /// /// - internal static bool LinkContainedInTheCollection(string link, Generic.List linkCollection) + internal static bool LinkContainedInTheCollection(string link, List linkCollection) { foreach (string l in linkCollection) if (string.Compare(l, link, StringComparison.OrdinalIgnoreCase) == 0) @@ -171,7 +169,7 @@ public static void ChangeLinkExtensionEnableStatue(/*Deployment.DeploymentBaseOp { if (!string.IsNullOrEmpty(listOfLinkExtensions)) { - Generic.List linkExtensionList = ConvertStringIntoList(listOfLinkExtensions); + List linkExtensionList = ConvertStringIntoList(listOfLinkExtensions); ChangeLinkExtensionEnableStatue(baseOptions, linkExtensionList, enable); } } @@ -182,15 +180,14 @@ public static void ChangeLinkExtensionEnableStatue(/*Deployment.DeploymentBaseOp /// /// /// - public static void ChangeLinkExtensionEnableStatue(/*Deployment.DeploymentBaseOptions*/ dynamic baseOptions, System.Collections.Generic.List linkExtensions, bool enable) + public static void ChangeLinkExtensionEnableStatue(/*Deployment.DeploymentBaseOptions*/ dynamic baseOptions, List linkExtensions, bool enable) { - if (linkExtensions != null && linkExtensions.Count != 0) + if (linkExtensions is not null && linkExtensions.Count != 0) { foreach (string linkExtObj in linkExtensions) { - RegularExpressions.Regex match = new(linkExtObj, RegularExpressions.RegexOptions.IgnoreCase); - Generic.List matchedList = new(); + List matchedList = new(); foreach (/*Deployment.DeploymentLinkExtension*/dynamic linkExtension in baseOptions.LinkExtensions) { @@ -212,18 +209,17 @@ public static void ChangeLinkExtensionEnableStatue(/*Deployment.DeploymentBaseOp // throw new DeploymentException(Resources.UnknownLinkExtension, disableLink); //$Todo lmchen //Diagnostics.Debug.Assert(false, "NYI, we should prompt user for invalid LinkExtension"); - throw new System.InvalidOperationException("UnknowLinkExtension"); + throw new InvalidOperationException("UnknowLinkExtension"); } } } } } /// - /// Abstract interface to allow homogenious SynTo() operation to work regardless of the object + /// Abstract interface to allow homogeneous SynTo() operation to work regardless of the object /// internal class VSMSDeployObject { - public VSMSDeployObject(string provider, string root) { m_NameValueDictionary.Clear(); @@ -234,13 +230,13 @@ public VSMSDeployObject(string provider, string root) m_provider = provider; // maybe we should show the "secure data to display" - // for now just supress it. + // for now just suppress it. #if NET472 - if (0 == string.Compare(m_provider, MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.DBFullSql).ToString(), StringComparison.InvariantCultureIgnoreCase) + if (0 == string.Compare(m_provider, MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.DBFullSql)?.ToString(), StringComparison.InvariantCultureIgnoreCase) || 0 == string.Compare(m_provider, MSDeploy.Provider.DbDacFx , StringComparison.InvariantCultureIgnoreCase)) m_fNoDisplayRoot = true; #else - if (0 == string.Compare(m_provider, MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.DBFullSql).ToString()) + if (0 == string.Compare(m_provider, MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.DBFullSql)?.ToString()) || 0 == string.Compare(m_provider, MSDeploy.Provider.DbDacFx, StringComparison.OrdinalIgnoreCase)) m_fNoDisplayRoot = true; #endif @@ -250,7 +246,7 @@ public VSMSDeployObject(Build.Framework.ITaskItem taskItem) { Diagnostics.Debug.Assert(taskItem != null); - m_provider = taskItem.ItemSpec; + m_provider = taskItem!.ItemSpec; m_root = taskItem.GetMetadata("Path"); if (string.IsNullOrEmpty(m_root)) m_root = string.Empty; @@ -259,8 +255,8 @@ public VSMSDeployObject(Build.Framework.ITaskItem taskItem) Diagnostics.Debug.Assert(Utility.IsDeploymentWellKnownProvider(m_provider)); // maybe we should show the "secure data to display" - // for now just supress it. - if (0 == string.Compare(m_provider, MSWebDeploymentAssembly.DynamicAssembly.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.DBFullSql).ToString(), StringComparison.OrdinalIgnoreCase)) + // for now just suppress it. + if (0 == string.Compare(m_provider, MSWebDeploymentAssembly.DynamicAssembly?.GetEnumValue(MSDeploy.TypeName.DeploymentWellKnownProvider, MSDeploy.Provider.DBFullSql)?.ToString(), StringComparison.OrdinalIgnoreCase)) m_fNoDisplayRoot = true; m_NameValueDictionary.Clear(); @@ -284,8 +280,8 @@ public VSMSDeployObject(Build.Framework.ITaskItem taskItem) } else { - MsDeploy.Utility.IISExpressMetadata expressMetadata; - if (Enum.TryParse(name, out expressMetadata)) + Utility.IISExpressMetadata expressMetadata; + if (Enum.TryParse(name, out expressMetadata)) { string value = taskItem.GetMetadata(name); if (!string.IsNullOrEmpty(value)) @@ -296,7 +292,6 @@ public VSMSDeployObject(Build.Framework.ITaskItem taskItem) } } - } public VSMSDeployObject(Build.Framework.ITaskItem taskItem, bool fNoDisplayRoot) @@ -305,19 +300,19 @@ public VSMSDeployObject(Build.Framework.ITaskItem taskItem, bool fNoDisplayRoot) m_fNoDisplayRoot = fNoDisplayRoot; } - private string GetDictionaryValue(string name) + private string? GetDictionaryValue(string name) { - string value = null; + string? value = null; if (m_NameValueDictionary != null) { m_NameValueDictionary.TryGetValue(name, out value); } return value; } - private void SetDictionaryValue(string name, string value) + private void SetDictionaryValue(string name, string? value) { Diagnostics.Debug.Assert(m_NameValueDictionary != null); - if (m_NameValueDictionary.ContainsKey(name)) + if (m_NameValueDictionary!.ContainsKey(name)) { m_NameValueDictionary[name] = value; } @@ -335,14 +330,14 @@ private void SetDictionaryValue(string name, string value) protected int m_retryInterval = -1; protected int m_retryAttempts = -1; - Generic.IList m_iListParameter = new Generic.List(); - Generic.IList m_iListProviderOption = new Generic.List(); - Generic.IList m_iListParameterWithEntry = new Generic.List(); - Generic.IList m_iListSetParametersFiles = new Generic.List(); + IList m_iListParameter = new List(); + IList m_iListProviderOption = new List(); + IList m_iListParameterWithEntry = new List(); + IList m_iListSetParametersFiles = new List(); - private System.Collections.Generic.Dictionary m_NameValueDictionary = new(10, StringComparer.OrdinalIgnoreCase); + private Dictionary m_NameValueDictionary = new(10, StringComparer.OrdinalIgnoreCase); - protected /*Deployment.DeploymentBaseOptions*/ dynamic m_deploymentBaseOptions = null; + protected /*Deployment.DeploymentBaseOptions*/ dynamic? m_deploymentBaseOptions = null; public override string ToString() { @@ -350,7 +345,6 @@ public override string ToString() return string.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.VSMSDEPLOY_ObjectIdentity, m_provider.ToString(), root); } - // property used to call Deployment.DeploymentManager.CreateObject public virtual string Root { @@ -363,7 +357,6 @@ public virtual string Provider set { m_provider = value; } } - // property use to create the LocationInfo public virtual bool IsLocal { @@ -375,7 +368,6 @@ public virtual bool UseSeparatedCredential get { return !string.IsNullOrEmpty(UserName); } } - public virtual string DisableLinks { get { return m_disableLinks; } @@ -388,8 +380,6 @@ public virtual string EnableLinks set { m_enableLinks = value; } } - - // // -------------------------// bugbug, not supported yet // @@ -399,30 +389,29 @@ public virtual string EnableLinks // // - - public virtual string ComputerName + public virtual string? ComputerName { get { return GetDictionaryValue("computerName"); } set { SetDictionaryValue("computerName", value); } } - public virtual string UserName + public virtual string? UserName { get { return GetDictionaryValue("userName"); } set { SetDictionaryValue("userName", value); } } - public virtual string Password + public virtual string? Password { get { return GetDictionaryValue("password"); } set { SetDictionaryValue("password", value); } } // Note this support is still broken for vsmsdeploy - public string MSDeployServiceUrl + public string? MSDeployServiceUrl { get { - string value = GetDictionaryValue("wmsvc"); + string? value = GetDictionaryValue("wmsvc"); Diagnostics.Debug.Assert(string.IsNullOrEmpty(value), "Not yet implement"); return value; } @@ -433,11 +422,11 @@ public string MSDeployServiceUrl } } - public string AuthenticationType + public string? AuthenticationType { get { - string authType = GetDictionaryValue("authType"); + string? authType = GetDictionaryValue("authType"); if (string.IsNullOrEmpty(authType)) { if (!string.IsNullOrEmpty(MSDeployServiceUrl) && string.IsNullOrEmpty(ComputerName)) @@ -451,7 +440,7 @@ public string AuthenticationType set { SetDictionaryValue("authType", value); } } - public string EncryptPassword + public string? EncryptPassword { get { return GetDictionaryValue("encryptPassword"); } set { SetDictionaryValue("encryptPassword", value); } @@ -468,27 +457,24 @@ public bool PrefetchPayload set { SetDictionaryValue("prefetchPayload", value.ToString()); } } - - public string WebServerAppHostConfigDirectory + public string? WebServerAppHostConfigDirectory { get { return GetDictionaryValue("WebServerAppHostConfigDirectory"); } set { SetDictionaryValue("WebServerAppHostConfigDirectory", value); } } - public string WebServerDirectory + public string? WebServerDirectory { get { return GetDictionaryValue("WebServerDirectory"); } set { SetDictionaryValue("WebServerDirectory", value); } } - public string WebServerManifest + public string? WebServerManifest { get { return GetDictionaryValue("WebServerManifest"); } set { SetDictionaryValue("WebServerManifest", value); } } - - public int RetryAttempts { get { return m_retryAttempts; } @@ -501,16 +487,14 @@ public int RetryInterval set { m_retryInterval = value; } } - public string UserAgent { get; set; } - - + public string? UserAgent { get; set; } - public Generic.IList Parameters + public IList Parameters { get { return m_iListParameter; } } - public Generic.IList ProviderOptions + public IList ProviderOptions { get { return m_iListProviderOption; } } @@ -525,21 +509,19 @@ public void SyncParameter(string parameterName, string parameterStringValue) m_iListParameter.Add(new ParameterInfo(parameterName, parameterStringValue)); } - - public Generic.IList EntryParameters + public IList EntryParameters { get { return m_iListParameterWithEntry; } } - public Generic.IList SetParametersFiles + public IList SetParametersFiles { get { return m_iListSetParametersFiles; } } - public void SyncParameter(string name, string value, string type, string scope, string matchRegularExpression, string description, string defaultValue, string tags, string element, string validationString) { - m_iListParameterWithEntry.Add(new MsDeploy.ParameterInfoWithEntry(name, value, type, scope, matchRegularExpression, description, defaultValue, tags, element, validationString)); + m_iListParameterWithEntry.Add(new ParameterInfoWithEntry(name, value, type, scope, matchRegularExpression, description, defaultValue, tags, element, validationString)); } public void SyncParameterFile(string filename) @@ -553,7 +535,7 @@ public void ResetBaseOptions() m_deploymentBaseOptions = null; } - public /*Deployment.DeploymentBaseOptions*/ dynamic BaseOptions + public /*Deployment.DeploymentBaseOptions*/ dynamic? BaseOptions { get { @@ -565,18 +547,17 @@ public void ResetBaseOptions() } } - public void SyncTo(VSMSDeployObject destObject, /*VSMSDeploySyncOption*/ dynamic syncOptions, IVSMSDeployHost _host) { #if NET472 //$BUGBUG lmchen, there is only set to source provider? // set up the provider setting /*Deployment.DeploymentProviderOptions*/ - dynamic srcProviderConfig = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentProviderOptions", new object[]{Provider.ToString()}); - srcProviderConfig.Path = Root; + dynamic? srcProviderConfig = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentProviderOptions", new object[]{Provider.ToString()}); + srcProviderConfig!.Path = Root; Utility.AddProviderOptions(srcProviderConfig, ProviderOptions, _host); - using (/*Deployment.DeploymentObject*/ dynamic srcObj = MSWebDeploymentAssembly.DynamicAssembly.CallStaticMethod("Microsoft.Web.Deployment.DeploymentManager", "CreateObject", new object[]{srcProviderConfig, BaseOptions})) + using (/*Deployment.DeploymentObject*/ dynamic? srcObj = MSWebDeploymentAssembly.DynamicAssembly?.CallStaticMethod("Microsoft.Web.Deployment.DeploymentManager", "CreateObject", new object[]{srcProviderConfig, BaseOptions!})) { //$BUGBUG lmchen, there is only set to source provider? @@ -585,13 +566,13 @@ public void SyncTo(VSMSDeployObject destObject, /*VSMSDeploySyncOption*/ dynamic Utility.AddSimpleSetParametersToObject(srcObj, Parameters, _host); Utility.AddSetParametersToObject(srcObj, EntryParameters, _host); - /*Deployment.DeploymentProviderOptions*/ dynamic destProviderConfig = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentProviderOptions", new object[]{destObject.Provider.ToString()}); - destProviderConfig.Path = destObject.Root; + /*Deployment.DeploymentProviderOptions*/ dynamic? destProviderConfig = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentProviderOptions", new object[]{destObject.Provider.ToString()}); + destProviderConfig!.Path = destObject.Root; - // Setup Destination Provider otpion + // Setup Destination Provider option Utility.AddProviderOptions(destProviderConfig, destObject.ProviderOptions, _host); - srcObj.SyncTo(destProviderConfig, destObject.BaseOptions, syncOptions); + srcObj?.SyncTo(destProviderConfig, destObject.BaseOptions, syncOptions); } #endif } diff --git a/src/WebSdk/Publish/Tasks/Tasks/GenerateEFSQLScripts.cs b/src/WebSdk/Publish/Tasks/Tasks/GenerateEFSQLScripts.cs index a93ad31a066d..0cb2af889f08 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/GenerateEFSQLScripts.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/GenerateEFSQLScripts.cs @@ -12,17 +12,17 @@ namespace Microsoft.NET.Sdk.Publish.Tasks public class GenerateEFSQLScripts : Task { [Required] - public string ProjectDirectory { get; set; } + public string? ProjectDirectory { get; set; } [Required] - public string EFPublishDirectory { get; set; } + public string? EFPublishDirectory { get; set; } [Required] - public ITaskItem[] EFMigrations { get; set; } + public ITaskItem[]? EFMigrations { get; set; } [Required] - public string Configuration { get; set; } - public string EFSQLScriptsFolderName { get; set; } - public string EFMigrationsAdditionalArgs { get; set; } + public string? Configuration { get; set; } + public string? EFSQLScriptsFolderName { get; set; } + public string? EFMigrationsAdditionalArgs { get; set; } [Output] - public ITaskItem[] EFSQLScripts { get; set; } + public ITaskItem[]? EFSQLScripts { get; set; } public override bool Execute() { @@ -40,11 +40,11 @@ public override bool Execute() public bool GenerateEFSQLScriptsInternal(bool isLoggingEnabled = true) { InitializeProperties(); - EFSQLScripts = new ITaskItem[EFMigrations.Length]; + EFSQLScripts = new ITaskItem[EFMigrations!.Length]; int index = 0; foreach (ITaskItem dbContext in EFMigrations) { - string outputFileFullPath = Path.Combine(EFPublishDirectory, EFSQLScriptsFolderName, dbContext.ItemSpec + ".sql"); + string outputFileFullPath = Path.Combine(EFPublishDirectory!, EFSQLScriptsFolderName!, dbContext.ItemSpec + ".sql"); bool isScriptGenerationSuccessful = GenerateSQLScript(outputFileFullPath, dbContext.ItemSpec, isLoggingEnabled); if (!isScriptGenerationSuccessful) { @@ -72,14 +72,14 @@ private void InitializeProperties() } private object _sync = new(); - private Process _runningProcess; + private Process? _runningProcess; private int _processExitCode; private StringBuilder _standardOut = new(); private StringBuilder _standardError = new(); private const string AspNetCoreEnvironment = "ASPNETCORE_ENVIRONMENT"; private bool GenerateSQLScript(string sqlFileFullPath, string dbContextName, bool isLoggingEnabled = true) { - string previousAspNetCoreEnvironment = Environment.GetEnvironmentVariable(AspNetCoreEnvironment); + string? previousAspNetCoreEnvironment = Environment.GetEnvironmentVariable(AspNetCoreEnvironment); Environment.SetEnvironmentVariable(AspNetCoreEnvironment, "Development"); ProcessStartInfo psi = new("dotnet", $@"ef migrations script --no-build --idempotent --configuration {Configuration} --output ""{sqlFileFullPath}"" --context {dbContextName} {EFMigrationsAdditionalArgs}") { @@ -90,7 +90,7 @@ private bool GenerateSQLScript(string sqlFileFullPath, string dbContextName, boo UseShellExecute = false }; - Process proc = null; + Process? proc = null; try { @@ -141,7 +141,7 @@ private bool GenerateSQLScript(string sqlFileFullPath, string dbContextName, boo return true; } - private void Proc_Exited(object sender, EventArgs e) + private void Proc_Exited(object? sender, EventArgs e) { if (_runningProcess != null) { @@ -161,7 +161,6 @@ private void Proc_Exited(object sender, EventArgs e) _runningProcess = null; } } - } private void Proc_ErrorDataReceived(object sender, DataReceivedEventArgs e) diff --git a/src/WebSdk/Publish/Tasks/Tasks/GenerateEnvTransform.cs b/src/WebSdk/Publish/Tasks/Tasks/GenerateEnvTransform.cs index d3a802150e14..6e6c2828ed62 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/GenerateEnvTransform.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/GenerateEnvTransform.cs @@ -8,16 +8,16 @@ namespace Microsoft.NET.Sdk.Publish.Tasks public class GenerateEnvTransform : Task { [Required] - public string WebConfigEnvironmentVariables { get; set; } + public string? WebConfigEnvironmentVariables { get; set; } [Required] - public string[] EnvTransformTemplatePaths { get; set; } + public string[]? EnvTransformTemplatePaths { get; set; } [Required] - public string PublishTempDirectory { get; set; } + public string? PublishTempDirectory { get; set; } [Output] - public string[] GeneratedTransformFullPaths { get; set; } + public string[]? GeneratedTransformFullPaths { get; set; } public override bool Execute() { @@ -30,17 +30,17 @@ public override bool Execute() bool isSuccess = true; List generatedFiles = new(); - foreach (var envTransformTemplatePath in EnvTransformTemplatePaths) + foreach (var envTransformTemplatePath in EnvTransformTemplatePaths ?? Array.Empty()) { if (File.Exists(envTransformTemplatePath)) { string templateContent = File.ReadAllText(envTransformTemplatePath); XDocument templateContentDocument = XDocument.Parse(templateContent); - XDocument envTransformDoc = GenerateEnvTransformDocument(templateContentDocument, WebConfigEnvironmentVariables); + XDocument? envTransformDoc = GenerateEnvTransformDocument(templateContentDocument, WebConfigEnvironmentVariables!); if (envTransformDoc != null) { - string generatedTransformFileName = Path.Combine(PublishTempDirectory, Path.GetFileName(envTransformTemplatePath)); + string generatedTransformFileName = Path.Combine(PublishTempDirectory!, Path.GetFileName(envTransformTemplatePath)); envTransformDoc.Save(generatedTransformFileName, SaveOptions.None); generatedFiles.Add(generatedTransformFileName); } @@ -51,7 +51,7 @@ public override bool Execute() return isSuccess; } - public XDocument GenerateEnvTransformDocument(XDocument templateContentDocument, string webConfigEnvironmentVariables) + public XDocument? GenerateEnvTransformDocument(XDocument templateContentDocument, string webConfigEnvironmentVariables) { if (string.IsNullOrEmpty(webConfigEnvironmentVariables)) { @@ -85,7 +85,7 @@ public XDocument GenerateEnvTransformDocument(XDocument templateContentDocument, return updatedContent; } - public List> GetEnvironmentVariables(string webConfigEnvironmentVariables) + public List>? GetEnvironmentVariables(string webConfigEnvironmentVariables) { if (string.IsNullOrEmpty(webConfigEnvironmentVariables)) { diff --git a/src/WebSdk/Publish/Tasks/Tasks/Kudu/KuduDeploy.cs b/src/WebSdk/Publish/Tasks/Tasks/Kudu/KuduDeploy.cs index 5edacb6f6a2c..f8291202d77e 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/Kudu/KuduDeploy.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/Kudu/KuduDeploy.cs @@ -11,43 +11,42 @@ using Microsoft.NET.Sdk.Publish.Tasks.Properties; using Framework = Microsoft.Build.Framework; -using Utilities = Microsoft.Build.Utilities; namespace Microsoft.NET.Sdk.Publish.Tasks.Kudu { - public sealed class KuduDeploy : Utilities.Task + public sealed class KuduDeploy : Task { public static readonly int TimeoutMilliseconds = 180000; [Framework.Required] - public string PublishIntermediateOutputPath + public string? PublishIntermediateOutputPath { get; set; } [Framework.Required] - public string PublishUrl + public string? PublishUrl { get; set; } [Framework.Required] - public string UserName + public string? UserName { get; set; } [Framework.Required] - public string Password + public string? Password { get; set; } [Framework.Required] - public string PublishSiteName + public string? PublishSiteName { get; set; @@ -113,10 +112,10 @@ internal bool DeployFiles(KuduConnectionInfo connectionInfo) } // Deploy the files. - System.Threading.Tasks.Task deployTask = fileDeploy.DeployAsync(PublishIntermediateOutputPath); + System.Threading.Tasks.Task? deployTask = fileDeploy.DeployAsync(PublishIntermediateOutputPath); try { - success = deployTask.Wait(TimeoutMilliseconds); + success = deployTask?.Wait(TimeoutMilliseconds) ?? false; if (!success) { Log.LogError(string.Format(Resources.KUDUDEPLOY_AzurePublishErrorReason, Resources.KUDUDEPLOY_OperationTimeout)); @@ -138,8 +137,8 @@ internal bool DeployZipFile(KuduConnectionInfo connectionInfo) bool success; KuduZipDeploy zipDeploy = new(connectionInfo, Log); - string zipFileFullPath = CreateZipFile(PublishIntermediateOutputPath); - System.Threading.Tasks.Task zipTask = zipDeploy.DeployAsync(zipFileFullPath); + string? zipFileFullPath = CreateZipFile(PublishIntermediateOutputPath); + Task zipTask = zipDeploy.DeployAsync(zipFileFullPath); try { success = zipTask.Wait(TimeoutMilliseconds); @@ -160,7 +159,7 @@ internal bool DeployZipFile(KuduConnectionInfo connectionInfo) return success && zipTask.Result; } - internal string CreateZipFile(string sourcePath) + internal string? CreateZipFile(string? sourcePath) { // Zip the files from PublishOutput path. string zipFileFullPath = Path.Combine(Path.GetTempPath(), string.Format("Publish{0}.zip", new Random().Next(int.MaxValue))); @@ -168,7 +167,7 @@ internal string CreateZipFile(string sourcePath) try { - System.IO.Compression.ZipFile.CreateFromDirectory(sourcePath, zipFileFullPath); + System.IO.Compression.ZipFile.CreateFromDirectory(sourcePath!, zipFileFullPath); } catch (Exception e) { @@ -182,7 +181,7 @@ internal string CreateZipFile(string sourcePath) return zipFileFullPath; } - internal System.Threading.Tasks.Task DeleteTempZipFile(string tempFilePath) + internal System.Threading.Tasks.Task DeleteTempZipFile(string? tempFilePath) { return System.Threading.Tasks.Task.Factory.StartNew( () => diff --git a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateMSDeployScript.cs b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateMSDeployScript.cs index dfdde9ab4586..f85538f4574a 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateMSDeployScript.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateMSDeployScript.cs @@ -9,29 +9,29 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy public class CreateMSDeployScript : Task { [Required] - public string ProjectName { get; set; } + public string? ProjectName { get; set; } [Required] - public string ScriptFullPath { get; set; } + public string? ScriptFullPath { get; set; } [Required] - public string ReadMeFullPath { get; set; } + public string? ReadMeFullPath { get; set; } public override bool Execute() { if (!File.Exists(ScriptFullPath)) { - File.Create(ScriptFullPath); + File.Create(ScriptFullPath!); } - File.WriteAllLines(ScriptFullPath, GetReplacedFileContents(Resources.MsDeployBatchFile)); + File.WriteAllLines(ScriptFullPath!, GetReplacedFileContents(Resources.MsDeployBatchFile)); if (!File.Exists(ReadMeFullPath)) { - File.Create(ReadMeFullPath); + File.Create(ReadMeFullPath!); } - File.WriteAllLines(ReadMeFullPath, GetReplacedFileContents(Resources.MsDeployReadMe)); + File.WriteAllLines(ReadMeFullPath!, GetReplacedFileContents(Resources.MsDeployReadMe)); return true; } @@ -41,7 +41,7 @@ private string[] GetReplacedFileContents(string fileContents) var lines = fileContents.Split(new string[] { Environment.NewLine, "\n" }, StringSplitOptions.None); for (int i = 0; i < lines.Length; i++) { - lines[i] = lines[i]?.Replace("$$ProjectName$$", ProjectName); + lines![i] = lines[i]!.Replace("$$ProjectName$$", ProjectName); } return lines; diff --git a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateManifestFile.cs b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateManifestFile.cs index 8bc1ba38cbd3..0d7791723e67 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateManifestFile.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateManifestFile.cs @@ -9,34 +9,33 @@ /// /// Copyright(c) 2006 Microsoft Corporation ///-------------------------------------------------------------------------------------------- + +using Framework = Microsoft.Build.Framework; +using Utilities = Microsoft.Build.Utilities; +using Xml = System.Xml; + namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy { - using System.IO; - using Framework = Microsoft.Build.Framework; - using Utilities = Microsoft.Build.Utilities; - using Xml = System.Xml; - - public class CreateManifestFile : Utilities.Task + public class CreateManifestFile : Task { - private Framework.ITaskItem[] m_manifests = null; - private string m_manifestFile = null; + private Framework.ITaskItem[]? m_manifests = null; + private string? m_manifestFile = null; private bool m_generateFileEvenIfEmpty = false; [Framework.Required] - public Framework.ITaskItem[] Manifests + public Framework.ITaskItem[]? Manifests { get { return m_manifests; } set { m_manifests = value; } } [Framework.Required] - public string ManifestFile + public string? ManifestFile { get { return m_manifestFile; } set { m_manifestFile = value; } } - public bool GenerateFileEvenIfEmpty { get { return m_generateFileEvenIfEmpty; } @@ -49,7 +48,7 @@ public bool GenerateFileEvenIfEmpty /// /// /// - private static void WriteManifestsToFile(Utilities.TaskLoggingHelper loggingHelper, Framework.ITaskItem[] items, string outputFileName) + private static void WriteManifestsToFile(Utilities.TaskLoggingHelper loggingHelper, Framework.ITaskItem[]? items, string outputFileName) { Xml.XmlDocument document = new(); Xml.XmlElement manifestElement = document.CreateElement("sitemanifest"); @@ -108,17 +107,17 @@ public override bool Execute() { File.Create(ManifestFile); } - WriteManifestsToFile(Log, m_manifests, ManifestFile); + WriteManifestsToFile(Log, m_manifests, ManifestFile!); } } #if NET472 - catch (System.Xml.XmlException ex) + catch (Xml.XmlException ex) { - System.Uri sourceUri = new(ex.SourceUri); + Uri sourceUri = new(ex.SourceUri); succeeded = false; } #endif - catch (System.Exception) + catch (Exception) { succeeded = false; } @@ -132,7 +131,4 @@ public override bool Execute() return succeeded; } } - - - } diff --git a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateParameterFile.cs b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateParameterFile.cs index 8839a38e0798..9ac061ea59d0 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateParameterFile.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/CreateParameterFile.cs @@ -1,44 +1,42 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Text.RegularExpressions; +using Framework = Microsoft.Build.Framework; +using Utilities = Microsoft.Build.Utilities; +using Xml = System.Xml; + namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy { - using System.IO; - using System.Text.RegularExpressions; - using Microsoft.Build.Utilities; - using Framework = Microsoft.Build.Framework; - using Utilities = Microsoft.Build.Utilities; - using Xml = System.Xml; - public class CreateParameterFile : Task { - private Framework.ITaskItem[] m_parameters = null; - private string m_declareParametersFile = null; - private string m_declareSetParametersFile = null; - private string m_setParametersFile = null; + private Framework.ITaskItem[]? m_parameters = null; + private string? m_declareParametersFile = null; + private string? m_declareSetParametersFile = null; + private string? m_setParametersFile = null; private bool m_generateFileEvenIfEmpty = false; private bool m_includeDefaultValue = false; [Framework.Required] - public Framework.ITaskItem[] Parameters + public Framework.ITaskItem[]? Parameters { get { return m_parameters; } set { m_parameters = value; } } - public string DeclareParameterFile + public string? DeclareParameterFile { get { return m_declareParametersFile; } set { m_declareParametersFile = value; } } - public string DeclareSetParameterFile + public string? DeclareSetParameterFile { get { return m_declareSetParametersFile; } set { m_declareSetParametersFile = value; } } - public string SetParameterFile + public string? SetParameterFile { get { return m_setParametersFile; } set { m_setParametersFile = value; } @@ -66,13 +64,13 @@ public bool IncludeDefaultValue private static readonly string[] s_setParameterAttributes = { SyncParameterMetadata.Description.ToString().ToLowerInvariant(), SyncParameterMetadata.Value.ToString().ToLowerInvariant(), SyncParameterMetadata.Tags.ToString().ToLowerInvariant(),}; - private static readonly string[] s_parameterEntryIdentities = { ExistingParameterValiationMetadata.Element.ToString().ToLowerInvariant(), + private static readonly string[] s_parameterEntryIdentities = { ExistingParameterValidationMetadata.Element.ToString().ToLowerInvariant(), ExistingDeclareParameterMetadata.Kind.ToString().ToLowerInvariant(), ExistingDeclareParameterMetadata.Scope.ToString().ToLowerInvariant(), ExistingDeclareParameterMetadata.Match.ToString().ToLowerInvariant(),}; - private static readonly string[] s_parameterValidationIdentities = { ExistingParameterValiationMetadata.Element.ToString().ToLowerInvariant(), - ExistingParameterValiationMetadata.Kind.ToString().ToLowerInvariant(), + private static readonly string[] s_parameterValidationIdentities = { ExistingParameterValidationMetadata.Element.ToString().ToLowerInvariant(), + ExistingParameterValidationMetadata.Kind.ToString().ToLowerInvariant(), "validationString",}; /// @@ -81,19 +79,18 @@ public bool IncludeDefaultValue /// /// /// - private static void WriteDeclareParametersToFile(Utilities.TaskLoggingHelper loggingHelper, Framework.ITaskItem[] parameters, string outputFileName, bool foptimisticParameterDefaultValue) + private static void WriteDeclareParametersToFile(Utilities.TaskLoggingHelper loggingHelper, Framework.ITaskItem[]? parameters, string outputFileName, bool foptimisticParameterDefaultValue) { WriteDeclareParametersToFile(loggingHelper, parameters, s_parameterAttributes, outputFileName, foptimisticParameterDefaultValue, DeclareParameterMetadata.DefaultValue.ToString()); } - private static void WriteDeclareSetParametersToFile(Utilities.TaskLoggingHelper loggingHelper, Framework.ITaskItem[] parameters, string outputFileName, bool foptimisticParameterDefaultValue) + private static void WriteDeclareSetParametersToFile(Utilities.TaskLoggingHelper loggingHelper, Framework.ITaskItem[]? parameters, string outputFileName, bool foptimisticParameterDefaultValue) { WriteDeclareParametersToFile(loggingHelper, parameters, s_setParameterAttributes, outputFileName, foptimisticParameterDefaultValue, SyncParameterMetadata.Value.ToString()); } - private static void WriteDeclareParametersToFile(Utilities.TaskLoggingHelper loggingHelper, - Framework.ITaskItem[] parameters, + Framework.ITaskItem[]? parameters, string[] parameterAttributes, string outputFileName, bool foptimisticParameterDefaultValue, @@ -105,17 +102,17 @@ private static void WriteDeclareParametersToFile(Utilities.TaskLoggingHelper log if (parameters != null) { - System.Collections.Generic.Dictionary dictionaryLookup + Dictionary dictionaryLookup = new(parameters.GetLength(0), StringComparer.OrdinalIgnoreCase); // we are on purpose to keep the order without optimistic change the Value/Default base on the non-null optimistic - System.Collections.Generic.IList items + IList items = Utility.SortParametersTaskItems(parameters, foptimisticParameterDefaultValue, optimisticParameterMetadata); foreach (Framework.ITaskItem item in items) { string name = item.ItemSpec; - Xml.XmlElement parameterElement = null; + Xml.XmlElement? parameterElement; bool fCreateNew = false; if (!dictionaryLookup.TryGetValue(name, out parameterElement)) { @@ -132,7 +129,7 @@ private static void WriteDeclareParametersToFile(Utilities.TaskLoggingHelper log } if (parameterElement != null) { - string elementValue = item.GetMetadata(ExistingParameterValiationMetadata.Element.ToString()); + string elementValue = item.GetMetadata(ExistingParameterValidationMetadata.Element.ToString()); if (string.IsNullOrEmpty(elementValue)) elementValue = "parameterEntry"; @@ -175,7 +172,7 @@ private static void WriteDeclareParametersToFile(Utilities.TaskLoggingHelper log bool fIdentical = false; foreach (Xml.XmlNode childNode in parameterElement.ChildNodes) { - Xml.XmlElement childElement = childNode as Xml.XmlElement; + Xml.XmlElement? childElement = childNode as Xml.XmlElement; if (childElement != null) { if (string.Compare(childElement.Name, identityValues[0], StringComparison.OrdinalIgnoreCase) == 0) @@ -183,7 +180,7 @@ private static void WriteDeclareParametersToFile(Utilities.TaskLoggingHelper log fIdentical = true; for (int i = 1; i < parameterIdentitiesCount; i++) { - // case sensitive comparesion should be O.K. + // case sensitive comparison should be O.K. if (string.CompareOrdinal(identityValues[i], childElement.GetAttribute(parameterIdentities[i])) != 0) { fIdentical = false; @@ -233,18 +230,18 @@ private static void WriteDeclareParametersToFile(Utilities.TaskLoggingHelper log /// /// /// - private static void WriteSetParametersToFile(Utilities.TaskLoggingHelper loggingHelper, Framework.ITaskItem[] parameters, string outputFileName, bool foptimisticParameterDefaultValue) + private static void WriteSetParametersToFile(Utilities.TaskLoggingHelper loggingHelper, Framework.ITaskItem[]? parameters, string outputFileName, bool foptimisticParameterDefaultValue) { Xml.XmlDocument document = new(); Xml.XmlElement parametersElement = document.CreateElement("parameters"); document.AppendChild(parametersElement); if (parameters != null) { - System.Collections.Generic.IList items + IList items = Utility.SortParametersTaskItems(parameters, foptimisticParameterDefaultValue, SimpleSyncParameterMetadata.Value.ToString()); // only the first value win - System.Collections.Generic.Dictionary dictionaryLookup + Dictionary dictionaryLookup = new(parameters.GetLength(0)); foreach (Framework.ITaskItem item in items) @@ -286,38 +283,38 @@ public override bool Execute() { if (!File.Exists(DeclareSetParameterFile)) { - File.Create(DeclareSetParameterFile); + File.Create(DeclareSetParameterFile!); } if (!string.IsNullOrEmpty(DeclareParameterFile)) { - WriteDeclareParametersToFile(Log, m_parameters, DeclareParameterFile, OptimisticParameterDefaultValue); + WriteDeclareParametersToFile(Log, m_parameters, DeclareParameterFile!, OptimisticParameterDefaultValue); } if (!string.IsNullOrEmpty(SetParameterFile)) { - WriteSetParametersToFile(Log, m_parameters, SetParameterFile, OptimisticParameterDefaultValue); + WriteSetParametersToFile(Log, m_parameters, SetParameterFile!, OptimisticParameterDefaultValue); } if (!string.IsNullOrEmpty(DeclareSetParameterFile)) { if (IncludeDefaultValue) { - WriteDeclareSetParametersToFile(Log, m_parameters, DeclareSetParameterFile, true /*OptimisticParameterDefaultValue */); + WriteDeclareSetParametersToFile(Log, m_parameters, DeclareSetParameterFile!, true /*OptimisticParameterDefaultValue */); } else { - WriteDeclareSetParametersToFile(Log, m_parameters, DeclareSetParameterFile, OptimisticParameterDefaultValue); + WriteDeclareSetParametersToFile(Log, m_parameters, DeclareSetParameterFile!, OptimisticParameterDefaultValue); } } } #if NET472 - catch (System.Xml.XmlException ex) + catch (Xml.XmlException ex) { - System.Uri sourceUri = new(ex.SourceUri); + Uri sourceUri = new(ex.SourceUri); succeeded = false; } #endif - catch (System.Exception) + catch (Exception) { succeeded = false; } diff --git a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/GetPassword.cs b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/GetPassword.cs index 3d085cfd2505..0ff88c731589 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/GetPassword.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/GetPassword.cs @@ -7,10 +7,10 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy { public class GetPassword : Task { - public string EncryptedPassword { get; set; } + public string? EncryptedPassword { get; set; } [Output] - public string ClearPassword { get; set; } + public string? ClearPassword { get; set; } public override bool Execute() { @@ -22,7 +22,7 @@ public override bool Execute() return true; } - public string GetClearTextPassword(string base64EncodedString) + public string? GetClearTextPassword(string? base64EncodedString) { if (base64EncodedString == null) { diff --git a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/ImportParameterFile.cs b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/ImportParameterFile.cs index e7bb4af75c4e..9f7f7b81ab1a 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/ImportParameterFile.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/ImportParameterFile.cs @@ -1,26 +1,24 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics; +using Microsoft.Build.Utilities; +using Microsoft.NET.Sdk.Publish.Tasks.MsDeploy; +using Microsoft.NET.Sdk.Publish.Tasks.Properties; +using Microsoft.NET.Sdk.Publish.Tasks.Xdt; +using Microsoft.Web.XmlTransform; +using Framework = Microsoft.Build.Framework; +using Xml = System.Xml; + namespace Microsoft.NET.Sdk.Publish.Tasks.Tasks.MsDeploy { - using System.Diagnostics; - using System.IO; - using Microsoft.Build.Utilities; - using Microsoft.NET.Sdk.Publish.Tasks.MsDeploy; - using Microsoft.NET.Sdk.Publish.Tasks.Properties; - using Microsoft.NET.Sdk.Publish.Tasks.Xdt; - using Microsoft.Web.XmlTransform; - using Framework = Build.Framework; - using Utilities = Build.Utilities; - using Xml = System.Xml; - public class ImportParameterFile : Task { - private Framework.ITaskItem[] m_sourceFiles = null; + private Framework.ITaskItem[]? m_sourceFiles = null; private List m_parametersList = new(8); [Framework.Required] - public Framework.ITaskItem[] Files + public Framework.ITaskItem[]? Files { get { return m_sourceFiles; } set { m_sourceFiles = value; } @@ -32,7 +30,6 @@ public Framework.ITaskItem[] Result get { return m_parametersList.ToArray(); } } - public bool DisableEscapeMSBuildVariable { get; @@ -46,11 +43,11 @@ public bool DisableEscapeMSBuildVariable private void ReadParametersElement(Xml.XmlElement element) { Debug.Assert(element != null); - if (string.Compare(element.Name, "parameters", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(element!.Name, "parameters", StringComparison.OrdinalIgnoreCase) == 0) { foreach (Xml.XmlNode childNode in element.ChildNodes) { - Xml.XmlElement childElement = childNode as Xml.XmlElement; + Xml.XmlElement? childElement = childNode as Xml.XmlElement; if (childElement != null) { ReadParameterElement(childElement); @@ -66,12 +63,12 @@ private void ReadParametersElement(Xml.XmlElement element) private void ReadParameterElement(Xml.XmlElement element) { Debug.Assert(element != null); - if (string.Compare(element.Name, "parameter", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(element!.Name, "parameter", StringComparison.OrdinalIgnoreCase) == 0) { - Xml.XmlAttribute nameAttribute = element.Attributes.GetNamedItem("name") as Xml.XmlAttribute; + Xml.XmlAttribute? nameAttribute = element.Attributes.GetNamedItem("name") as Xml.XmlAttribute; if (nameAttribute != null) { - Utilities.TaskItem taskItem = new(nameAttribute.Value); + TaskItem taskItem = new(nameAttribute.Value); foreach (Xml.XmlNode attribute in element.Attributes) { string attributeName = attribute.Name.ToLower(System.Globalization.CultureInfo.InvariantCulture); @@ -82,22 +79,22 @@ private void ReadParameterElement(Xml.XmlElement element) { continue; } - string value = DisableEscapeMSBuildVariable ? attribute.Value : Utility.EscapeTextForMSBuildVariable(attribute.Value); + string? value = DisableEscapeMSBuildVariable ? attribute.Value : Utility.EscapeTextForMSBuildVariable(attribute.Value); taskItem.SetMetadata(attribute.Name, value); } - // work around the MSDeploy.exe limition of the Parameter must have the ParameterEntry. + // work around the MSDeploy.exe limitation of the Parameter must have the ParameterEntry. // m_parametersList.Add(taskItem); bool fAddNoParameterEntryParameter = true; foreach (Xml.XmlNode childNode in element.ChildNodes) { - Xml.XmlElement childElement = childNode as Xml.XmlElement; + Xml.XmlElement? childElement = childNode as Xml.XmlElement; if (childElement != null) { - Utilities.TaskItem childEntry = ReadParameterEntryElement(childElement, taskItem); + TaskItem? childEntry = ReadParameterEntryElement(childElement, taskItem); if (childEntry != null) { - fAddNoParameterEntryParameter = false; // we have Parameter entry, supress adding the Parameter with no entry + fAddNoParameterEntryParameter = false; // we have Parameter entry, suppress adding the Parameter with no entry m_parametersList.Add(childEntry); } } @@ -118,33 +115,33 @@ private void ReadParameterElement(Xml.XmlElement element) /// /// /// - private Utilities.TaskItem ReadParameterEntryElement(Xml.XmlElement element, Utilities.TaskItem parentItem) + private TaskItem? ReadParameterEntryElement(Xml.XmlElement element, TaskItem parentItem) { Debug.Assert(element != null && parentItem != null); - Utilities.TaskItem taskItem = null; - if (string.Compare(element.Name, "parameterEntry", StringComparison.OrdinalIgnoreCase) == 0) + TaskItem? taskItem = null; + if (string.Compare(element!.Name, "parameterEntry", StringComparison.OrdinalIgnoreCase) == 0) { - taskItem = new Microsoft.Build.Utilities.TaskItem(parentItem); + taskItem = new TaskItem(parentItem); taskItem.RemoveMetadata("OriginalItemSpec"); foreach (Xml.XmlNode attribute in element.Attributes) { if (attribute != null && attribute.Name != null && attribute.Value != null) { - string value = DisableEscapeMSBuildVariable ? attribute.Value : Utility.EscapeTextForMSBuildVariable(attribute.Value); + string? value = DisableEscapeMSBuildVariable ? attribute.Value : Utility.EscapeTextForMSBuildVariable(attribute.Value); taskItem.SetMetadata(attribute.Name, value); } } } else if (string.Compare(element.Name, "parameterValidation", StringComparison.OrdinalIgnoreCase) == 0) { - taskItem = new Microsoft.Build.Utilities.TaskItem(parentItem); + taskItem = new TaskItem(parentItem); taskItem.RemoveMetadata("OriginalItemSpec"); taskItem.SetMetadata("Element", "parameterValidation"); foreach (Xml.XmlNode attribute in element.Attributes) { if (attribute != null && attribute.Name != null && attribute.Value != null) { - string value = DisableEscapeMSBuildVariable ? attribute.Value : Utility.EscapeTextForMSBuildVariable(attribute.Value); + string? value = DisableEscapeMSBuildVariable ? attribute.Value : Utility.EscapeTextForMSBuildVariable(attribute.Value); taskItem.SetMetadata(attribute.Name, value); } } @@ -178,7 +175,7 @@ public override bool Execute() document.Load(filePath); foreach (Xml.XmlNode node in document.ChildNodes) { - Xml.XmlElement element = node as Xml.XmlElement; + Xml.XmlElement? element = node as Xml.XmlElement; if (element != null) { ReadParametersElement(element); @@ -186,13 +183,13 @@ public override bool Execute() } } } - catch (System.Xml.XmlException ex) + catch (Xml.XmlException ex) { - System.Uri sourceUri = new(ex.SourceUri); + Uri sourceUri = new(ex.SourceUri!); logger.LogError(sourceUri.LocalPath, ex.LineNumber, ex.LinePosition, ex.Message); succeeded = false; } - catch (System.Exception ex) + catch (Exception ex) { logger.LogErrorFromException(ex); succeeded = false; diff --git a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/MSDeploy.cs b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/MSDeploy.cs index a6bfb6a4f5fa..eea4b42d9e8b 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/MSDeploy.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/MSDeploy.cs @@ -1,16 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.NET.Sdk.Publish.Tasks.Properties; +using CultureInfo = System.Globalization.CultureInfo; +using Framework = Microsoft.Build.Framework; +using Utilities = Microsoft.Build.Utilities; + namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy { - using System; - using System.Linq; - using Microsoft.NET.Sdk.Publish.Tasks.Properties; - using CultureInfo = System.Globalization.CultureInfo; - using Framework = Microsoft.Build.Framework; - using IO = System.IO; - using Utilities = Microsoft.Build.Utilities; - /// /// The MSDeploy task, which is a wrapper around msdeploy.exe /// @@ -152,19 +149,19 @@ duration of a remote operation */ - private string m_exePath; - private string m_disableRule; - private string m_verb; - private string m_failureLevel; - private string m_xpath; - private string m_enableRule; - private string m_replace; - private string m_skip; - private string m_disableLink; - private string m_enableLink; - private string m_disableSkipDirective; - private string m_enableSkipDirective; - private string m_lastCommandLine; + private string? m_exePath; + private string? m_disableRule; + private string? m_verb; + private string? m_failureLevel; + private string? m_xpath; + private string? m_enableRule; + private string? m_replace; + private string? m_skip; + private string? m_disableLink; + private string? m_enableLink; + private string? m_disableSkipDirective; + private string? m_enableSkipDirective; + private string? m_lastCommandLine; private bool m_xml; private bool m_whatif; private bool m_useChecksum; @@ -174,27 +171,25 @@ duration of a remote operation private int m_retryAttempts; private int m_retryInterval; private bool m_useDoubleQuoteForValue = false; - private string m_strValueQuote = null; + private string? m_strValueQuote = null; //public const string AppHostConfigDirectory = "-appHostConfigDir"; // * public const string WebServerDirectory = "-webServerDir"; // public const string WebServerManifest = "-webServerManifest"; - public string WebServerAppHostConfigDirectory { get; set; } - public string WebServerDirectory { get; set; } - public string WebServerManifest { get; set; } - - - private Framework.ITaskItem[] m_sourceITaskItem = null; - private Framework.ITaskItem[] m_destITaskItem = null; - private Framework.ITaskItem[] m_replaceRuleItemsITaskItem = null; - private Framework.ITaskItem[] m_skipRuleItemsITaskItem = null; - private Framework.ITaskItem[] m_declareParameterItems = null; - private Framework.ITaskItem[] m_importDeclareParametersItems = null; - private Framework.ITaskItem[] m_simpleSetParamterItems = null; - private Framework.ITaskItem[] m_importSetParametersItems = null; - private Framework.ITaskItem[] m_setParamterItems = null; + public string? WebServerAppHostConfigDirectory { get; set; } + public string? WebServerDirectory { get; set; } + public string? WebServerManifest { get; set; } + private Framework.ITaskItem[]? m_sourceITaskItem = null; + private Framework.ITaskItem[]? m_destITaskItem = null; + private Framework.ITaskItem[]? m_replaceRuleItemsITaskItem = null; + private Framework.ITaskItem[]? m_skipRuleItemsITaskItem = null; + private Framework.ITaskItem[]? m_declareParameterItems = null; + private Framework.ITaskItem[]? m_importDeclareParametersItems = null; + private Framework.ITaskItem[]? m_simpleSetParamterItems = null; + private Framework.ITaskItem[]? m_importSetParametersItems = null; + private Framework.ITaskItem[]? m_setParamterItems = null; private bool m_previewOnly = false; @@ -223,11 +218,10 @@ public class Extensions public static readonly string DbDacFx = ".dacpac"; } - /// /// Location for the MSdeploy.exe path /// - public string ExePath + public string? ExePath { get { @@ -294,27 +288,27 @@ public string ExePath set { m_exePath = value; } } - public string DisableRule + public string? DisableRule { get { return m_disableRule; } set { m_disableRule = value; } } [Framework.Required] - public string Verb + public string? Verb { get { return m_verb; } set { m_verb = value; } } [Framework.Required] - public Framework.ITaskItem[] Source + public Framework.ITaskItem[]? Source { get { return m_sourceITaskItem; } set { m_sourceITaskItem = value; } } - public Framework.ITaskItem[] Destination + public Framework.ITaskItem[]? Destination { get { return m_destITaskItem; } set { m_destITaskItem = value; } @@ -344,7 +338,7 @@ public bool Verbose get { return m_verbose; } set { m_verbose = value; } } - public string FailureLevel + public string? FailureLevel { get { return m_failureLevel; } set { m_failureLevel = value; } @@ -354,33 +348,33 @@ public bool Xml get { return m_xml; } set { m_xml = value; } } - public string XPath + public string? XPath { get { return m_xpath; } set { m_xpath = value; } } - public string EnableRule + public string? EnableRule { get { return m_enableRule; } set { m_enableRule = value; } } - public string Replace + public string? Replace { get { return m_replace; } set { m_replace = value; } } - public string Skip + public string? Skip { get { return m_skip; } set { m_skip = value; } } - public string DisableLink + public string? DisableLink { get { return m_disableLink; } set { m_disableLink = value; } } - public string EnableLink + public string? EnableLink { get { return m_enableLink; } set { m_enableLink = value; } @@ -412,72 +406,70 @@ public bool UseDoubleQuoteForValue } } - public Framework.ITaskItem[] ReplaceRuleItems + public Framework.ITaskItem[]? ReplaceRuleItems { get { return m_replaceRuleItemsITaskItem; } set { m_replaceRuleItemsITaskItem = value; } } - public Framework.ITaskItem[] SkipRuleItems + public Framework.ITaskItem[]? SkipRuleItems { get { return m_skipRuleItemsITaskItem; } set { m_skipRuleItemsITaskItem = value; } } - public string DisableSkipDirective + public string? DisableSkipDirective { get { return m_disableSkipDirective; } set { m_disableSkipDirective = value; } } - public string EnableSkipDirective + public string? EnableSkipDirective { get { return m_enableSkipDirective; } set { m_enableSkipDirective = value; } } - public Framework.ITaskItem[] DeclareParameterItems + public Framework.ITaskItem[]? DeclareParameterItems { get { return m_declareParameterItems; } set { m_declareParameterItems = value; } } - public Framework.ITaskItem[] ImportDeclareParametersItems + public Framework.ITaskItem[]? ImportDeclareParametersItems { get { return m_importDeclareParametersItems; } set { m_importDeclareParametersItems = value; } } - - public Framework.ITaskItem[] ImportSetParametersItems + public Framework.ITaskItem[]? ImportSetParametersItems { get { return m_importSetParametersItems; } set { m_importSetParametersItems = value; } } - public Framework.ITaskItem[] SimpleSetParameterItems + public Framework.ITaskItem[]? SimpleSetParameterItems { get { return m_simpleSetParamterItems; } set { m_simpleSetParamterItems = value; } } - - public Framework.ITaskItem[] SetParameterItems + public Framework.ITaskItem[]? SetParameterItems { get { return m_setParamterItems; } set { m_setParamterItems = value; } } - public Framework.ITaskItem[] AdditionalDestinationProviderOptions { get; set; } + public Framework.ITaskItem[]? AdditionalDestinationProviderOptions { get; set; } - string _userAgent; - public string UserAgent + private string? _userAgent; + public string? UserAgent { get { return _userAgent; } set { if (!string.IsNullOrEmpty(value)) { - _userAgent = Utility.GetFullUserAgentString(value); + _userAgent = Utility.GetFullUserAgentString(value!); } } } @@ -533,7 +525,6 @@ protected override bool SkipTaskExecution() return base.SkipTaskExecution(); } - protected override Framework.MessageImportance StandardOutputLoggingImportance { get @@ -567,7 +558,7 @@ public override bool Execute() if (bSuccess) Log.LogMessage(Framework.MessageImportance.Normal, Resources.MSDEPLOY_EXE_Succeeded); } - catch (System.Exception ex) + catch (Exception ex) { // Log Failure Log.LogMessage(Framework.MessageImportance.High, Resources.MSDEPLOY_EXE_Failed); @@ -578,7 +569,7 @@ public override bool Execute() { string type = string.Empty; string path = string.Empty; - Framework.ITaskItem taskItem = null; + Framework.ITaskItem? taskItem = null; if (Destination != null && Destination.GetLength(0) == 1) { taskItem = Destination[0]; @@ -598,63 +589,58 @@ public override bool Execute() return bSuccess; } - - // utility function to add the replace rule for the option - public static void AddReplaceRulesToOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[] replaceRuleItems, string valueQuoteChar) + public static void AddReplaceRulesToOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[]? replaceRuleItems, string? valueQuoteChar) { - if (commandLineBuilder != null - && replaceRuleItems != null)// Dev10 bug 496639 foreach will throw the exception if the replaceRuleItem is null + if (commandLineBuilder is not null && replaceRuleItems is not null)// Dev10 bug 496639 foreach will throw the exception if the replaceRuleItem is null { - System.Collections.Generic.List arguments = new(6); + List arguments = new(6); foreach (Framework.ITaskItem item in replaceRuleItems) { arguments.Clear(); - Utility.BuildArgumentsBaseOnEnumTypeName(item, arguments, typeof(MsDeploy.ReplaceRuleMetadata), valueQuoteChar); + Utility.BuildArgumentsBaseOnEnumTypeName(item, arguments, typeof(ReplaceRuleMetadata), valueQuoteChar); commandLineBuilder.AppendSwitchUnquotedIfNotNull("-replace:", arguments.Count == 0 ? null : string.Join(",", arguments.ToArray())); } } } - public static void AddSkipDirectiveToBaseOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[] skipRuleItems, string valueQuoteChar) + public static void AddSkipDirectiveToBaseOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[]? skipRuleItems, string? valueQuoteChar) { - if (commandLineBuilder != null - && skipRuleItems != null)// Dev10 bug 496639 foreach will throw the exception if the replaceRuleItem is null + if (commandLineBuilder is not null && skipRuleItems is not null)// Dev10 bug 496639 foreach will throw the exception if the replaceRuleItem is null { - System.Collections.Generic.List arguments = new(6); + List arguments = new(6); foreach (Framework.ITaskItem item in skipRuleItems) { arguments.Clear(); - Utility.BuildArgumentsBaseOnEnumTypeName(item, arguments, typeof(MsDeploy.SkipRuleMetadata), valueQuoteChar); + Utility.BuildArgumentsBaseOnEnumTypeName(item, arguments, typeof(SkipRuleMetadata), valueQuoteChar); commandLineBuilder.AppendSwitchUnquotedIfNotNull("-skip:", arguments.Count == 0 ? null : string.Join(",", arguments.ToArray())); } } } - - public static void AddDeclareParameterToCommandArgument(System.Collections.Generic.List arguments, - Framework.ITaskItem item, - string valueQuote, - System.Collections.Generic.Dictionary lookupDictionary) + public static void AddDeclareParameterToCommandArgument(List arguments, + Framework.ITaskItem? item, + string? valueQuote, + Dictionary lookupDictionary) { - if (arguments != null && item != null && lookupDictionary != null) + if (arguments is not null && item is not null && lookupDictionary is not null) { // special for the name arguments.Clear(); - System.Collections.Generic.List idenities = new(6); + List idenities = new(6); string name = item.ItemSpec; if (!string.IsNullOrEmpty(name)) { - string element = item.GetMetadata(ExistingParameterValiationMetadata.Element.ToString()); + string element = item.GetMetadata(ExistingParameterValidationMetadata.Element.ToString()); if (string.IsNullOrEmpty(element)) element = "parameterEntry"; if (string.Compare(element, "parameterEntry", StringComparison.OrdinalIgnoreCase) == 0) { idenities.Add(name); - foreach (string dPIdentity in Enum.GetNames(typeof(MsDeploy.ExistingDeclareParameterMetadata))) + foreach (string dPIdentity in Enum.GetNames(typeof(ExistingDeclareParameterMetadata))) { idenities.Add(item.GetMetadata(dPIdentity)); } @@ -664,7 +650,7 @@ public static void AddDeclareParameterToCommandArgument(System.Collections.Gener { string nameValue = Utility.PutValueInQuote(name, valueQuote); arguments.Add(string.Concat("name=", nameValue)); - System.Type enumType = lookupDictionary.ContainsValue(name) ? typeof(MsDeploy.ExistingDeclareParameterMetadata) : typeof(MsDeploy.DeclareParameterMetadata); + Type enumType = lookupDictionary.ContainsValue(name) ? typeof(ExistingDeclareParameterMetadata) : typeof(DeclareParameterMetadata); // the rest, build on the Enum Name Utility.BuildArgumentsBaseOnEnumTypeName(item, arguments, enumType, valueQuote); lookupDictionary.Add(identity, name); @@ -678,19 +664,18 @@ public static void AddDeclareParameterToCommandArgument(System.Collections.Gener } } - /// /// Utility to build DeclareParameterOptions /// /// /// - public static void AddDeclareParametersOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[] originalItems, string valueQuote, bool foptimisticParameterDefaultValue) + public static void AddDeclareParametersOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[]? originalItems, string? valueQuote, bool foptimisticParameterDefaultValue) { - System.Collections.Generic.IList items = Utility.SortParametersTaskItems(originalItems, foptimisticParameterDefaultValue, DeclareParameterMetadata.DefaultValue.ToString()); - if (commandLineBuilder != null && items != null) + IList items = Utility.SortParametersTaskItems(originalItems, foptimisticParameterDefaultValue, DeclareParameterMetadata.DefaultValue.ToString()); + if (commandLineBuilder is not null && items is not null) { - System.Collections.Generic.List arguments = new(6); - System.Collections.Generic.Dictionary lookupDictionary = new(items.Count); + List arguments = new(6); + Dictionary lookupDictionary = new(items.Count); foreach (Framework.ITaskItem item in items) { @@ -700,24 +685,20 @@ public static void AddDeclareParametersOptions(Utilities.CommandLineBuilder comm } } - - public static void AddImportDeclareParametersFilesOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[] items) + public static void AddImportDeclareParametersFilesOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[]? items) { AddImportParametersFilesOptions(commandLineBuilder, "-declareParamFile:", items); } - public static void AddImportSetParametersFilesOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[] items) + public static void AddImportSetParametersFilesOptions(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[]? items) { AddImportParametersFilesOptions(commandLineBuilder, "-setParamFile:", items); } - internal static void AddImportParametersFilesOptions(Utilities.CommandLineBuilder commandLineBuilder, string parameterFlag, Framework.ITaskItem[] items) + internal static void AddImportParametersFilesOptions(Utilities.CommandLineBuilder commandLineBuilder, string parameterFlag, Framework.ITaskItem[]? items) { - if (commandLineBuilder != null - && !string.IsNullOrEmpty(parameterFlag) - && items != null)// Dev10 bug 496639 foreach will throw the exception if the replaceRuleItem is null + if (commandLineBuilder is not null && !string.IsNullOrEmpty(parameterFlag) && items is not null)// Dev10 bug 496639 foreach will throw the exception if the replaceRuleItem is null { - foreach (Framework.ITaskItem item in items) { string fileName = item.ItemSpec; @@ -729,18 +710,17 @@ internal static void AddImportParametersFilesOptions(Utilities.CommandLineBuilde } } - /// - /// Utility function to set SimpleeSyncParameter Name/Value + /// Utility function to set SimpleSyncParameter Name/Value /// /// /// - public static void AddSimpleSetParametersToObject(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[] originalItems, string valueQuoteChar, bool foptimisticParameterDefaultValue) + public static void AddSimpleSetParametersToObject(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[]? originalItems, string? valueQuoteChar, bool foptimisticParameterDefaultValue) { - System.Collections.Generic.IList items = Utility.SortParametersTaskItems(originalItems, foptimisticParameterDefaultValue, SimpleSyncParameterMetadata.Value.ToString()); - if (commandLineBuilder != null && items != null) + IList items = Utility.SortParametersTaskItems(originalItems, foptimisticParameterDefaultValue, SimpleSyncParameterMetadata.Value.ToString()); + if (commandLineBuilder is not null && items is not null) { - System.Collections.Generic.List arguments = new(6); + List arguments = new(6); foreach (Framework.ITaskItem item in items) { arguments.Clear(); @@ -754,7 +734,7 @@ public static void AddSimpleSetParametersToObject(Utilities.CommandLineBuilder c } // the rest, build on the enum name - Utility.BuildArgumentsBaseOnEnumTypeName(item, arguments, typeof(MsDeploy.SimpleSyncParameterMetadata), valueQuoteChar); + Utility.BuildArgumentsBaseOnEnumTypeName(item, arguments, typeof(SimpleSyncParameterMetadata), valueQuoteChar); commandLineBuilder.AppendSwitchUnquotedIfNotNull("-setParam:", arguments.Count == 0 ? null : string.Join(",", arguments.ToArray())); } } @@ -765,41 +745,41 @@ public static void AddSimpleSetParametersToObject(Utilities.CommandLineBuilder c /// /// /// - public static void AddSetParametersToObject(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[] originalItems, string valueQuote, bool foptimisticParameterDefaultValue) + public static void AddSetParametersToObject(Utilities.CommandLineBuilder commandLineBuilder, Framework.ITaskItem[]? originalItems, string? valueQuote, bool foptimisticParameterDefaultValue) { - System.Collections.Generic.IList items = Utility.SortParametersTaskItems(originalItems, foptimisticParameterDefaultValue, ExistingSyncParameterMetadata.Value.ToString()); - if (commandLineBuilder != null && items != null) + IList items = Utility.SortParametersTaskItems(originalItems, foptimisticParameterDefaultValue, ExistingSyncParameterMetadata.Value.ToString()); + if (commandLineBuilder is not null && items is not null) { - System.Collections.Generic.List arguments = new(6); - System.Collections.Generic.Dictionary lookupDictionary = new(items.Count); - System.Collections.Generic.Dictionary nameValueDictionary = new(items.Count, StringComparer.OrdinalIgnoreCase); + List arguments = new(6); + Dictionary lookupDictionary = new(items.Count); + Dictionary nameValueDictionary = new(items.Count, StringComparer.OrdinalIgnoreCase); foreach (Framework.ITaskItem item in items) { arguments.Clear(); - System.Collections.Generic.List idenities = new(6); + List identities = new(6); string name = item.ItemSpec; if (!string.IsNullOrEmpty(name)) { - string element = item.GetMetadata(ExistingParameterValiationMetadata.Element.ToString()); + string element = item.GetMetadata(ExistingParameterValidationMetadata.Element.ToString()); if (string.IsNullOrEmpty(element)) element = "parameterEntry"; if (string.Compare(element, "parameterEntry", StringComparison.OrdinalIgnoreCase) == 0) { - idenities.Add(name); - foreach (string dPIdentity in Enum.GetNames(typeof(MsDeploy.ExistingDeclareParameterMetadata))) + identities.Add(name); + foreach (string dPIdentity in Enum.GetNames(typeof(ExistingDeclareParameterMetadata))) { - idenities.Add(item.GetMetadata(dPIdentity)); + identities.Add(item.GetMetadata(dPIdentity)); } - string identity = string.Join(",", idenities.ToArray()); + string identity = string.Join(",", identities.ToArray()); if (!lookupDictionary.ContainsKey(identity)) { - string data = null; + string? data = null; bool fExistingName = nameValueDictionary.ContainsKey(name); if (nameValueDictionary.ContainsKey(name)) @@ -813,7 +793,7 @@ public static void AddSetParametersToObject(Utilities.CommandLineBuilder command } // the rest, build on the Enum Name - Utility.BuildArgumentsBaseOnEnumTypeName(item, arguments, typeof(MsDeploy.ExistingDeclareParameterMetadata), valueQuote); + Utility.BuildArgumentsBaseOnEnumTypeName(item, arguments, typeof(ExistingDeclareParameterMetadata), valueQuote); if (arguments.Count > 0 && !string.IsNullOrEmpty(data)) { #if NET472 @@ -838,14 +818,12 @@ public static void AddSetParametersToObject(Utilities.CommandLineBuilder command } } - - - public static void AddDestinationProviderSettingToObject(Utilities.CommandLineBuilder commandLineBuilder, string dest, Framework.ITaskItem[] items, string valueQuoteChar, - Framework.ITaskItem[] additionalProviderItems, MSDeploy msdeploy) + public static void AddDestinationProviderSettingToObject(Utilities.CommandLineBuilder commandLineBuilder, string? dest, Framework.ITaskItem[]? items, string? valueQuoteChar, + Framework.ITaskItem[]? additionalProviderItems, MSDeploy msdeploy) { //commandLineBuilder.AppendSwitchUnquotedIfNotNull("-source:", m_source); //commandLineBuilder.AppendSwitchUnquotedIfNotNull("-dest:", m_dest); - System.Collections.Generic.List arguments = new(6); + List arguments = new(6); if (items != null && items.GetLength(0) == 1) { @@ -880,8 +858,8 @@ public static void AddDestinationProviderSettingToObject(Utilities.CommandLineBu } else { - MsDeploy.Utility.IISExpressMetadata expressMetadata; - if (Enum.TryParse(name, out expressMetadata)) + Utility.IISExpressMetadata expressMetadata; + if (Enum.TryParse(name, out expressMetadata)) { string value = taskItem.GetMetadata(name); if (!string.IsNullOrEmpty(value)) @@ -900,10 +878,10 @@ public static void AddDestinationProviderSettingToObject(Utilities.CommandLineBu } } } - } } } + // If additional parameters are specified, we add these too. the itemSpec will be something like iisApp, contentPath, etc and // each item should have a name\value pair defined as metadata. Each provider will be written as itemSpec.Name=Value if (additionalProviderItems != null) @@ -927,19 +905,17 @@ public static void AddDestinationProviderSettingToObject(Utilities.CommandLineBu return; } - /// /// Utility function to help to generate Switch per item /// /// /// /// - private static void GenerateSwitchPerItem(Utilities.CommandLineBuilder commandLine, string strSwitch, string args) + private static void GenerateSwitchPerItem(Utilities.CommandLineBuilder commandLine, string strSwitch, string? args) { - if (!string.IsNullOrEmpty(args)) { - foreach (string dl in args.Split(new char[] { ';' })) + foreach (string dl in args!.Split(new char[] { ';' })) { if (!string.IsNullOrEmpty(dl)) { @@ -947,16 +923,14 @@ private static void GenerateSwitchPerItem(Utilities.CommandLineBuilder commandLi } } } - - } - internal static void IncorporateSettingsFromHostObject(ref Framework.ITaskItem[] skipRuleItems, Framework.ITaskItem[] destProviderSetting, System.Collections.Generic.IEnumerable hostObject) + internal static void IncorporateSettingsFromHostObject(ref Framework.ITaskItem[]? skipRuleItems, Framework.ITaskItem[]? destProviderSetting, IEnumerable? hostObject) { if (hostObject != null) { //retrieve user credentials - Framework.ITaskItem credentialItem = hostObject.FirstOrDefault(p => p.ItemSpec == VSMsDeployTaskHostObject.CredentailItemSpecName); + Framework.ITaskItem? credentialItem = hostObject.FirstOrDefault(p => p.ItemSpec == VSMsDeployTaskHostObject.CredentailItemSpecName); if (credentialItem != null && destProviderSetting != null && destProviderSetting[0] != null) { Framework.ITaskItem destSettings = destProviderSetting[0]; @@ -969,7 +943,7 @@ internal static void IncorporateSettingsFromHostObject(ref Framework.ITaskItem[] } //retrieve skip rules - System.Collections.Generic.IEnumerable skips = hostObject.Where(item => item.ItemSpec == VSMsDeployTaskHostObject.SkipFileItemSpecName); + IEnumerable skips = hostObject.Where(item => item.ItemSpec == VSMsDeployTaskHostObject.SkipFileItemSpecName); if (skips != null) { if (skipRuleItems != null) @@ -990,7 +964,7 @@ internal static void IncorporateSettingsFromHostObject(ref Framework.ITaskItem[] protected override string GenerateCommandLineCommands() { Utilities.CommandLineBuilder commandLine = new(); - IncorporateSettingsFromHostObject(ref m_skipRuleItemsITaskItem, Destination, HostObject as System.Collections.Generic.IEnumerable); + IncorporateSettingsFromHostObject(ref m_skipRuleItemsITaskItem, Destination, HostObject as IEnumerable); AddDestinationProviderSettingToObject(commandLine, "-source:", Source, m_strValueQuote, null, this); AddDestinationProviderSettingToObject(commandLine, "-dest:", Destination, m_strValueQuote, AdditionalDestinationProviderOptions, this); @@ -1062,7 +1036,7 @@ protected override string ToolName /// path to aspnet_merge.exe, null if not found protected override string GenerateFullPathToTool() { - string result = Path.Combine(ExePath, ToolName); + string result = Path.Combine(ExePath!, ToolName); if (string.Compare(ExePath, "%MSDeployPath%", StringComparison.OrdinalIgnoreCase) == 0) { @@ -1077,10 +1051,10 @@ protected override string GenerateFullPathToTool() /// /// Validate the task arguments, log any warnings/errors /// - /// true if arguments are corrent enough to continue processing, false otherwise + /// true if arguments are current enough to continue processing, false otherwise protected override bool ValidateParameters() { - if (Source != null && Source.GetLength(0) > 1) + if (Source is not null && Source.GetLength(0) > 1) { Log.LogError(string.Format(CultureInfo.CurrentCulture, Resources.MSDEPLOY_InvalidSourceCount, Source.GetLength(0)), null); return false; @@ -1093,7 +1067,7 @@ protected override bool ValidateParameters() } else { - string[] validVerbs = null; + string[]? validVerbs = null; bool fNullDestination = false; if (Destination == null || Destination.GetLength(0) == 0) { @@ -1110,7 +1084,6 @@ protected override bool ValidateParameters() validVerbs = new string[] { "delete", }; - } else { @@ -1129,7 +1102,7 @@ protected override bool ValidateParameters() } } } - Log.LogError(string.Format(CultureInfo.CurrentCulture, Resources.MSDEPLOY_InvalidVerbForTheInput, Verb, Source[0].ItemSpec, (fNullDestination) ? null : Destination[0].ItemSpec), null); + Log.LogError(string.Format(CultureInfo.CurrentCulture, Resources.MSDEPLOY_InvalidVerbForTheInput, Verb, Source?[0].ItemSpec, (fNullDestination) ? null : Destination?[0].ItemSpec), null); return false; } } diff --git a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/NormalizeServiceUrl.cs b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/NormalizeServiceUrl.cs index cdc0b9423454..64831af41223 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/NormalizeServiceUrl.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/NormalizeServiceUrl.cs @@ -109,7 +109,7 @@ private string ConstructServiceUrlForDeployThruWMSVC(string serviceUrl) const string http = "http://"; const string msddepaxd = "msdeploy.axd"; - System.UriBuilder serviceUriBuilder = null; + UriBuilder serviceUriBuilder; // We want to try adding https:// if there is no schema. However abc:123 is parsed as a schema=abc and path=123 // so the goal is to isolate this case and add the https:// but allow for http if the user chooses to diff --git a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/VsMsdeploy.cs b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/VsMsdeploy.cs index 399c005131e8..e1190d430447 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/VsMsdeploy.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/VsMsdeploy.cs @@ -1,30 +1,27 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.Build.Framework; +using Microsoft.NET.Sdk.Publish.Tasks.Properties; +using Collections = System.Collections; +using Diagnostics = System.Diagnostics; +using Utilities = Microsoft.Build.Utilities; + namespace Microsoft.NET.Sdk.Publish.Tasks.MsDeploy { - using System.Collections.Generic; - using System.Linq; - using Microsoft.Build.Framework; - using Microsoft.NET.Sdk.Publish.Tasks.Properties; - using Collections = System.Collections; - using Diagnostics = System.Diagnostics; - using Framework = Build.Framework; - using Utilities = Build.Utilities; - /// /// WrapperClass for Microsoft.Web.Deployment /// internal class MSWebDeploymentAssembly : DynamicAssembly { - public MSWebDeploymentAssembly(System.Version verToLoad) : + public MSWebDeploymentAssembly(Version verToLoad) : base(AssemblyName, verToLoad, "31bf3856ad364e35") { } public static string AssemblyName { get { return "Microsoft.Web.Deployment"; } } - public static MSWebDeploymentAssembly DynamicAssembly { get; set; } - public static void SetVersion(System.Version version) + public static MSWebDeploymentAssembly? DynamicAssembly { get; set; } + public static void SetVersion(Version version) { if (DynamicAssembly == null || DynamicAssembly.Version != version) { @@ -33,13 +30,13 @@ public static void SetVersion(System.Version version) } /// - /// Utility function to help out on getting Deployment colleciton's tryGetMethod + /// Utility function to help out on getting Deployment collection's tryGetMethod /// /// /// /// /// - public static bool DeploymentTryGetValueForEach(dynamic deploymentCollection, string name, out dynamic foundObject) + public static bool DeploymentTryGetValueForEach(dynamic deploymentCollection, string name, out dynamic? foundObject) { foundObject = null; if (deploymentCollection != null) @@ -56,8 +53,7 @@ public static bool DeploymentTryGetValueForEach(dynamic deploymentCollection, st return false; } - - public static bool DeploymentTryGetValueContains(dynamic deploymentCollection, string name, out dynamic foundObject) + public static bool DeploymentTryGetValueContains(dynamic deploymentCollection, string name, out dynamic? foundObject) { foundObject = null; if (deploymentCollection != null) @@ -77,15 +73,15 @@ public static bool DeploymentTryGetValueContains(dynamic deploymentCollection, s /// internal class MSWebDelegationAssembly : DynamicAssembly { - public MSWebDelegationAssembly(System.Version verToLoad) : + public MSWebDelegationAssembly(Version verToLoad) : base(AssemblyName, verToLoad, "31bf3856ad364e35") { } public static string AssemblyName { get { return "Microsoft.Web.Delegation"; } } - public static MSWebDelegationAssembly DynamicAssembly { get; set; } - public static void SetVersion(System.Version version) + public static MSWebDelegationAssembly? DynamicAssembly { get; set; } + public static void SetVersion(Version version) { if (DynamicAssembly == null || DynamicAssembly.Version != version) { @@ -94,7 +90,6 @@ public static void SetVersion(System.Version version) } } - // Microsoft.Web.Delegation ///-------------------------------------------------------------------- @@ -108,7 +103,7 @@ enum DeployStatus } /// - /// Encapsulte the process of interacting with MSDeploy + /// Encapsulate the process of interacting with MSDeploy /// abstract class BaseMSDeployDriver { @@ -116,9 +111,9 @@ abstract class BaseMSDeployDriver protected VSMSDeployObject _src; protected IVSMSDeployHost _host; - protected /*VSMSDeploySyncOption*/ dynamic _option; + protected /*VSMSDeploySyncOption*/ dynamic? _option; protected bool _isCancelOperation = false; - protected string _cancelMessage; + protected string? _cancelMessage; public string TaskName { @@ -128,7 +123,7 @@ public string TaskName } } - public string HighImportanceEventTypes + public string? HighImportanceEventTypes { get; set; @@ -136,7 +131,7 @@ public string HighImportanceEventTypes /// /// Boolean to cancel the operation - /// (TODO: in RTM, use thread synchoronization to protect the entry(though not absoluately necessary. + /// (TODO: in RTM, use thread synchronization to protect the entry(though not absolutely necessary. /// Need consider perf hit incurred though as msdeploy's callback will reference the value frequently) /// public bool IsCancelOperation @@ -150,7 +145,7 @@ public bool IsCancelOperation } } - public string CancelMessage + public string? CancelMessage { get { return _cancelMessage; } set { _cancelMessage = value; } @@ -165,13 +160,13 @@ private bool CancelCallback() return IsCancelOperation; } - protected /*VSMSDeploySyncOption*/ dynamic CreateOptionIfNeeded() + protected /*VSMSDeploySyncOption*/ dynamic? CreateOptionIfNeeded() { if (_option == null) { - object option = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentSyncOptions"); + object? option = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentSyncOptions"); #if NET472 - System.Type deploymentCancelCallbackType = MSWebDeploymentAssembly.DynamicAssembly.GetType("Microsoft.Web.Deployment.DeploymentCancelCallback"); + Type? deploymentCancelCallbackType = MSWebDeploymentAssembly.DynamicAssembly?.GetType("Microsoft.Web.Deployment.DeploymentCancelCallback"); object cancelCallbackDelegate = Delegate.CreateDelegate(deploymentCancelCallbackType, this, "CancelCallback"); Utility.SetDynamicProperty(option, "CancelCallback", cancelCallbackDelegate); @@ -185,15 +180,15 @@ private bool CancelCallback() } #if NET472 - private System.Collections.Generic.Dictionary _highImportanceEventTypes = null; - private System.Collections.Generic.Dictionary GetHighImportanceEventTypes() + private Dictionary? _highImportanceEventTypes = null; + private Dictionary GetHighImportanceEventTypes() { if (_highImportanceEventTypes == null) { - _highImportanceEventTypes = new System.Collections.Generic.Dictionary(StringComparer.InvariantCultureIgnoreCase); ; + _highImportanceEventTypes = new Dictionary(StringComparer.InvariantCultureIgnoreCase); ; if (!string.IsNullOrEmpty(HighImportanceEventTypes)) { - string[] typeNames = HighImportanceEventTypes.Split(new char[] { ';' }); // follow msbuild convention + string[] typeNames = HighImportanceEventTypes!.Split(new char[] { ';' }); // follow msbuild convention foreach (string typeName in typeNames) { _highImportanceEventTypes.Add(typeName, MessageImportance.High); @@ -222,7 +217,7 @@ void TraceEventHandlerDynamic(object sender, dynamic e) // if (operationCanceledException != null) // { // // eat this exception and set the args - // // Loger is the one throw this exception. we should not log again. + // // Logger is the one throw this exception. we should not log again. // // _option.CancelCallback(); // IsCancelOperation = true; // CancelMessage = operationCanceledException.Message; @@ -234,20 +229,19 @@ void TraceEventHandlerDynamic(object sender, dynamic e) //} } - /// /// Using MSDeploy API to invoke MSDeploy /// protected void InvokeMSdeploySync() { /*VSMSDeploySyncOption*/ - dynamic option = CreateOptionIfNeeded(); + dynamic? option = CreateOptionIfNeeded(); IsCancelOperation = false; _host.PopulateOptions(option); - // you can reuse traceEventHandler if you know the function signuture is the same - System.Delegate traceEventHandler = DynamicAssembly.AddEventDeferHandler( + // you can reuse traceEventHandler if you know the function signature is the same + Delegate traceEventHandler = DynamicAssembly.AddEventDeferHandler( _src.BaseOptions, "Trace", new DynamicAssembly.EventHandlerDynamicDelegate(TraceEventHandlerDynamic)); @@ -300,7 +294,7 @@ public void SyncThruMSDeploy() /// // abstract protected void LogTrace(Deployment.DeploymentTraceEventArgs e); - protected abstract void LogTrace(dynamic e, System.Collections.Generic.IDictionary customTypeLoging); + protected abstract void LogTrace(dynamic e, IDictionary customTypeLoging); /// /// Encapsulate the things to be done after the deploy is done @@ -335,9 +329,9 @@ public static BaseMSDeployDriver CreateBaseMSDeployDriver( /// in a IDictionary such that the MBuild handler can handle generically. /// #if NET472 - [System.Serializable] + [Serializable] #endif - public class CustomBuildWithPropertiesEventArgs : Framework.CustomBuildEventArgs, Collections.IDictionary + public class CustomBuildWithPropertiesEventArgs : CustomBuildEventArgs, Collections.IDictionary { public CustomBuildWithPropertiesEventArgs() : base() { } public CustomBuildWithPropertiesEventArgs(string msg, string keyword, string senderName) @@ -349,9 +343,9 @@ public CustomBuildWithPropertiesEventArgs(string msg, string keyword, string sen #region IDictionary Members // Delegate everything to m_hybridDictionary - public void Add(object key, object value) + public void Add(object? key, object? value) { - m_hybridDictionary.Add(key, value); + m_hybridDictionary.Add(key!, value); } public void Clear() @@ -364,7 +358,7 @@ public bool Contains(object key) return m_hybridDictionary.Contains(key); } - public System.Collections.IDictionaryEnumerator GetEnumerator() + public Collections.IDictionaryEnumerator GetEnumerator() { return m_hybridDictionary.GetEnumerator(); } @@ -379,7 +373,7 @@ public bool IsReadOnly get { return m_hybridDictionary.IsReadOnly; } } - public System.Collections.ICollection Keys + public Collections.ICollection Keys { get { return m_hybridDictionary.Keys; } } @@ -389,12 +383,12 @@ public void Remove(object key) m_hybridDictionary.Remove(key); } - public System.Collections.ICollection Values + public Collections.ICollection Values { get { return m_hybridDictionary.Values; } } - public object this[object key] + public object? this[object key] { get { return m_hybridDictionary[key]; } set { m_hybridDictionary[key] = value; } @@ -404,7 +398,7 @@ public object this[object key] #region ICollection Members - public void CopyTo(System.Array array, int index) + public void CopyTo(Array array, int index) { m_hybridDictionary.CopyTo(array, index); } @@ -428,15 +422,13 @@ public object SyncRoot #region IEnumerable Members - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } - - /// /// Deploy through msbuild in command line /// @@ -448,32 +440,30 @@ protected override void BeforeSync() _host.Log.LogMessage(strMsg); } - // Utility function to log all public instance property to CustomerBuildEventArgs private static void AddAllPropertiesToCustomBuildWithPropertyEventArgs(CustomBuildWithPropertiesEventArgs cbpEventArg, object obj) { #if NET472 if (obj != null) { - System.Type thisType = obj.GetType(); + Type thisType = obj.GetType(); cbpEventArg.Add("ArgumentType", thisType.ToString()); System.Reflection.MemberInfo[] arrayMemberInfo = thisType.FindMembers(System.Reflection.MemberTypes.Property, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null); if (arrayMemberInfo != null) { - foreach (System.Reflection.MemberInfo memberinfo in arrayMemberInfo) + foreach (System.Reflection.MemberInfo memberInfo in arrayMemberInfo) { - object val = thisType.InvokeMember(memberinfo.Name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty, null, obj, null, System.Globalization.CultureInfo.InvariantCulture); + object val = thisType.InvokeMember(memberInfo.Name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty, null, obj, null, System.Globalization.CultureInfo.InvariantCulture); if (val != null) - cbpEventArg.Add(memberinfo.Name, val); + cbpEventArg.Add(memberInfo.Name, val); } } } #endif } - ///// - ///// Log Trace ifnormation in the command line + ///// Log Trace information in the command line ///// ///// //protected override void LogTrace(Microsoft.Web.Deployment.DeploymentTraceEventArgs args) @@ -519,18 +509,17 @@ private static void AddAllPropertiesToCustomBuildWithPropertyEventArgs(CustomBui // _host.BuildEngine.LogCustomEvent(customBuildWithPropertiesEventArg); //} - - protected override void LogTrace(dynamic args, System.Collections.Generic.IDictionary customTypeLoging) + protected override void LogTrace(dynamic args, IDictionary customTypeLoging) { string strMsg = args.Message; string strEventType = "Trace"; - Framework.MessageImportance messageImportance = MessageImportance.Low; + MessageImportance messageImportance = MessageImportance.Low; - System.Type argsT = args.GetType(); - if (Utility.IsType(argsT, MSWebDeploymentAssembly.DynamicAssembly.GetType("Microsoft.Web.Deployment.DeploymentFileSerializationEventArgs")) || - Utility.IsType(argsT, MSWebDeploymentAssembly.DynamicAssembly.GetType("Microsoft.Web.Deployment.DeploymentPackageSerializationEventArgs")) || - Utility.IsType(argsT, MSWebDeploymentAssembly.DynamicAssembly.GetType("Microsoft.Web.Deployment.DeploymentObjectChangedEventArgs")) || - Utility.IsType(argsT, MSWebDeploymentAssembly.DynamicAssembly.GetType("Microsoft.Web.Deployment.DeploymentSyncParameterEventArgs"))) + Type argsT = args.GetType(); + if (Utility.IsType(argsT, MSWebDeploymentAssembly.DynamicAssembly?.GetType("Microsoft.Web.Deployment.DeploymentFileSerializationEventArgs")) || + Utility.IsType(argsT, MSWebDeploymentAssembly.DynamicAssembly?.GetType("Microsoft.Web.Deployment.DeploymentPackageSerializationEventArgs")) || + Utility.IsType(argsT, MSWebDeploymentAssembly.DynamicAssembly?.GetType("Microsoft.Web.Deployment.DeploymentObjectChangedEventArgs")) || + Utility.IsType(argsT, MSWebDeploymentAssembly.DynamicAssembly?.GetType("Microsoft.Web.Deployment.DeploymentSyncParameterEventArgs"))) { //promote those message only for those event strEventType = "Action"; @@ -544,7 +533,7 @@ protected override void LogTrace(dynamic args, System.Collections.Generic.IDicti if (!string.IsNullOrEmpty(strMsg)) { - System.Diagnostics.TraceLevel level = (System.Diagnostics.TraceLevel)Enum.ToObject(typeof(System.Diagnostics.TraceLevel), args.EventLevel); + Diagnostics.TraceLevel level = (Diagnostics.TraceLevel)Enum.ToObject(typeof(Diagnostics.TraceLevel), args.EventLevel); switch (level) { case Diagnostics.TraceLevel.Off: @@ -579,7 +568,7 @@ protected override void StartSync() } /// - /// Wait foreve if we are in the command line + /// Wait forever if we are in the command line /// protected override void WaitForDone() { } @@ -602,24 +591,23 @@ internal VSMSDeployDriverInCmd(VSMSDeployObject src, VSMSDeployObject dest, IVSM : base(src, dest, host) { if (host.GetProperty("HighImportanceEventTypes") != null) - HighImportanceEventTypes = host.GetProperty("HighImportanceEventTypes").ToString(); + HighImportanceEventTypes = host.GetProperty("HighImportanceEventTypes")?.ToString(); } } - /// /// MSBuild Task VSMSDeploy to call the object through UI or not /// - public class VSMSDeploy : Utilities.Task, IVSMSDeployHost, Framework.ICancelableTask + public class VSMSDeploy : Task, IVSMSDeployHost, ICancelableTask { - string _disableLink; - string _enableLink; - private string _disableSkipDirective; - private string _enableSkipDirective; + string? _disableLink; + string? _enableLink; + private string? _disableSkipDirective; + private string? _enableSkipDirective; bool _result = false; bool _whatIf = false; - string _deploymentTraceLevel; + string? _deploymentTraceLevel; bool _useCheckSum = false; private int m_retryAttempts = -1; private int m_retryInterval = -1; @@ -627,32 +615,32 @@ public class VSMSDeploy : Utilities.Task, IVSMSDeployHost, Framework.ICancelable bool _allowUntrustedCert; bool _skipExtraFilesOnServer = false; - private Framework.ITaskItem[] m_sourceITaskItem = null; - private Framework.ITaskItem[] m_destITaskItem = null; - private Framework.ITaskItem[] m_replaceRuleItemsITaskItem = null; - private Framework.ITaskItem[] m_skipRuleItemsITaskItem = null; - private Framework.ITaskItem[] m_declareParameterItems = null; - private Framework.ITaskItem[] m_importDeclareParametersItems = null; - private Framework.ITaskItem[] m_simpleSetParamterItems = null; - private Framework.ITaskItem[] m_importSetParametersItems = null; - private Framework.ITaskItem[] m_setParamterItems = null; + private ITaskItem[]? m_sourceITaskItem = null; + private ITaskItem[]? m_destITaskItem = null; + private ITaskItem[]? m_replaceRuleItemsITaskItem = null; + private ITaskItem[]? m_skipRuleItemsITaskItem = null; + private ITaskItem[]? m_declareParameterItems = null; + private ITaskItem[]? m_importDeclareParametersItems = null; + private ITaskItem[]? m_simpleSetParamterItems = null; + private ITaskItem[]? m_importSetParametersItems = null; + private ITaskItem[]? m_setParamterItems = null; - private BaseMSDeployDriver m_msdeployDriver = null; + private BaseMSDeployDriver? m_msdeployDriver = null; - [Framework.Required] - public Framework.ITaskItem[] Source + [Required] + public ITaskItem[]? Source { get { return m_sourceITaskItem; } set { m_sourceITaskItem = value; } } - public string HighImportanceEventTypes + public string? HighImportanceEventTypes { get; set; } - public Framework.ITaskItem[] Destination + public ITaskItem[]? Destination { get { return m_destITaskItem; } set { m_destITaskItem = value; } @@ -676,15 +664,12 @@ public bool WhatIf set { _whatIf = value; } } - - - public string DeploymentTraceLevel + public string? DeploymentTraceLevel { get { return _deploymentTraceLevel; } set { _deploymentTraceLevel = value; } } - public bool UseChecksum { get { return _useCheckSum; } @@ -692,7 +677,7 @@ public bool UseChecksum } //Sync result: Succeed or Fail - [Framework.Output] + [Output] public bool Result { get { return _result; } @@ -702,26 +687,25 @@ public bool Result /// /// Disable Link is a list of disable provider /// - public string DisableLink + public string? DisableLink { get { return _disableLink; } set { _disableLink = value; } } - public string EnableLink + public string? EnableLink { get { return _enableLink; } set { _enableLink = value; } } - - public string DisableSkipDirective + public string? DisableSkipDirective { get { return _disableSkipDirective; } set { _disableSkipDirective = value; } } - public string EnableSkipDirective + public string? EnableSkipDirective { get { return _enableSkipDirective; } set { _enableSkipDirective = value; } @@ -739,22 +723,19 @@ public int RetryInterval set { m_retryInterval = value; } } - - public Framework.ITaskItem[] ReplaceRuleItems + public ITaskItem[]? ReplaceRuleItems { get { return m_replaceRuleItemsITaskItem; } set { m_replaceRuleItemsITaskItem = value; } } - - public Framework.ITaskItem[] SkipRuleItems + public ITaskItem[]? SkipRuleItems { get { return m_skipRuleItemsITaskItem; } set { m_skipRuleItemsITaskItem = value; } } - - public Framework.ITaskItem[] DeclareParameterItems + public ITaskItem[]? DeclareParameterItems { get { return m_declareParameterItems; } set { m_declareParameterItems = value; } @@ -762,26 +743,25 @@ public Framework.ITaskItem[] DeclareParameterItems public bool OptimisticParameterDefaultValue { get; set; } - - public Framework.ITaskItem[] ImportDeclareParametersItems + public ITaskItem[]? ImportDeclareParametersItems { get { return m_importDeclareParametersItems; } set { m_importDeclareParametersItems = value; } } - public Framework.ITaskItem[] SimpleSetParameterItems + public ITaskItem[]? SimpleSetParameterItems { get { return m_simpleSetParamterItems; } set { m_simpleSetParamterItems = value; } } - public Framework.ITaskItem[] ImportSetParametersItems + public ITaskItem[]? ImportSetParametersItems { get { return m_importSetParametersItems; } set { m_importSetParametersItems = value; } } - public Framework.ITaskItem[] SetParameterItems + public ITaskItem[]? SetParameterItems { get { return m_setParamterItems; } set { m_setParamterItems = value; } @@ -793,8 +773,8 @@ public Framework.ITaskItem[] SetParameterItems public bool EnableMSDeployWebConfigEncryptRule { get; set; } - private string _userAgent; - public string UserAgent + private string? _userAgent; + public string? UserAgent { get { return _userAgent; } set @@ -806,9 +786,9 @@ public string UserAgent } } - public Framework.ITaskItem[] AdditionalDestinationProviderOptions { get; set; } + public ITaskItem[]? AdditionalDestinationProviderOptions { get; set; } - public string MSDeployVersionsToTry + public string? MSDeployVersionsToTry { get; set; @@ -845,18 +825,18 @@ public override bool Execute() { Utility.SetupMSWebDeployDynamicAssemblies(MSDeployVersionsToTry, this); } - catch (System.Exception exception) + catch (Exception exception) { Log.LogErrorFromException(exception); return false; // failed the task } - string errorMessage = null; + string? errorMessage = null; if (!Utility.CheckMSDeploymentVersion(Log, out errorMessage)) return false; - VSMSDeployObject src = null; - VSMSDeployObject dest = null; + VSMSDeployObject? src = null; + VSMSDeployObject? dest = null; if (Source == null || Source.GetLength(0) != 1) { @@ -876,7 +856,7 @@ public override bool Execute() else { dest = VSMSDeployObjectFactory.CreateVSMSDeployObject(Destination[0]); - VSHostObject hostObj = new(HostObject as System.Collections.Generic.IEnumerable); + VSHostObject hostObj = new((HostObject as IEnumerable)!); string username, password; if (hostObj.ExtractCredentials(out username, out password)) { @@ -886,10 +866,10 @@ public override bool Execute() } //$Todo, Should we split the Disable Link to two set of setting, one for source, one for destination - src.DisableLinks = DisableLink; - dest.DisableLinks = DisableLink; - src.EnableLinks = EnableLink; - dest.EnableLinks = EnableLink; + src.DisableLinks = DisableLink ?? string.Empty; + dest.DisableLinks = DisableLink ?? string.Empty; + src.EnableLinks = EnableLink ?? string.Empty; + dest.EnableLinks = EnableLink ?? string.Empty; if (RetryAttempts >= 0) { src.RetryAttempts = RetryAttempts; @@ -912,7 +892,7 @@ public override bool Execute() driver.SyncThruMSDeploy(); Result = !driver.IsCancelOperation; } - catch (System.Exception e) + catch (Exception e) { if (e is System.Reflection.TargetInvocationException) { @@ -920,13 +900,13 @@ public override bool Execute() e = e.InnerException; } - System.Type eType = e.GetType(); - if (Utility.IsType(eType, MSWebDeploymentAssembly.DynamicAssembly.GetType("Microsoft.Web.Deployment.DeploymentCanceledException"))) + Type eType = e.GetType(); + if (Utility.IsType(eType, MSWebDeploymentAssembly.DynamicAssembly?.GetType("Microsoft.Web.Deployment.DeploymentCanceledException"))) { Log.LogMessageFromText(Resources.VSMSDEPLOY_Canceled, MessageImportance.High); } - else if (Utility.IsType(eType, MSWebDelegationAssembly.DynamicAssembly.GetType("Microsoft.Web.Deployment.DeploymentException")) - || Utility.IsType(eType, MSWebDeploymentAssembly.DynamicAssembly.GetType("Microsoft.Web.Deployment.DeploymentFatalException"))) + else if (Utility.IsType(eType, MSWebDelegationAssembly.DynamicAssembly?.GetType("Microsoft.Web.Deployment.DeploymentException")) + || Utility.IsType(eType, MSWebDeploymentAssembly.DynamicAssembly?.GetType("Microsoft.Web.Deployment.DeploymentFatalException"))) { Utility.LogVsMsDeployException(Log, e); } @@ -960,7 +940,7 @@ string IVsPublishMsBuildTaskHost.TaskName } } - Microsoft.Build.Utilities.TaskLoggingHelper IVsPublishMsBuildTaskHost.Log + Utilities.TaskLoggingHelper IVsPublishMsBuildTaskHost.Log { get { @@ -968,7 +948,7 @@ Microsoft.Build.Utilities.TaskLoggingHelper IVsPublishMsBuildTaskHost.Log } } - Microsoft.Build.Framework.IBuildEngine IVsPublishMsBuildTaskHost.BuildEngine + IBuildEngine IVsPublishMsBuildTaskHost.BuildEngine { get { @@ -987,11 +967,11 @@ Microsoft.Build.Framework.IBuildEngine IVsPublishMsBuildTaskHost.BuildEngine /// void IVSMSDeployHost.UpdateDeploymentBaseOptions(VSMSDeployObject srcVsMsDeployobject, VSMSDeployObject destVsMsDeployobject) { - Collections.Generic.List enableSkipDirectiveList = MSDeployUtility.ConvertStringIntoList(EnableSkipDirective); - Collections.Generic.List disableSkipDirectiveList = MSDeployUtility.ConvertStringIntoList(DisableSkipDirective); + List enableSkipDirectiveList = MSDeployUtility.ConvertStringIntoList(EnableSkipDirective); + List disableSkipDirectiveList = MSDeployUtility.ConvertStringIntoList(DisableSkipDirective); - VSHostObject hostObject = new(HostObject as System.Collections.Generic.IEnumerable); - Framework.ITaskItem[] srcSkipItems, destSkipsItems; + VSHostObject hostObject = new(HostObject as IEnumerable); + ITaskItem[]? srcSkipItems, destSkipsItems; // Add FileSkip rules from Host Object hostObject.GetFileSkips(out srcSkipItems, out destSkipsItems); @@ -1007,8 +987,8 @@ void IVSMSDeployHost.UpdateDeploymentBaseOptions(VSMSDeployObject srcVsMsDeployo { Diagnostics.TraceLevel deploymentTraceEventLevel = (Diagnostics.TraceLevel)Enum.Parse(typeof(Diagnostics.TraceLevel), DeploymentTraceLevel, true); - srcVsMsDeployobject.BaseOptions.TraceLevel = deploymentTraceEventLevel; - destVsMsDeployobject.BaseOptions.TraceLevel = deploymentTraceEventLevel; + srcVsMsDeployobject.BaseOptions!.TraceLevel = deploymentTraceEventLevel; + destVsMsDeployobject.BaseOptions!.TraceLevel = deploymentTraceEventLevel; } Utility.AddSetParametersFilesVsMsDeployObject(srcVsMsDeployobject, ImportSetParametersItems); @@ -1017,7 +997,7 @@ void IVSMSDeployHost.UpdateDeploymentBaseOptions(VSMSDeployObject srcVsMsDeployo AddAdditionalProviderOptions(destVsMsDeployobject); } - private void GetCustomAndAppDataSkips(out ITaskItem[] srcSkips, out ITaskItem[] destSkips) + private void GetCustomAndAppDataSkips(out ITaskItem[]? srcSkips, out ITaskItem[]? destSkips) { srcSkips = null; destSkips = null; @@ -1052,7 +1032,7 @@ private void AddAdditionalProviderOptions(VSMSDeployObject destVsMsDeployobject) string settingName = item.GetMetadata("Name"); string settingValue = item.GetMetadata("Value"); if (!string.IsNullOrEmpty(settingName) && !string.IsNullOrEmpty(settingValue)) - destVsMsDeployobject.BaseOptions.AddDefaultProviderSetting(item.ItemSpec, settingName, settingValue); + destVsMsDeployobject.BaseOptions?.AddDefaultProviderSetting(item.ItemSpec, settingName, settingValue); } } } @@ -1113,7 +1093,7 @@ public void Cancel() m_msdeployDriver.IsCancelOperation = true; } } - catch (System.Exception ex) + catch (Exception ex) { Diagnostics.Debug.Fail("Exception on ICancelableTask.Cancel being invoked:" + ex.Message); } @@ -1121,8 +1101,7 @@ public void Cancel() #endregion - - public object GetProperty(string propertyName) + public object? GetProperty(string propertyName) { #if NET472 string lowerName = propertyName.ToLower(System.Globalization.CultureInfo.InvariantCulture); @@ -1143,20 +1122,19 @@ public object GetProperty(string propertyName) public void AddOptionRule(/*Microsoft.Web.Deployment.DeploymentSyncOptions*/ dynamic option, string ruleName, string handlerType) { - bool ruleExists = false; try { object existingRule = option.Rules[ruleName]; ruleExists = true; } - catch (Collections.Generic.KeyNotFoundException) { } + catch (KeyNotFoundException) { } if (!ruleExists) { - dynamic appOfflineRuleHanlder = MSWebDeploymentAssembly.DynamicAssembly.CreateObject(handlerType, new object[] { }); - dynamic appOfflineRule = MSWebDeploymentAssembly.DynamicAssembly.CreateObject("Microsoft.Web.Deployment.DeploymentRule", - new object[] { ruleName, appOfflineRuleHanlder }); + dynamic? appOfflineRuleHandler = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject(handlerType, new object[] { }); + dynamic? appOfflineRule = MSWebDeploymentAssembly.DynamicAssembly?.CreateObject("Microsoft.Web.Deployment.DeploymentRule", + new object[] { ruleName, appOfflineRuleHandler! }); option.Rules.Add(appOfflineRule); } } diff --git a/src/WebSdk/Publish/Tasks/Tasks/TransformAppSettings.cs b/src/WebSdk/Publish/Tasks/Tasks/TransformAppSettings.cs index 007968bad22c..1a7d91917c54 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/TransformAppSettings.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/TransformAppSettings.cs @@ -11,29 +11,29 @@ public class TransformAppSettings : Task /// Full Path to the Project Folder. This is used to determine the default appsettings location. /// [Required] - public string ProjectDirectory { get; set; } + public string? ProjectDirectory { get; set; } /// /// Path to the Publish Folder. /// [Required] - public string PublishDirectory { get; set; } + public string? PublishDirectory { get; set; } /// /// Gets the destination connection string information. /// [Required] - public ITaskItem[] DestinationConnectionStrings { get; set; } + public ITaskItem[]? DestinationConnectionStrings { get; set; } /// /// AppSettings file name. /// - public string SourceAppSettingsName { get; set; } + public string? SourceAppSettingsName { get; set; } /// /// Optional: Get the destination AppSettingsName /// - public string DestinationAppSettingsName { get; set; } + public string? DestinationAppSettingsName { get; set; } /// /// options: Name of the deployment environment. /// - public string EnvironmentName { get; set; } + public string? EnvironmentName { get; set; } public override bool Execute() { @@ -58,12 +58,12 @@ public bool TransformAppSettingsInternal() InitializeProperties(); - string sourceAppSettingsFilePath = Path.Combine(ProjectDirectory, SourceAppSettingsName); + string sourceAppSettingsFilePath = Path.Combine(ProjectDirectory!, SourceAppSettingsName!); if (string.IsNullOrEmpty(DestinationAppSettingsName)) { DestinationAppSettingsName = $"{Path.GetFileNameWithoutExtension(SourceAppSettingsName)}.{EnvironmentName}{Path.GetExtension(SourceAppSettingsName)}"; } - string destinationAppSettingsFilePath = Path.Combine(PublishDirectory, DestinationAppSettingsName); + string destinationAppSettingsFilePath = Path.Combine(PublishDirectory!, DestinationAppSettingsName!); // If the source appsettings is not present, generate one. if (!File.Exists(sourceAppSettingsFilePath)) @@ -103,6 +103,5 @@ private void InitializeProperties() EnvironmentName = "production"; } } - } } diff --git a/src/WebSdk/Publish/Tasks/Tasks/TransformWebConfig.cs b/src/WebSdk/Publish/Tasks/Tasks/TransformWebConfig.cs index 786eb7e95785..e0aa4ec4a5a8 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/TransformWebConfig.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/TransformWebConfig.cs @@ -13,14 +13,14 @@ public class TransformWebConfig : Task /// /// [Required] - public string TargetPath { get; set; } + public string? TargetPath { get; set; } /// /// Destination folder of the publish /// /// [Required] - public string PublishDir { get; set; } + public string? PublishDir { get; set; } [Required] public bool UseAppHost { get; set; } @@ -34,7 +34,7 @@ public class TransformWebConfig : Task /// /// ProjectGuid that uniquely identifies the project. Used for Telemetry /// - public string ProjectGuid { get; set; } + public string? ProjectGuid { get; set; } /// /// Flag that determines whether the publish telemetry needs to be disabled. @@ -43,47 +43,47 @@ public class TransformWebConfig : Task /// /// Absolute path to the project file. /// - public string ProjectFullPath { get; set; } + public string? ProjectFullPath { get; set; } /// /// Absolute path to the Solution file. /// - public string SolutionPath { get; set; } + public string? SolutionPath { get; set; } /// /// Native executable extension /// - public string ExecutableExtension { get; set; } + public string? ExecutableExtension { get; set; } /// /// AspNetCoreHostingModel defines whether the hosting will be InProcess or OutOfProcess. /// /// - public string AspNetCoreHostingModel { get; set; } + public string? AspNetCoreHostingModel { get; set; } /// /// AspNetCoreModule defines the module name /// /// - public string AspNetCoreModuleName { get; set; } + public string? AspNetCoreModuleName { get; set; } - public string EnvironmentName { get; set; } + public string? EnvironmentName { get; set; } public override bool Execute() { Log.LogMessage(MessageImportance.Low, $"Configuring the following project for use with IIS: '{PublishDir}'"); - XDocument webConfigXml = null; + XDocument? webConfigXml = null; // Initialize the publish web.config file with project web.config content if present. Else, clean the existing web.config in the // publish folder to make sure we have a consistent web.config update experience. string defaultWebConfigPath = "web.config"; - string projectWebConfigPath = null; - string publishWebConfigPath = Path.Combine(PublishDir, defaultWebConfigPath); + string? projectWebConfigPath = null; + string publishWebConfigPath = Path.Combine(PublishDir!, defaultWebConfigPath); if (!string.IsNullOrEmpty(ProjectFullPath)) { //Ensure that we load the actual web.config name (case-sensitive on Unix-like systems) - projectWebConfigPath = GetWebConfigFileOrDefault(ProjectFullPath, defaultWebConfigPath); - publishWebConfigPath = Path.Combine(PublishDir, Path.GetFileName(projectWebConfigPath)); + projectWebConfigPath = GetWebConfigFileOrDefault(ProjectFullPath!, defaultWebConfigPath); + publishWebConfigPath = Path.Combine(PublishDir!, Path.GetFileName(projectWebConfigPath)); } publishWebConfigPath = Path.GetFullPath(publishWebConfigPath); @@ -120,8 +120,8 @@ public override bool Execute() Log.LogMessage("Configuring web.config for deployment to Azure"); } - string outputFile = Path.GetFileName(TargetPath); - XDocument transformedConfig = WebConfigTransform.Transform( + string? outputFile = Path.GetFileName(TargetPath); + XDocument? transformedConfig = WebConfigTransform.Transform( webConfigXml, outputFile, IsAzure, @@ -136,7 +136,7 @@ public override bool Execute() transformedConfig = WebConfigTelemetry.AddTelemetry(transformedConfig, ProjectGuid, IgnoreProjectGuid, SolutionPath, ProjectFullPath); using (FileStream f = new(publishWebConfigPath, FileMode.Create)) { - transformedConfig.Save(f); + transformedConfig?.Save(f); } Log.LogMessage(MessageImportance.Low, "Configuring project completed successfully"); @@ -147,18 +147,17 @@ public override bool Execute() /// Searches for an existing (case-insensitive) `Web.config` file. Otherwise defaults to defaultWebConfigName /// /// Full path to project file - /// Web Config file name to search for i.e. `web.config` + /// Web Config file name to search for i.e. `web.config` /// public string GetWebConfigFileOrDefault(string projectPath, string defaultWebConfigName) { var projectDirectory = Path.GetDirectoryName(projectPath); - var currentWebConfigFileName = Directory.EnumerateFiles(projectDirectory) + var currentWebConfigFileName = Directory.EnumerateFiles(projectDirectory!) .FirstOrDefault(file => string.Equals(Path.GetFileName(file), defaultWebConfigName, StringComparison.OrdinalIgnoreCase)); var webConfigFileName = currentWebConfigFileName == null ? defaultWebConfigName : Path.GetFileName(currentWebConfigFileName); - var projectWebConfigPath = Path.Combine(projectDirectory, webConfigFileName); + var projectWebConfigPath = Path.Combine(projectDirectory!, webConfigFileName); return projectWebConfigPath; } - } } diff --git a/src/WebSdk/Publish/Tasks/Tasks/ValidateParameter.cs b/src/WebSdk/Publish/Tasks/Tasks/ValidateParameter.cs index a6f21a24fbc0..1b06470ba243 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/ValidateParameter.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/ValidateParameter.cs @@ -7,12 +7,12 @@ namespace Microsoft.NET.Sdk.Publish.Tasks { - public class ValidateParameter : Build.Utilities.Task + public class ValidateParameter : Task { [Required] - public string ParameterName { get; set; } + public string? ParameterName { get; set; } - public string ParameterValue { get; set; } + public string? ParameterValue { get; set; } public override bool Execute() { diff --git a/src/WebSdk/Publish/Tasks/Tasks/WebJobs/GenerateRunCommandFile.cs b/src/WebSdk/Publish/Tasks/Tasks/WebJobs/GenerateRunCommandFile.cs index e45788329884..ee7619089247 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/WebJobs/GenerateRunCommandFile.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/WebJobs/GenerateRunCommandFile.cs @@ -9,22 +9,22 @@ public class GenerateRunCommandFile : Task { private const string RunCommandFile = "run.cmd"; [Required] - public string ProjectDirectory { get; set; } + public string? ProjectDirectory { get; set; } [Required] - public string WebJobsDirectory { get; set; } + public string? WebJobsDirectory { get; set; } [Required] - public string TargetPath { get; set; } + public string? TargetPath { get; set; } [Required] public bool UseAppHost { get; set; } - public string ExecutableExtension { get; set; } + public string? ExecutableExtension { get; set; } public override bool Execute() { - bool isRunCommandFilePresent = File.Exists(Path.Combine(ProjectDirectory, RunCommandFile)); + bool isRunCommandFilePresent = File.Exists(Path.Combine(ProjectDirectory!, RunCommandFile)); if (!isRunCommandFilePresent) { string command = WebJobsCommandGenerator.RunCommand(TargetPath, UseAppHost, ExecutableExtension); - File.WriteAllText(Path.Combine(WebJobsDirectory, RunCommandFile), command); + File.WriteAllText(Path.Combine(WebJobsDirectory!, RunCommandFile), command); } return true; diff --git a/src/WebSdk/Publish/Tasks/Tasks/Xdt/TaskTransformationLogger.cs b/src/WebSdk/Publish/Tasks/Tasks/Xdt/TaskTransformationLogger.cs index 4235bbe9d080..cd7e0827183f 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/Xdt/TaskTransformationLogger.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/Xdt/TaskTransformationLogger.cs @@ -15,7 +15,7 @@ internal class TaskTransformationLogger : IXmlTransformationLogger private int indentLevel = 0; private readonly string indentStringPiece = " "; - private string indentString = null; + private string? indentString = null; private bool stackTrace; #endregion @@ -31,7 +31,7 @@ public TaskTransformationLogger(TaskLoggingHelper loggingHelper, bool stackTrace this.stackTrace = stackTrace; } - private string IndentString + private string? IndentString { get { @@ -156,7 +156,7 @@ void IXmlTransformationLogger.LogErrorFromException(Exception ex, string file, i // that accepts line numbers. So instead, we have to construct // the error message from the exception and use LogError. StringBuilder sb = new(); - Exception exIterator = ex; + Exception? exIterator = ex; while (exIterator != null) { sb.AppendFormat("{0} : {1}", exIterator.GetType().Name, exIterator.Message); diff --git a/src/WebSdk/Publish/Tasks/Tasks/Xdt/TransformXml.cs b/src/WebSdk/Publish/Tasks/Tasks/Xdt/TransformXml.cs index 8625993f7c2f..4828a884ae86 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/Xdt/TransformXml.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/Xdt/TransformXml.cs @@ -10,16 +10,16 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.Xdt { public class TransformXml : Task { - private string _sourceFile = null; - private string _transformFile = null; - private string _destinationFile = null; + private string? _sourceFile = null; + private string? _transformFile = null; + private string? _destinationFile = null; private string _sourceRootPath = string.Empty; private string _transformRootPath = string.Empty; private bool _ignoreError = false; private bool stackTrace = false; [Required] - public string Source + public string? Source { get { @@ -40,9 +40,8 @@ public bool IgnoreError set { _ignoreError = value; } } - [Required] - public string Transform + public string? Transform { get { @@ -70,9 +69,8 @@ public string TransformRootPath set { _transformRootPath = value; } } - [Required] - public string Destination + public string? Destination { get { @@ -104,14 +102,14 @@ public override bool Execute() public bool RunXmlTransform(bool isLoggingEnabled = true) { bool succeeded = true; - IXmlTransformationLogger logger = null; + IXmlTransformationLogger? logger = null; if (isLoggingEnabled && !IgnoreError) { logger = new TaskTransformationLogger(Log, StackTrace); } - XmlTransformation transformation = null; - XmlTransformableDocument document = null; + XmlTransformation? transformation = null; + XmlTransformableDocument? document = null; try { @@ -142,7 +140,7 @@ public bool RunXmlTransform(bool isLoggingEnabled = true) return true; } - string localPath = Source; + string? localPath = Source; if (!string.IsNullOrEmpty(ex.SourceUri)) { Uri sourceUri = new(ex.SourceUri); @@ -180,7 +178,7 @@ public bool RunXmlTransform(bool isLoggingEnabled = true) return succeeded; } - private void SaveTransformedFile(XmlTransformableDocument document, string destinationFile) + private void SaveTransformedFile(XmlTransformableDocument document, string? destinationFile) { try { @@ -198,7 +196,7 @@ private void SaveTransformedFile(XmlTransformableDocument document, string desti } } - private XmlTransformableDocument OpenSourceFile(string sourceFile) + private XmlTransformableDocument OpenSourceFile(string? sourceFile) { try { @@ -222,7 +220,7 @@ private XmlTransformableDocument OpenSourceFile(string sourceFile) } } - private XmlTransformation OpenTransformFile(string transformFile, IXmlTransformationLogger logger) + private XmlTransformation OpenTransformFile(string? transformFile, IXmlTransformationLogger? logger) { try { diff --git a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/CreateZipFile.cs b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/CreateZipFile.cs index a5a7f14b5753..20f6952310da 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/CreateZipFile.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/CreateZipFile.cs @@ -9,22 +9,22 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.ZipDeploy public class CreateZipFile : Task { [Required] - public string FolderToZip { get; set; } + public string? FolderToZip { get; set; } [Required] - public string ProjectName { get; set; } + public string? ProjectName { get; set; } [Required] - public string PublishIntermediateTempPath { get; set; } + public string? PublishIntermediateTempPath { get; set; } [Output] - public string CreatedZipPath { get; private set; } + public string? CreatedZipPath { get; private set; } public override bool Execute() { string zipFileName = ProjectName + "-" + DateTime.Now.ToString("yyyyMMddHHmmssFFF") + ".zip"; - CreatedZipPath = Path.Combine(PublishIntermediateTempPath, zipFileName); - ZipFile.CreateFromDirectory(FolderToZip, CreatedZipPath); + CreatedZipPath = Path.Combine(PublishIntermediateTempPath!, zipFileName); + ZipFile.CreateFromDirectory(FolderToZip!, CreatedZipPath); return true; } } diff --git a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/DeploymentResponse.cs b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/DeploymentResponse.cs index d6e47625b19b..e531d3f1e696 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/DeploymentResponse.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/DeploymentResponse.cs @@ -8,18 +8,18 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.ZipDeploy public class DeploymentResponse { [JsonPropertyName("id")] - public string Id { get; set; } + public string? Id { get; set; } [JsonPropertyName("status")] public DeployStatus? Status { get; set; } [JsonPropertyName("log_url")] - public string LogUrl { get; set; } + public string? LogUrl { get; set; } } public static class DeploymentResponseExtensions { - public static string GetLogUrlWithId(this DeploymentResponse deploymentResponse) + public static string? GetLogUrlWithId(this DeploymentResponse deploymentResponse) { if (deploymentResponse is null || string.IsNullOrEmpty(deploymentResponse.LogUrl) @@ -37,7 +37,7 @@ public static string GetLogUrlWithId(this DeploymentResponse deploymentResponse) if (!string.IsNullOrEmpty(pathAndQuery)) { string[] pathAndQueryParts = pathAndQuery.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); - string[] pathWithIdParts = new string[pathAndQueryParts.Length]; + string?[] pathWithIdParts = new string[pathAndQueryParts.Length]; for (int i = pathAndQueryParts.Length - 1; i >= 0; i--) { diff --git a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/HttpClientHelpers.cs b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/HttpClientHelpers.cs index 9a877b2e86c3..53e94bde4692 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/HttpClientHelpers.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/HttpClientHelpers.cs @@ -12,7 +12,7 @@ internal static class HttpClientHelpers internal static readonly string AzureADUserName = Guid.Empty.ToString(); internal static readonly string BearerAuthenticationScheme = "Bearer"; internal static readonly string BasicAuthenticationScheme = "Basic"; - public static async Task PostRequestAsync(this IHttpClient client, Uri uri, string username, string password, string contentType, string userAgent, Encoding encoding, Stream messageBody) + public static async Task PostRequestAsync(this IHttpClient client, Uri uri, string? username, string? password, string contentType, string userAgent, Encoding encoding, Stream messageBody) { AddAuthenticationHeader(username, password, client); client.DefaultRequestHeaders.Add("User-Agent", userAgent); @@ -43,7 +43,7 @@ public static async Task PostRequestAsync(this IHttpClient client } } - public static async Task GetRequestAsync(this IHttpClient client, Uri uri, string username, string password, string userAgent, CancellationToken cancellationToken) + public static async Task GetRequestAsync(this IHttpClient client, Uri uri, string? username, string? password, string userAgent, CancellationToken cancellationToken) { AddAuthenticationHeader(username, password, client); client.DefaultRequestHeaders.Add("User-Agent", userAgent); @@ -59,7 +59,7 @@ public static async Task GetRequestAsync(this IHttpClient client, } } - private static void AddAuthenticationHeader(string username, string password, IHttpClient client) + private static void AddAuthenticationHeader(string? username, string? password, IHttpClient client) { client.DefaultRequestHeaders.Remove("Connection"); diff --git a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/HttpResponseMessageWrapper.cs b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/HttpResponseMessageWrapper.cs index 2ad5d693d2e7..ae31d4c3fbe9 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/HttpResponseMessageWrapper.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/HttpResponseMessageWrapper.cs @@ -32,7 +32,7 @@ private Task GetResponseStream() public IEnumerable GetHeader(string name) { - IEnumerable values; + IEnumerable? values; if (_message.Headers.TryGetValues(name, out values)) { return values; diff --git a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploy.cs b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploy.cs index abfb798abb87..e38f065ee84e 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploy.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploy.cs @@ -13,28 +13,28 @@ public class ZipDeploy : Task private const string UserAgentName = "websdk"; [Required] - public string ZipToPublishPath { get; set; } + public string? ZipToPublishPath { get; set; } [Required] - public string UserAgentVersion { get; set; } + public string? UserAgentVersion { get; set; } [Required] - public string DestinationUsername { get; set; } + public string? DestinationUsername { get; set; } - public string DestinationPassword { get; set; } + public string? DestinationPassword { get; set; } - public string PublishUrl { get; set; } + public string? PublishUrl { get; set; } /// /// Our fallback if PublishUrl is not given, which is the case for ZIP Deploy profiles /// profiles created prior to 15.8 Preview 4. Using this will fail if the site is a slot. /// - public string SiteName { get; set; } + public string? SiteName { get; set; } public override bool Execute() { - string user = DestinationUsername; - string password = DestinationPassword; + string? user = DestinationUsername; + string? password = DestinationPassword; if (string.IsNullOrEmpty(password) && !GetDestinationCredentials(out user, out password)) { @@ -44,24 +44,24 @@ public override bool Execute() using (DefaultHttpClient client = new()) { - System.Threading.Tasks.Task t = ZipDeployAsync(ZipToPublishPath, user, password, PublishUrl, SiteName, UserAgentVersion, client, true); + Task t = ZipDeployAsync(ZipToPublishPath, user, password, PublishUrl, SiteName, UserAgentVersion, client, true); t.Wait(); return t.Result; } } - public async System.Threading.Tasks.Task ZipDeployAsync(string zipToPublishPath, string userName, string password, string publishUrl, string siteName, string userAgentVersion, IHttpClient client, bool logMessages) + public async Task ZipDeployAsync(string? zipToPublishPath, string? userName, string? password, string? publishUrl, string? siteName, string? userAgentVersion, IHttpClient client, bool logMessages) { if (!File.Exists(zipToPublishPath) || client == null) { return false; } - string zipDeployPublishUrl = null; + string? zipDeployPublishUrl = null; if (!string.IsNullOrEmpty(publishUrl)) { - if (!publishUrl.EndsWith("/")) + if (!publishUrl!.EndsWith("/")) { publishUrl += "/"; } @@ -108,12 +108,12 @@ public async System.Threading.Tasks.Task ZipDeployAsync(string zipToPublis Log.LogMessage(Resources.ZIPDEPLOY_Uploaded); } - string deploymentUrl = response.GetHeader("Location").FirstOrDefault(); + string? deploymentUrl = response.GetHeader("Location").FirstOrDefault(); if (!string.IsNullOrEmpty(deploymentUrl)) { ZipDeploymentStatus deploymentStatus = new(client, userAgent, Log, logMessages); - DeploymentResponse deploymentResponse = await deploymentStatus.PollDeploymentStatusAsync(deploymentUrl, userName, password); + DeploymentResponse? deploymentResponse = await deploymentStatus.PollDeploymentStatusAsync(deploymentUrl, userName, password); if (deploymentResponse?.Status == DeployStatus.Success) { Log.LogMessage(MessageImportance.High, Resources.ZIPDEPLOY_Succeeded); @@ -136,7 +136,7 @@ public async System.Threading.Tasks.Task ZipDeployAsync(string zipToPublis private bool GetDestinationCredentials(out string user, out string password) { - VSHostObject hostObj = new(HostObject as System.Collections.Generic.IEnumerable); + VSHostObject hostObj = new(HostObject as IEnumerable); return hostObj.ExtractCredentials(out user, out password); } } diff --git a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploymentStatus.cs b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploymentStatus.cs index 08b215774b69..8be6f2ebc8cc 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploymentStatus.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploymentStatus.cs @@ -29,7 +29,7 @@ public ZipDeploymentStatus(IHttpClient client, string userAgent, TaskLoggingHelp _logMessages = logMessages; } - public async System.Threading.Tasks.Task PollDeploymentStatusAsync(string deploymentUrl, string userName, string password) + public async Task PollDeploymentStatusAsync(string deploymentUrl, string? userName, string? password) { var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(MaxMinutesToWait)); @@ -38,7 +38,7 @@ public async System.Threading.Tasks.Task PollDeploymentStatu _log.LogMessage(Resources.ZIPDEPLOY_DeploymentStatusPolling); } - DeploymentResponse deploymentResponse = null; + DeploymentResponse? deploymentResponse = null; DeployStatus? deployStatus = DeployStatus.Pending; while (!tokenSource.IsCancellationRequested @@ -71,17 +71,17 @@ public async System.Threading.Tasks.Task PollDeploymentStatu return deploymentResponse ?? new() { Status = DeployStatus.Unknown }; } - private async System.Threading.Tasks.Task InvokeGetRequestWithRetryAsync(string url, string userName, string password, int retryCount, TimeSpan retryDelay, CancellationTokenSource cts) + private async Task InvokeGetRequestWithRetryAsync(string url, string? userName, string? password, int retryCount, TimeSpan retryDelay, CancellationTokenSource cts) { - IHttpResponse response = null; + IHttpResponse? response = null; await RetryAsync(async () => { response = await _client.GetRequestAsync(new Uri(url, UriKind.RelativeOrAbsolute), userName, password, _userAgent, cts.Token); }, retryCount, retryDelay); - if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Accepted) + if (response?.StatusCode != HttpStatusCode.OK && response?.StatusCode != HttpStatusCode.Accepted) { - return default(T); + return default; } else { @@ -115,7 +115,7 @@ private async System.Threading.Tasks.Task RetryAsync(Func(string jsonString) + private static T? FromJson(string jsonString) { return JsonSerializer.Deserialize(jsonString, new JsonSerializerOptions diff --git a/src/WebSdk/Publish/Tasks/WebConfigTelemetry.cs b/src/WebSdk/Publish/Tasks/WebConfigTelemetry.cs index 80e0e4385e31..45805412fa71 100644 --- a/src/WebSdk/Publish/Tasks/WebConfigTelemetry.cs +++ b/src/WebSdk/Publish/Tasks/WebConfigTelemetry.cs @@ -26,7 +26,7 @@ public class WebConfigTelemetry ) ); - public static XDocument AddTelemetry(XDocument webConfig, string projectGuid, bool ignoreProjectGuid, string solutionFileFullPath, string projectFileFullPath) + public static XDocument? AddTelemetry(XDocument? webConfig, string? projectGuid, bool ignoreProjectGuid, string? solutionFileFullPath, string? projectFileFullPath) { try { @@ -41,13 +41,13 @@ public static XDocument AddTelemetry(XDocument webConfig, string projectGuid, bo } catch { - // Telemtry + // Telemetry } return webConfig; } - public static string GetProjectGuidFromSolutionFile(string solutionFileFullPath, string projectFileFullPath) + public static string? GetProjectGuidFromSolutionFile(string? solutionFileFullPath, string? projectFileFullPath) { try { @@ -57,7 +57,7 @@ public static string GetProjectGuidFromSolutionFile(string solutionFileFullPath, } int parentLevelsToSearch = 5; - string solutionDirectory = Path.GetDirectoryName(projectFileFullPath); + string? solutionDirectory = Path.GetDirectoryName(projectFileFullPath); while (parentLevelsToSearch-- > 0) { @@ -69,7 +69,7 @@ public static string GetProjectGuidFromSolutionFile(string solutionFileFullPath, IEnumerable solutionFiles = Directory.EnumerateFiles(solutionDirectory, "*.sln", SearchOption.TopDirectoryOnly); foreach (string solutionFile in solutionFiles) { - string projectGuid = GetProjectGuid(solutionFile, projectFileFullPath); + string? projectGuid = GetProjectGuid(solutionFile, projectFileFullPath); if (!string.IsNullOrEmpty(projectGuid)) { return projectGuid; @@ -87,7 +87,7 @@ public static string GetProjectGuidFromSolutionFile(string solutionFileFullPath, return null; } - private static string GetProjectGuid(string solutionFileFullPath, string projectFileFullPath) + private static string? GetProjectGuid(string? solutionFileFullPath, string? projectFileFullPath) { if (!string.IsNullOrEmpty(solutionFileFullPath) && File.Exists(solutionFileFullPath)) { @@ -98,7 +98,7 @@ private static string GetProjectGuid(string solutionFileFullPath, string project if (match.Success) { string projectRelativePath = match.Groups["RELATIVEPATH"].Value.Trim(); - string projectFullPathConstructed = Path.Combine(Path.GetDirectoryName(solutionFileFullPath), projectRelativePath); + string projectFullPathConstructed = Path.Combine(Path.GetDirectoryName(solutionFileFullPath)!, projectRelativePath); projectFullPathConstructed = Path.GetFullPath((new Uri(projectFullPathConstructed)).LocalPath); if (string.Equals(projectFileFullPath, projectFullPathConstructed, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/WebSdk/Publish/Tasks/WebConfigTransform.cs b/src/WebSdk/Publish/Tasks/WebConfigTransform.cs index d23a99fd9234..5caa5d96351a 100644 --- a/src/WebSdk/Publish/Tasks/WebConfigTransform.cs +++ b/src/WebSdk/Publish/Tasks/WebConfigTransform.cs @@ -7,21 +7,21 @@ namespace Microsoft.NET.Sdk.Publish.Tasks { public static class WebConfigTransform { - public static XDocument Transform(XDocument webConfig, string appName, bool configureForAzure, bool useAppHost, string extension, string aspNetCoreModuleName, string aspNetCoreHostingModel, string environmentName, string projectFullPath) + public static XDocument Transform(XDocument? webConfig, string? appName, bool configureForAzure, bool useAppHost, string? extension, string? aspNetCoreModuleName, string? aspNetCoreHostingModel, string? environmentName, string? projectFullPath) { const string HandlersElementName = "handlers"; const string aspNetCoreElementName = "aspNetCore"; const string envVariablesElementName = "environmentVariables"; - if (webConfig == null || webConfig.Root.Name.LocalName != "configuration") + if (webConfig == null || webConfig.Root!.Name.LocalName != "configuration") { webConfig = XDocument.Parse(WebConfigTemplate.Template); } - XElement rootElement = null; + XElement? rootElement = null; // Find the first aspNetCore element. If it is null use the default logic. Else use the root containing the aspNetCore element. - var firstAspNetCoreElement = webConfig.Root.Descendants(aspNetCoreElementName).FirstOrDefault(); + var firstAspNetCoreElement = webConfig.Root!.Descendants(aspNetCoreElementName).FirstOrDefault(); if (firstAspNetCoreElement == null) { rootElement = webConfig.Root.Element("location") == null ? webConfig.Root : webConfig.Root.Element("location"); @@ -37,9 +37,9 @@ public static XDocument Transform(XDocument webConfig, string appName, bool conf TransformHandlers(handlerSection, aspNetCoreModuleName); // aspNetCoreModuleName might not get set if the web.config already has a different module name defined. - string aspNetCoreModuleNameFinalValue = - (string)handlerSection.Elements("add") - .FirstOrDefault(e => string.Equals((string)e.Attribute("name"), "aspnetcore", StringComparison.OrdinalIgnoreCase)) + string? aspNetCoreModuleNameFinalValue = + (string?)handlerSection?.Elements("add") + .FirstOrDefault(e => string.Equals((string?)e.Attribute("name"), "aspnetcore", StringComparison.OrdinalIgnoreCase))? .Attribute("modules"); var aspNetCoreSection = GetOrCreateChild(webServerSection, aspNetCoreElementName); @@ -50,22 +50,22 @@ public static XDocument Transform(XDocument webConfig, string appName, bool conf } // make sure that the aspNetCore element is after handlers element - var aspNetCoreElement = webServerSection.Element(HandlersElementName) + var aspNetCoreElement = webServerSection?.Element(HandlersElementName)? .ElementsBeforeSelf(aspNetCoreElementName).SingleOrDefault(); if (aspNetCoreElement != null) { aspNetCoreElement.Remove(); - webServerSection.Element(HandlersElementName).AddAfterSelf(aspNetCoreElement); + webServerSection?.Element(HandlersElementName)?.AddAfterSelf(aspNetCoreElement); } return webConfig; } - private static void TransformHandlers(XElement handlersElement, string aspNetCoreModuleName) + private static void TransformHandlers(XElement handlersElement, string? aspNetCoreModuleName) { var aspNetCoreElement = handlersElement.Elements("add") - .FirstOrDefault(e => string.Equals((string)e.Attribute("name"), "aspnetcore", StringComparison.OrdinalIgnoreCase)); + .FirstOrDefault(e => string.Equals((string?)e.Attribute("name"), "aspnetcore", StringComparison.OrdinalIgnoreCase)); if (aspNetCoreElement == null) { @@ -86,11 +86,11 @@ private static void TransformHandlers(XElement handlersElement, string aspNetCor SetAttributeValueIfEmpty(aspNetCoreElement, "resourceType", "Unspecified"); } - private static void TransformAspNetCore(XElement aspNetCoreElement, string appName, bool configureForAzure, bool useAppHost, string extension, string aspNetCoreModuleName, string aspNetCoreHostingModelValue, string projectFullPath) + private static void TransformAspNetCore(XElement aspNetCoreElement, string? appName, bool configureForAzure, bool useAppHost, string? extension, string? aspNetCoreModuleName, string? aspNetCoreHostingModelValue, string? projectFullPath) { // Forward slashes currently work neither in AspNetCoreModule nor in dotnet so they need to be // replaced with backwards slashes when the application is published on a non-Windows machine - var appPath = Path.Combine(".", appName).Replace("/", "\\"); + var appPath = Path.Combine(".", appName!).Replace("/", "\\"); RemoveLauncherArgs(aspNetCoreElement); if (useAppHost) @@ -115,12 +115,12 @@ private static void TransformAspNetCore(XElement aspNetCoreElement, string appNa var attributes = aspNetCoreElement.Attributes().ToList(); var processPathIndex = attributes.FindIndex(a => a.Name.LocalName == "processPath"); // if the app path is already there in the web.config, don't do anything. - if (string.Equals(appPath, (string)argumentsAttribute, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(appPath, (string?)argumentsAttribute, StringComparison.OrdinalIgnoreCase)) { appPath = string.Empty; } attributes.Insert(processPathIndex + 1, - new XAttribute("arguments", (appPath + " " + (string)argumentsAttribute).Trim())); + new XAttribute("arguments", (appPath + " " + (string?)argumentsAttribute).Trim())); aspNetCoreElement.Attributes().Remove(); aspNetCoreElement.Add(attributes); @@ -143,11 +143,11 @@ private static void TransformAspNetCore(XElement aspNetCoreElement, string appNa var hostingModelAttributeValue = aspNetCoreElement.Attribute("hostingModel"); - string projectWebConfigPath = null; + string? projectWebConfigPath = null; if (!string.IsNullOrEmpty(projectFullPath)) { - string projectFolder = Path.GetDirectoryName(projectFullPath); - projectWebConfigPath = Path.Combine(projectFolder, "web.config"); + string? projectFolder = Path.GetDirectoryName(projectFullPath); + projectWebConfigPath = Path.Combine(projectFolder!, "web.config"); } if (File.Exists(projectWebConfigPath)) @@ -165,11 +165,11 @@ private static void TransformAspNetCore(XElement aspNetCoreElement, string appNa } - private static void SetAspNetCoreHostingModel(string aspNetCoreHostingModelValue, string aspNetCoreModuleName, XElement aspNetCoreElement) + private static void SetAspNetCoreHostingModel(string? aspNetCoreHostingModelValue, string? aspNetCoreModuleName, XElement aspNetCoreElement) { if (!string.IsNullOrEmpty(aspNetCoreHostingModelValue)) { - switch (aspNetCoreHostingModelValue.ToUpperInvariant()) + switch (aspNetCoreHostingModelValue?.ToUpperInvariant()) { case "INPROCESS": // In process is not supported for AspNetCoreModule. @@ -188,11 +188,11 @@ private static void SetAspNetCoreHostingModel(string aspNetCoreHostingModelValue } } - private static void TransformEnvironmentVariables(XElement envVariablesElement, string environmentName) + private static void TransformEnvironmentVariables(XElement envVariablesElement, string? environmentName) { var envVariableElement = envVariablesElement.Elements("environmentVariable") - .FirstOrDefault(e => string.Equals((string)e.Attribute("name"), "ASPNETCORE_ENVIRONMENT", StringComparison.OrdinalIgnoreCase)); + .FirstOrDefault(e => string.Equals((string?)e.Attribute("name"), "ASPNETCORE_ENVIRONMENT", StringComparison.OrdinalIgnoreCase)); if (envVariableElement == null) { @@ -204,25 +204,25 @@ private static void TransformEnvironmentVariables(XElement envVariablesElement, envVariableElement.SetAttributeValue("value", environmentName); } - private static XElement GetOrCreateChild(XElement parent, string childName) + private static XElement GetOrCreateChild(XElement? parent, string childName) { - var childElement = parent.Element(childName); + var childElement = parent?.Element(childName); if (childElement == null) { childElement = new XElement(childName); - parent.Add(childElement); + parent?.Add(childElement); } return childElement; } - private static void SetAttributeValueIfEmpty(XElement element, string attributeName, string value) + private static void SetAttributeValueIfEmpty(XElement element, string attributeName, string? value) { - element.SetAttributeValue(attributeName, (string)element.Attribute(attributeName) ?? value); + element.SetAttributeValue(attributeName, (string?)element.Attribute(attributeName) ?? value); } private static void RemoveLauncherArgs(XElement aspNetCoreElement) { - var arguments = (string)aspNetCoreElement.Attribute("arguments"); + var arguments = (string?)aspNetCoreElement.Attribute("arguments"); if (arguments != null) { @@ -240,16 +240,16 @@ private static void RemoveLauncherArgs(XElement aspNetCoreElement) } } - public static XDocument AddProjectGuidToWebConfig(XDocument document, string projectGuid, bool ignoreProjectGuid) + public static XDocument? AddProjectGuidToWebConfig(XDocument? document, string? projectGuid, bool ignoreProjectGuid) { try { if (document != null && !string.IsNullOrEmpty(projectGuid)) { IEnumerable comments = document.DescendantNodes().OfType(); - projectGuid = projectGuid.Trim('{', '}', '(', ')').Trim(); + projectGuid = projectGuid?.Trim('{', '}', '(', ')').Trim(); string projectGuidValue = string.Format("ProjectGuid: {0}", projectGuid); - XComment projectGuidComment = comments.FirstOrDefault(comment => string.Equals(comment.Value, projectGuidValue, StringComparison.OrdinalIgnoreCase)); + XComment? projectGuidComment = comments.FirstOrDefault(comment => string.Equals(comment.Value, projectGuidValue, StringComparison.OrdinalIgnoreCase)); if (projectGuidComment != null) { if (ignoreProjectGuid) @@ -262,7 +262,7 @@ public static XDocument AddProjectGuidToWebConfig(XDocument document, string pro if (!ignoreProjectGuid) { - document.LastNode.AddAfterSelf(new XComment(projectGuidValue)); + document?.LastNode?.AddAfterSelf(new XComment(projectGuidValue)); return document; } } diff --git a/src/WebSdk/Publish/Tasks/WebJobsCommandGenerator.cs b/src/WebSdk/Publish/Tasks/WebJobsCommandGenerator.cs index 40d7f83f5c54..da2c2c968f2a 100644 --- a/src/WebSdk/Publish/Tasks/WebJobsCommandGenerator.cs +++ b/src/WebSdk/Publish/Tasks/WebJobsCommandGenerator.cs @@ -5,11 +5,11 @@ namespace Microsoft.NET.Sdk.Publish.Tasks { public static class WebJobsCommandGenerator { - public static string RunCommand(string targetPath, bool useAppHost, string executableExtension) + public static string RunCommand(string? targetPath, bool useAppHost, string? executableExtension) { - string appName = Path.GetFileName(targetPath); + string? appName = Path.GetFileName(targetPath); - string command = $"dotnet {appName}"; + string? command = $"dotnet {appName}"; if (useAppHost) { command = Path.ChangeExtension(appName, !string.IsNullOrWhiteSpace(executableExtension) ? executableExtension : null); From 4ddb7b2eb09835ca45cbacbc619b41c445c2631c Mon Sep 17 00:00:00 2001 From: Michael Yanni Date: Thu, 28 Mar 2024 12:37:01 -0700 Subject: [PATCH 3/7] Got Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.csproj building with nullable enable. Added WorkloadRootPath.cs since the tuples were problematic with nullability logic. --- src/Common/WorkloadFileBasedInstall.cs | 8 ++--- .../CachingWorkloadResolver.cs | 2 +- ....NET.Sdk.WorkloadMSBuildSdkResolver.csproj | 1 + .../WorkloadSdkResolver.cs | 29 ++++++++-------- .../SdkDirectoryWorkloadManifestProvider.cs | 6 ++-- .../WorkloadInstallType.cs | 8 ++--- .../WorkloadResolver.cs | 34 +++++++++---------- .../WorkloadRootPath.cs | 7 ++++ 8 files changed, 50 insertions(+), 45 deletions(-) create mode 100644 src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadRootPath.cs diff --git a/src/Common/WorkloadFileBasedInstall.cs b/src/Common/WorkloadFileBasedInstall.cs index c252671ce64d..4afc84005e80 100644 --- a/src/Common/WorkloadFileBasedInstall.cs +++ b/src/Common/WorkloadFileBasedInstall.cs @@ -5,7 +5,7 @@ namespace Microsoft.DotNet.Workloads.Workload { static class WorkloadFileBasedInstall { - public static bool IsUserLocal(string dotnetDir, string sdkFeatureBand) + public static bool IsUserLocal(string? dotnetDir, string? sdkFeatureBand) => File.Exists(GetUserInstallFilePath(dotnetDir, sdkFeatureBand)); internal static void SetUserLocal(string dotnetDir, string sdkFeatureBand) @@ -16,9 +16,9 @@ internal static void SetUserLocal(string dotnetDir, string sdkFeatureBand) File.WriteAllText(filePath, ""); } - private static string GetUserInstallFilePath(string dotnetDir, string sdkFeatureBand) + private static string GetUserInstallFilePath(string? dotnetDir, string? sdkFeatureBand) { - if (sdkFeatureBand.Contains("-") || !sdkFeatureBand.EndsWith("00", StringComparison.Ordinal)) + if (sdkFeatureBand != null && (sdkFeatureBand.Contains("-") || !sdkFeatureBand.EndsWith("00", StringComparison.Ordinal))) { // The user passed in the sdk version. Derive the feature band version. if (!Version.TryParse(sdkFeatureBand.Split('-')[0], out var sdkVersionParsed)) @@ -34,7 +34,7 @@ static int Last2DigitsTo0(int versionBuild) sdkFeatureBand = $"{sdkVersionParsed.Major}.{sdkVersionParsed.Minor}.{Last2DigitsTo0(sdkVersionParsed.Build)}"; } - return Path.Combine(dotnetDir, "metadata", "workloads", sdkFeatureBand, "userlocal"); + return Path.Combine(dotnetDir!, "metadata", "workloads", sdkFeatureBand!, "userlocal"); } } } diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs index dc8976ad53c7..2bcb8b7342cb 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs @@ -175,7 +175,7 @@ private static ResolutionResult Resolve(string sdkReferenceName, IWorkloadManife return new NullResolutionResult(); } - public ResolutionResult Resolve(string sdkReferenceName, string dotnetRootPath, string sdkVersion, string? userProfileDir, string? globalJsonPath) + public ResolutionResult Resolve(string sdkReferenceName, string? dotnetRootPath, string? sdkVersion, string? userProfileDir, string? globalJsonPath) { if (!_enabled) { diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.csproj b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.csproj index 7be14c4cf1fe..eeadebe061b7 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.csproj +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.csproj @@ -3,6 +3,7 @@ $(ResolverTargetFramework) true + enable diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/WorkloadSdkResolver.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/WorkloadSdkResolver.cs index 2246bdbed6af..6230bf03f208 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/WorkloadSdkResolver.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/WorkloadSdkResolver.cs @@ -24,17 +24,17 @@ public class WorkloadSdkResolver : SdkResolver private class CachedState { - public string DotnetRootPath { get; init; } - public string SdkVersion { get; init; } + public string? DotnetRootPath { get; init; } + public string? SdkVersion { get; init; } - public string GlobalJsonPath { get; init; } + public string? GlobalJsonPath { get; init; } - public CachingWorkloadResolver WorkloadResolver { get; init; } + public CachingWorkloadResolver? WorkloadResolver { get; init; } } - public override SdkResult Resolve(SdkReference sdkReference, SdkResolverContext resolverContext, SdkResultFactory factory) + public override SdkResult? Resolve(SdkReference sdkReference, SdkResolverContext resolverContext, SdkResultFactory factory) { - CachedState cachedState = null; + CachedState? cachedState = null; if (resolverContext.State is CachedState resolverContextState) { @@ -63,14 +63,13 @@ public override SdkResult Resolve(SdkReference sdkReference, SdkResolverContext resolverContext.State = cachedState; } - string userProfileDir = CliFolderPathCalculatorCore.GetDotnetUserProfileFolderPath(); - var result = cachedState.WorkloadResolver.Resolve(sdkReference.Name, cachedState.DotnetRootPath, cachedState.SdkVersion, userProfileDir, cachedState.GlobalJsonPath); + string? userProfileDir = CliFolderPathCalculatorCore.GetDotnetUserProfileFolderPath(); + var result = cachedState.WorkloadResolver?.Resolve(sdkReference.Name, cachedState.DotnetRootPath, cachedState.SdkVersion, userProfileDir, cachedState.GlobalJsonPath); - - return result.ToSdkResult(sdkReference, factory); + return result?.ToSdkResult(sdkReference, factory); } - private string GetSdkDirectory(SdkResolverContext context) + private string? GetSdkDirectory(SdkResolverContext context) { #if NET var sdkDirectory = Path.GetDirectoryName(typeof(DotnetFiles).Assembly.Location); @@ -86,17 +85,17 @@ private string GetSdkDirectory(SdkResolverContext context) } - private string GetDotNetRoot(SdkResolverContext context) + private string? GetDotNetRoot(SdkResolverContext context) { var sdkDirectory = GetSdkDirectory(context); - var dotnetRoot = Directory.GetParent(sdkDirectory).Parent.FullName; + var dotnetRoot = Directory.GetParent(sdkDirectory!)?.Parent?.FullName; return dotnetRoot; } // Duplicated logic from DotNetMSBuildSdkResolver - private static string GetGlobalJsonStartDir(SdkResolverContext context) + private static string? GetGlobalJsonStartDir(SdkResolverContext context) { - string startDir = Environment.CurrentDirectory; + string? startDir = Environment.CurrentDirectory; if (!string.IsNullOrWhiteSpace(context.SolutionFilePath)) { diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.cs index 74eabb18be64..82a18f734ec0 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.cs @@ -18,7 +18,7 @@ public partial class SdkDirectoryWorkloadManifestProvider : IWorkloadManifestPro { public const string WorkloadSetsFolderName = "workloadsets"; - private readonly string _sdkRootPath; + private readonly string? _sdkRootPath; private readonly SdkFeatureBand _sdkVersionBand; private readonly string[] _manifestRoots; private static HashSet _outdatedManifestIds = new(StringComparer.OrdinalIgnoreCase) { "microsoft.net.workload.android", "microsoft.net.workload.blazorwebassembly", "microsoft.net.workload.ios", @@ -32,7 +32,7 @@ public partial class SdkDirectoryWorkloadManifestProvider : IWorkloadManifestPro private WorkloadSet? _manifestsFromInstallState; private string? _installStateFilePath; - public SdkDirectoryWorkloadManifestProvider(string sdkRootPath, string sdkVersion, string? userProfileDir, string? globalJsonPath) + public SdkDirectoryWorkloadManifestProvider(string? sdkRootPath, string? sdkVersion, string? userProfileDir, string? globalJsonPath) : this(sdkRootPath, sdkVersion, Environment.GetEnvironmentVariable, userProfileDir, globalJsonPath) { } @@ -42,7 +42,7 @@ public static SdkDirectoryWorkloadManifestProvider ForWorkloadSet(string sdkRoot return new SdkDirectoryWorkloadManifestProvider(sdkRootPath, sdkVersion, Environment.GetEnvironmentVariable, userProfileDir, globalJsonPath: null, workloadSetVersion); } - internal SdkDirectoryWorkloadManifestProvider(string sdkRootPath, string sdkVersion, Func getEnvironmentVariable, string? userProfileDir, string? globalJsonPath = null, string? workloadSetVersion = null) + internal SdkDirectoryWorkloadManifestProvider(string? sdkRootPath, string? sdkVersion, Func getEnvironmentVariable, string? userProfileDir, string? globalJsonPath = null, string? workloadSetVersion = null) { if (string.IsNullOrWhiteSpace(sdkVersion)) { diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadInstallType.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadInstallType.cs index 83f74012c2bf..8a9fb53b68fc 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadInstallType.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadInstallType.cs @@ -25,9 +25,9 @@ public static class WorkloadInstallType /// /// The SDK version to check. /// The associated with the SDK. - public static InstallType GetWorkloadInstallType(SdkFeatureBand sdkFeatureBand, string dotnetDir) + public static InstallType GetWorkloadInstallType(SdkFeatureBand sdkFeatureBand, string? dotnetDir) { - string installerTypePath = Path.Combine(dotnetDir, "metadata", + string installerTypePath = Path.Combine(dotnetDir!, "metadata", "workloads", $"{sdkFeatureBand.ToStringWithoutPrerelease()}", "installertype"); if (File.Exists(Path.Combine(installerTypePath, "msi"))) @@ -38,13 +38,13 @@ public static InstallType GetWorkloadInstallType(SdkFeatureBand sdkFeatureBand, return InstallType.FileBased; } - public static string GetInstallStateFolder(SdkFeatureBand sdkFeatureBand, string dotnetDir) + public static string GetInstallStateFolder(SdkFeatureBand sdkFeatureBand, string? dotnetDir) { var installType = GetWorkloadInstallType(sdkFeatureBand, dotnetDir); if (installType == InstallType.FileBased) { - return Path.Combine(dotnetDir, "metadata", "workloads", sdkFeatureBand.ToString(), "InstallState"); + return Path.Combine(dotnetDir!, "metadata", "workloads", sdkFeatureBand.ToString(), "InstallState"); } else if (installType == InstallType.Msi) { diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadResolver.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadResolver.cs index 7c22a398a298..c1832de2b9c5 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadResolver.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadResolver.cs @@ -22,32 +22,32 @@ public class WorkloadResolver : IWorkloadResolver private readonly Dictionary _packs = new(); private IWorkloadManifestProvider _manifestProvider; private string[] _currentRuntimeIdentifiers; - private readonly (string path, bool installable)[] _dotnetRootPaths; + private readonly WorkloadRootPath[] _dotnetRootPaths; private Func? _fileExistOverride; private Func? _directoryExistOverride; - public static WorkloadResolver Create(IWorkloadManifestProvider manifestProvider, string dotnetRootPath, string sdkVersion, string? userProfileDir) + public static WorkloadResolver Create(IWorkloadManifestProvider manifestProvider, string? dotnetRootPath, string? sdkVersion, string? userProfileDir) { - string runtimeIdentifierChainPath = Path.Combine(dotnetRootPath, "sdk", sdkVersion, "NETCoreSdkRuntimeIdentifierChain.txt"); + string runtimeIdentifierChainPath = Path.Combine(dotnetRootPath!, "sdk", sdkVersion!, "NETCoreSdkRuntimeIdentifierChain.txt"); string[] currentRuntimeIdentifiers = File.Exists(runtimeIdentifierChainPath) ? File.ReadAllLines(runtimeIdentifierChainPath).Where(l => !string.IsNullOrEmpty(l)).ToArray() : new string[] { }; - (string path, bool installable)[] workloadRootPaths; + WorkloadRootPath[] workloadRootPaths; if (userProfileDir != null && WorkloadFileBasedInstall.IsUserLocal(dotnetRootPath, sdkVersion) && Directory.Exists(userProfileDir)) { - workloadRootPaths = new[] { (userProfileDir, true), (dotnetRootPath, true) }; + workloadRootPaths = [new(userProfileDir, true), new(dotnetRootPath, true)]; } else { - workloadRootPaths = new[] { (dotnetRootPath, true) }; + workloadRootPaths = [new(dotnetRootPath, true)]; } var packRootEnvironmentVariable = Environment.GetEnvironmentVariable(EnvironmentVariableNames.WORKLOAD_PACK_ROOTS); if (!string.IsNullOrEmpty(packRootEnvironmentVariable)) { - workloadRootPaths = packRootEnvironmentVariable.Split(Path.PathSeparator).Select(path => (path, false)).Concat(workloadRootPaths).ToArray(); + workloadRootPaths = packRootEnvironmentVariable.Split(Path.PathSeparator).Select(path => new WorkloadRootPath(path, false)).Concat(workloadRootPaths).ToArray(); } return new WorkloadResolver(manifestProvider, workloadRootPaths, currentRuntimeIdentifiers); @@ -59,13 +59,11 @@ public static WorkloadResolver CreateForTests(IWorkloadManifestProvider manifest { throw new ArgumentNullException(nameof(userProfileDir)); } - (string path, bool installable)[] dotNetRootPaths = userLocal - ? new[] { (userProfileDir!, true), (dotNetRoot, true) } - : new[] { (dotNetRoot, true) }; + WorkloadRootPath[] dotNetRootPaths = userLocal ? [new(userProfileDir!, true), new(dotNetRoot, true)] : [new(dotNetRoot, true)]; return CreateForTests(manifestProvider, dotNetRootPaths, currentRuntimeIdentifiers); } - public static WorkloadResolver CreateForTests(IWorkloadManifestProvider manifestProvider, (string path, bool installable)[] dotNetRootPaths, string[]? currentRuntimeIdentifiers = null) + public static WorkloadResolver CreateForTests(IWorkloadManifestProvider manifestProvider, WorkloadRootPath[] dotNetRootPaths, string[]? currentRuntimeIdentifiers = null) { if (currentRuntimeIdentifiers == null) { @@ -77,7 +75,7 @@ public static WorkloadResolver CreateForTests(IWorkloadManifestProvider manifest /// /// Creates a resolver by composing all the manifests from the provider. /// - private WorkloadResolver(IWorkloadManifestProvider manifestProvider, (string path, bool installable)[] dotnetRootPaths, string[] currentRuntimeIdentifiers) + private WorkloadResolver(IWorkloadManifestProvider manifestProvider, WorkloadRootPath[] dotnetRootPaths, string[] currentRuntimeIdentifiers) : this(dotnetRootPaths, currentRuntimeIdentifiers, manifestProvider.GetSdkFeatureBand()) { _manifestProvider = manifestProvider; @@ -89,7 +87,7 @@ private WorkloadResolver(IWorkloadManifestProvider manifestProvider, (string pat /// /// Creates a resolver with no manifests. /// - private WorkloadResolver((string path, bool installable)[] dotnetRootPaths, string[] currentRuntimeIdentifiers, string sdkFeatureBand) + private WorkloadResolver(WorkloadRootPath[] dotnetRootPaths, string[] currentRuntimeIdentifiers, string sdkFeatureBand) { _dotnetRootPaths = dotnetRootPaths; _currentRuntimeIdentifiers = currentRuntimeIdentifiers; @@ -315,26 +313,26 @@ string GetPackPath(WorkloadPackId resolvedPackageId, string packageVersion, Work { case WorkloadPackKind.Framework: case WorkloadPackKind.Sdk: - packPath = Path.Combine(rootPath.path, "packs", resolvedPackageId.ToString(), packageVersion); + packPath = Path.Combine(rootPath.Path!, "packs", resolvedPackageId.ToString(), packageVersion); isFile = false; break; case WorkloadPackKind.Template: - packPath = Path.Combine(rootPath.path, "template-packs", resolvedPackageId.GetNuGetCanonicalId() + "." + packageVersion.ToLowerInvariant() + ".nupkg"); + packPath = Path.Combine(rootPath.Path!, "template-packs", resolvedPackageId.GetNuGetCanonicalId() + "." + packageVersion.ToLowerInvariant() + ".nupkg"); isFile = true; break; case WorkloadPackKind.Library: - packPath = Path.Combine(rootPath.path, "library-packs", resolvedPackageId.GetNuGetCanonicalId() + "." + packageVersion.ToLowerInvariant() + ".nupkg"); + packPath = Path.Combine(rootPath.Path!, "library-packs", resolvedPackageId.GetNuGetCanonicalId() + "." + packageVersion.ToLowerInvariant() + ".nupkg"); isFile = true; break; case WorkloadPackKind.Tool: - packPath = Path.Combine(rootPath.path, "tool-packs", resolvedPackageId.ToString(), packageVersion); + packPath = Path.Combine(rootPath.Path!, "tool-packs", resolvedPackageId.ToString(), packageVersion); isFile = false; break; default: throw new ArgumentException($"The package kind '{kind}' is not known", nameof(kind)); } - if (rootPath.installable && firstInstallablePackPath is null) + if (rootPath.Installable && firstInstallablePackPath is null) { firstInstallablePackPath = packPath; } diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadRootPath.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadRootPath.cs new file mode 100644 index 000000000000..24d9ab70c4bc --- /dev/null +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadRootPath.cs @@ -0,0 +1,7 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.NET.Sdk.WorkloadManifestReader +{ + public record WorkloadRootPath(string? Path, bool Installable); +} From 9ef34078efd325c3ffb52a4f1bcd3ccf2c5c10b1 Mon Sep 17 00:00:00 2001 From: Michael Yanni Date: Tue, 2 Apr 2024 11:22:57 -0700 Subject: [PATCH 4/7] Got Microsoft.NET.Build.Extensions.Tasks.csproj building with nullable enable. --- .../Common/ConflictResolution/ConflictItem.cs | 44 +++++++++--------- .../ConflictResolution/ConflictResolver.cs | 45 +++++++++---------- .../ConflictResolution/FrameworkListReader.cs | 6 +-- .../ConflictResolution/PackageOverride.cs | 2 +- .../PackageOverrideResolver.cs | 24 +++++----- .../Common/ConflictResolution/PackageRank.cs | 10 ++--- .../PlatformManifestReader.cs | 6 +-- .../ResolvePackageFileConflicts.cs | 44 +++++++++--------- .../ResolvePublishOutputConflicts.cs | 18 ++++---- .../Common/FileUtilities.MetadataReader.cs | 17 ++++--- src/Tasks/Common/FileUtilities.cs | 6 +-- src/Tasks/Common/ItemUtilities.cs | 26 +++++------ src/Tasks/Common/MSBuildUtilities.cs | 8 ++-- src/Tasks/Common/MessageBase.cs | 15 +++---- src/Tasks/Common/NuGetUtils.cs | 9 ++-- .../AddFacadesToReferences.cs | 12 ++--- .../FileUtilities.net45.cs | 2 +- .../GetDependsOnNETStandard.cs | 4 +- .../GetDependsOnNETStandard.net46.cs | 2 +- ...icrosoft.NET.Build.Extensions.Tasks.csproj | 1 + 20 files changed, 152 insertions(+), 149 deletions(-) diff --git a/src/Tasks/Common/ConflictResolution/ConflictItem.cs b/src/Tasks/Common/ConflictResolution/ConflictItem.cs index 0c06c12daad2..0970edd3f9a0 100644 --- a/src/Tasks/Common/ConflictResolution/ConflictItem.cs +++ b/src/Tasks/Common/ConflictResolution/ConflictItem.cs @@ -23,15 +23,15 @@ internal enum ConflictItemType internal interface IConflictItem { - Version AssemblyVersion { get; } + Version? AssemblyVersion { get; } ConflictItemType ItemType { get; } bool Exists { get; } - string FileName { get; } - Version FileVersion { get; } - string PackageId { get; } - string DisplayName { get; } + string? FileName { get; } + Version? FileVersion { get; } + string? PackageId { get; } + string? DisplayName { get; } - ConflictVersion PackageVersion { get; } + ConflictVersion? PackageVersion { get; } } // Wraps an ITask item and adds lazy evaluated properties used by Conflict resolution. @@ -43,7 +43,7 @@ public ConflictItem(ITaskItem originalItem, ConflictItemType itemType) ItemType = itemType; } - public ConflictItem(string fileName, string packageId, Version assemblyVersion, Version fileVersion) + public ConflictItem(string fileName, string packageId, Version? assemblyVersion, Version? fileVersion) { OriginalItem = null; ItemType = ConflictItemType.Platform; @@ -55,8 +55,8 @@ public ConflictItem(string fileName, string packageId, Version assemblyVersion, } private bool _hasAssemblyVersion; - private Version _assemblyVersion; - public Version AssemblyVersion + private Version? _assemblyVersion; + public Version? AssemblyVersion { get { @@ -104,8 +104,8 @@ public bool Exists } } - private string _fileName; - public string FileName + private string? _fileName; + public string? FileName { get { @@ -119,8 +119,8 @@ public string FileName } private bool _hasFileVersion; - private Version _fileVersion; - public Version FileVersion + private Version? _fileVersion; + public Version? FileVersion { get { @@ -152,10 +152,10 @@ private set } } - public ITaskItem OriginalItem { get; } + public ITaskItem? OriginalItem { get; } - private string _packageId; - public string PackageId + private string? _packageId; + public string? PackageId { get { @@ -176,8 +176,8 @@ public string PackageId } private bool _hasPackageVersion; - private ConflictVersion _packageVersion; - public ConflictVersion PackageVersion + private ConflictVersion? _packageVersion; + public ConflictVersion? PackageVersion { get { @@ -200,8 +200,8 @@ public ConflictVersion PackageVersion } } - private string _sourcePath; - public string SourcePath + private string? _sourcePath; + public string? SourcePath { get { @@ -215,8 +215,8 @@ public string SourcePath private set { _sourcePath = value; } } - private string _displayName; - public string DisplayName + private string? _displayName; + public string? DisplayName { get { diff --git a/src/Tasks/Common/ConflictResolution/ConflictResolver.cs b/src/Tasks/Common/ConflictResolution/ConflictResolver.cs index e6e6d87d6151..8248adcc114a 100644 --- a/src/Tasks/Common/ConflictResolution/ConflictResolver.cs +++ b/src/Tasks/Common/ConflictResolution/ConflictResolver.cs @@ -18,7 +18,7 @@ internal class ConflictResolver : IDisposable where TConflictItem private Dictionary> _unresolvedConflictItems = new(StringComparer.Ordinal); // Callback for unresolved conflicts, currently just used as a test hook - public Action UnresolvedConflictHandler { get; set; } + public Action? UnresolvedConflictHandler { get; set; } public ConflictResolver(PackageRank packageRank, PackageOverrideResolver packageOverrideResolver, Logger log) { @@ -27,7 +27,7 @@ public ConflictResolver(PackageRank packageRank, PackageOverrideResolver conflictItems, Func getItemKey, + public void ResolveConflicts(IEnumerable conflictItems, Func getItemKey, ConflictCallback foundConflict, bool commitWinner = true) { if (conflictItems == null) @@ -44,9 +44,9 @@ public void ResolveConflicts(IEnumerable conflictItems, Func conflictItems, Func unresolvedConflictsForKey; - if (!_unresolvedConflictItems.TryGetValue(itemKey, out unresolvedConflictsForKey)) + List? unresolvedConflictsForKey; + if (!_unresolvedConflictItems.TryGetValue(itemKey!, out unresolvedConflictsForKey)) { unresolvedConflictsForKey = new List(); - _unresolvedConflictItems[itemKey] = unresolvedConflictsForKey; + _unresolvedConflictItems[itemKey!] = unresolvedConflictsForKey; // This is the first time we hit an unresolved conflict for this key, so // add the existing item to the unresolved conflicts list @@ -81,11 +81,11 @@ public void ResolveConflicts(IEnumerable conflictItems, Func conflictItems, Func previouslyUnresolvedConflicts; - if (_unresolvedConflictItems.TryGetValue(itemKey, out previouslyUnresolvedConflicts) && + List? previouslyUnresolvedConflicts; + if (_unresolvedConflictItems.TryGetValue(itemKey!, out previouslyUnresolvedConflicts) && previouslyUnresolvedConflicts.Contains(loser)) { List newUnresolvedConflicts = new(); @@ -129,16 +129,16 @@ public void ResolveConflicts(IEnumerable conflictItems, Func 0) { - _unresolvedConflictItems[itemKey] = newUnresolvedConflicts; + _unresolvedConflictItems[itemKey!] = newUnresolvedConflicts; } } } else if (commitWinner) { - _winningItemsByKey[itemKey] = conflictItem; + _winningItemsByKey[itemKey!] = conflictItem; } } } @@ -161,11 +161,10 @@ public void Dispose() // Call ResolveConflict to generate the right log message about the unresolved conflict ResolveConflict(firstItem, unresolvedConflictItem, logUnresolvedConflicts: true); } - } } - private TConflictItem ResolveConflict(TConflictItem item1, TConflictItem item2, bool logUnresolvedConflicts) + private TConflictItem? ResolveConflict(TConflictItem item1, TConflictItem item2, bool logUnresolvedConflicts) { var winner = _packageOverrideResolver.Resolve(item1, item2); if (winner != null) @@ -214,9 +213,9 @@ private TConflictItem ResolveConflict(TConflictItem item1, TConflictItem item2, // only handle cases where assembly version is different, and not null (implicit here due to xor above) if (assemblyVersion1 != assemblyVersion2) { - string winningDisplayName; - Version winningVersion; - Version losingVersion; + string? winningDisplayName; + Version? winningVersion; + Version? losingVersion; if (assemblyVersion1 > assemblyVersion2) { winningDisplayName = item1.DisplayName; @@ -263,9 +262,9 @@ private TConflictItem ResolveConflict(TConflictItem item1, TConflictItem item2, if (fileVersion1 != fileVersion2) { - string winningDisplayName; - Version winningVersion; - Version losingVersion; + string? winningDisplayName; + Version? winningVersion; + Version? losingVersion; if (fileVersion1 > fileVersion2) { winningDisplayName = item1.DisplayName; @@ -354,7 +353,7 @@ private TConflictItem ResolveConflict(TConflictItem item1, TConflictItem item2, return null; } - private void LogMessage(string conflictMessage, string format, params object[] args) + private void LogMessage(string conflictMessage, string format, params object?[] args) { _log.LogMessage( MessageImportance.Low, diff --git a/src/Tasks/Common/ConflictResolution/FrameworkListReader.cs b/src/Tasks/Common/ConflictResolution/FrameworkListReader.cs index 9619e82cf485..09e76766836e 100644 --- a/src/Tasks/Common/ConflictResolution/FrameworkListReader.cs +++ b/src/Tasks/Common/ConflictResolution/FrameworkListReader.cs @@ -31,7 +31,7 @@ public IEnumerable GetConflictItems(string frameworkListPath, Logg // Need to include assembly name in the key here, since both Microsoft.NET.Build.Tasks and Microsoft.NET.Build.Extensions.Tasks share this code, // but can't share the types of the ConflictItem objects. - string assemblyName = typeof(FrameworkListReader).GetTypeInfo().Assembly.FullName; + string? assemblyName = typeof(FrameworkListReader).GetTypeInfo().Assembly.FullName; string objectKey = $"{assemblyName}:{nameof(FrameworkListReader)}:{frameworkListPath}"; @@ -64,7 +64,7 @@ private static IEnumerable LoadConflictItems(string frameworkListP var frameworkList = XDocument.Load(frameworkListPath); var ret = new List(); - foreach (var file in frameworkList.Root.Elements("File")) + foreach (var file in frameworkList.Root?.Elements("File") ?? []) { var type = file.Attribute("Type")?.Value; @@ -86,7 +86,7 @@ private static IEnumerable LoadConflictItems(string frameworkListP return Enumerable.Empty(); } - Version assemblyVersion; + Version? assemblyVersion; if (string.IsNullOrEmpty(assemblyVersionString) || !Version.TryParse(assemblyVersionString, out assemblyVersion)) { string errorMessage = string.Format(CultureInfo.CurrentCulture, Strings.ErrorParsingFrameworkListInvalidValue, diff --git a/src/Tasks/Common/ConflictResolution/PackageOverride.cs b/src/Tasks/Common/ConflictResolution/PackageOverride.cs index ba8648ce28f1..cb206fc7b9b6 100644 --- a/src/Tasks/Common/ConflictResolution/PackageOverride.cs +++ b/src/Tasks/Common/ConflictResolution/PackageOverride.cs @@ -58,7 +58,7 @@ private static IEnumerable> CreateOverriddenPacka { string versionString = trimmedOverriddenPackagesAndVersion.Substring(separatorIndex + 1); string overriddenPackage = trimmedOverriddenPackagesAndVersion.Substring(0, separatorIndex); - if (OverrideVersion.TryParse(versionString, out OverrideVersion version)) + if (OverrideVersion.TryParse(versionString, out OverrideVersion? version)) { yield return Tuple.Create(overriddenPackage, version); } diff --git a/src/Tasks/Common/ConflictResolution/PackageOverrideResolver.cs b/src/Tasks/Common/ConflictResolution/PackageOverrideResolver.cs index a574a5a90e11..ce9879887f4f 100644 --- a/src/Tasks/Common/ConflictResolution/PackageOverrideResolver.cs +++ b/src/Tasks/Common/ConflictResolution/PackageOverrideResolver.cs @@ -18,20 +18,20 @@ namespace Microsoft.NET.Build.Tasks.ConflictResolution /// internal class PackageOverrideResolver where TConflictItem : class, IConflictItem { - private ITaskItem[] _packageOverrideItems; - private Lazy> _packageOverrides; + private ITaskItem[]? _packageOverrideItems; + private Lazy?> _packageOverrides; - public PackageOverrideResolver(ITaskItem[] packageOverrideItems) + public PackageOverrideResolver(ITaskItem[]? packageOverrideItems) { _packageOverrideItems = packageOverrideItems; - _packageOverrides = new Lazy>(() => BuildPackageOverrides()); + _packageOverrides = new Lazy?>(() => BuildPackageOverrides()); } - public Dictionary PackageOverrides => _packageOverrides.Value; + public Dictionary? PackageOverrides => _packageOverrides.Value; - private Dictionary BuildPackageOverrides() + private Dictionary? BuildPackageOverrides() { - Dictionary result; + Dictionary? result; if (_packageOverrideItems?.Length > 0) { @@ -41,7 +41,7 @@ private Dictionary BuildPackageOverrides() { PackageOverride packageOverride = PackageOverride.Create(packageOverrideItem); - if (result.TryGetValue(packageOverride.PackageName, out PackageOverride existing)) + if (result.TryGetValue(packageOverride.PackageName, out PackageOverride? existing)) { MergePackageOverrides(packageOverride, existing); } @@ -67,7 +67,7 @@ private static void MergePackageOverrides(PackageOverride newPackageOverride, Pa { foreach (KeyValuePair newOverride in newPackageOverride.OverriddenPackages) { - if (existingPackageOverride.OverriddenPackages.TryGetValue(newOverride.Key, out OverrideVersion existingOverrideVersion)) + if (existingPackageOverride.OverriddenPackages.TryGetValue(newOverride.Key, out OverrideVersion? existingOverrideVersion)) { if (existingOverrideVersion < newOverride.Value) { @@ -81,12 +81,12 @@ private static void MergePackageOverrides(PackageOverride newPackageOverride, Pa } } - public TConflictItem Resolve(TConflictItem item1, TConflictItem item2) + public TConflictItem? Resolve(TConflictItem item1, TConflictItem item2) { if (PackageOverrides != null && item1.PackageId != null && item2.PackageId != null) { - PackageOverride packageOverride; - OverrideVersion version; + PackageOverride? packageOverride; + OverrideVersion? version; if (PackageOverrides.TryGetValue(item1.PackageId, out packageOverride) && packageOverride.OverriddenPackages.TryGetValue(item2.PackageId, out version) && item2.PackageVersion != null diff --git a/src/Tasks/Common/ConflictResolution/PackageRank.cs b/src/Tasks/Common/ConflictResolution/PackageRank.cs index 5734fc89ed2e..d2519b522b60 100644 --- a/src/Tasks/Common/ConflictResolution/PackageRank.cs +++ b/src/Tasks/Common/ConflictResolution/PackageRank.cs @@ -7,7 +7,7 @@ class PackageRank { private Dictionary packageRanks; - public PackageRank(string[] packageIds) + public PackageRank(string[]? packageIds) { var numPackages = packageIds?.Length ?? 0; @@ -16,12 +16,12 @@ public PackageRank(string[] packageIds) for (int i = numPackages - 1; i >= 0; i--) { - var preferredPackageId = packageIds[i].Trim(); + var preferredPackageId = packageIds?[i].Trim(); - if (preferredPackageId.Length != 0) + if (preferredPackageId?.Length != 0) { // overwrite any duplicates, lowest rank will win. - packageRanks[preferredPackageId] = i; + packageRanks[preferredPackageId!] = i; } } } @@ -31,7 +31,7 @@ public PackageRank(string[] packageIds) /// /// id of package /// rank of package - public int GetPackageRank(string packageId) + public int GetPackageRank(string? packageId) { int rank; if (packageId != null && packageRanks.TryGetValue(packageId, out rank)) diff --git a/src/Tasks/Common/ConflictResolution/PlatformManifestReader.cs b/src/Tasks/Common/ConflictResolution/PlatformManifestReader.cs index 27b8cc384aad..8076917cd7c3 100644 --- a/src/Tasks/Common/ConflictResolution/PlatformManifestReader.cs +++ b/src/Tasks/Common/ConflictResolution/PlatformManifestReader.cs @@ -28,9 +28,9 @@ public static IEnumerable LoadConflictItems(string manifestPath, L { for (int lineNumber = 0; !manifestReader.EndOfStream; lineNumber++) { - var line = manifestReader.ReadLine().Trim(); + var line = manifestReader.ReadLine()?.Trim(); - if (line.Length == 0 || line[0] == '#') + if (line is null || line.Length == 0 || line[0] == '#') { continue; } @@ -52,7 +52,7 @@ public static IEnumerable LoadConflictItems(string manifestPath, L var assemblyVersionString = lineParts[2].Trim(); var fileVersionString = lineParts[3].Trim(); - Version assemblyVersion = null, fileVersion = null; + Version? assemblyVersion = null, fileVersion = null; if (assemblyVersionString.Length != 0 && !Version.TryParse(assemblyVersionString, out assemblyVersion)) { diff --git a/src/Tasks/Common/ConflictResolution/ResolvePackageFileConflicts.cs b/src/Tasks/Common/ConflictResolution/ResolvePackageFileConflicts.cs index a75fd9dcf2eb..525f2546d82c 100644 --- a/src/Tasks/Common/ConflictResolution/ResolvePackageFileConflicts.cs +++ b/src/Tasks/Common/ConflictResolution/ResolvePackageFileConflicts.cs @@ -8,28 +8,28 @@ namespace Microsoft.NET.Build.Tasks.ConflictResolution { public class ResolvePackageFileConflicts : TaskBase { - private HashSet referenceConflicts = new(); - private HashSet analyzerConflicts = new(); - private HashSet copyLocalConflicts = new(); + private HashSet referenceConflicts = new(); + private HashSet analyzerConflicts = new(); + private HashSet copyLocalConflicts = new(); private HashSet compilePlatformWinners = new(); private HashSet allConflicts = new(); - public ITaskItem[] References { get; set; } + public ITaskItem[]? References { get; set; } - public ITaskItem[] Analyzers { get; set; } + public ITaskItem[]? Analyzers { get; set; } - public ITaskItem[] ReferenceCopyLocalPaths { get; set; } + public ITaskItem[]? ReferenceCopyLocalPaths { get; set; } - public ITaskItem[] OtherRuntimeItems { get; set; } + public ITaskItem[]? OtherRuntimeItems { get; set; } - public ITaskItem[] PlatformManifests { get; set; } + public ITaskItem[]? PlatformManifests { get; set; } - public ITaskItem[] TargetFrameworkDirectories { get; set; } + public ITaskItem[]? TargetFrameworkDirectories { get; set; } /// /// NuGet3 and later only. In the case of a conflict with identical file version information a file from the most preferred package will be chosen. /// - public string[] PreferredPackages { get; set; } + public string[]? PreferredPackages { get; set; } /// /// A collection of items that contain information of which packages get overridden @@ -40,20 +40,20 @@ public class ResolvePackageFileConflicts : TaskBase /// in the default cases where platform packages (Microsoft.NETCore.App) should override specific packages /// (System.Console v4.3.0). /// - public ITaskItem[] PackageOverrides { get; set; } + public ITaskItem[]? PackageOverrides { get; set; } [Output] - public ITaskItem[] ReferencesWithoutConflicts { get; set; } + public ITaskItem[]? ReferencesWithoutConflicts { get; set; } [Output] - public ITaskItem[] AnalyzersWithoutConflicts { get; set; } + public ITaskItem[]? AnalyzersWithoutConflicts { get; set; } [Output] - public ITaskItem[] ReferenceCopyLocalPathsWithoutConflicts { get; set; } + public ITaskItem[]? ReferenceCopyLocalPathsWithoutConflicts { get; set; } [Output] - public ITaskItem[] Conflicts { get; set; } + public ITaskItem[]? Conflicts { get; set; } protected override void ExecuteCore() { @@ -62,7 +62,7 @@ protected override void ExecuteCore() var packageOverrides = new PackageOverrideResolver(PackageOverrides); // Treat assemblies from FrameworkList.xml as platform assemblies that also get considered at compile time - IEnumerable compilePlatformItems = null; + IEnumerable? compilePlatformItems = null; if (TargetFrameworkDirectories != null && TargetFrameworkDirectories.Any()) { var frameworkListReader = new FrameworkListReader(BuildEngine4); @@ -178,14 +178,14 @@ protected override void ExecuteCore() compilePlatformWinners.Select(c => Path.GetFileNameWithoutExtension(c.FileName)) // Don't add a reference if we already have one (especially in case the existing one has // metadata we want to keep, such as aliases) - .Where(simplename => !referenceItemSpecs.Contains(simplename)) + .Where(simpleName => !referenceItemSpecs.Contains(simpleName!)) .Select(r => new TaskItem(r))); } // Concatenate two things, either of which may be null. Interpret null as empty, // and return null if the result would be empty. - private ITaskItem[] SafeConcat(ITaskItem[] first, IEnumerable second) + private ITaskItem[]? SafeConcat(ITaskItem[]? first, IEnumerable second) { if (first == null || first.Length == 0) { @@ -226,7 +226,7 @@ private ITaskItem CreateConflictTaskItem(ConflictItem conflict) return item; } - private IEnumerable GetConflictTaskItems(ITaskItem[] items, ConflictItemType itemType) + private IEnumerable GetConflictTaskItems(ITaskItem[]? items, ConflictItemType itemType) { return (items != null) ? items.Select(i => new ConflictItem(i, itemType)) : Enumerable.Empty(); } @@ -255,7 +255,7 @@ private void HandleRuntimeConflict(ConflictItem winner, ConflictItem loser) { if (loser.ItemType == ConflictItemType.Reference) { - loser.OriginalItem.SetMetadata(MetadataNames.Private, "False"); + loser.OriginalItem?.SetMetadata(MetadataNames.Private, "False"); } else if (loser.ItemType == ConflictItemType.CopyLocal) { @@ -270,14 +270,14 @@ private void HandleRuntimeConflict(ConflictItem winner, ConflictItem loser) /// /// /// - private ITaskItem[] RemoveConflicts(ITaskItem[] original, ICollection conflicts) + private ITaskItem[]? RemoveConflicts(ITaskItem[]? original, ICollection conflicts) { if (conflicts.Count == 0) { return original; } - var result = new ITaskItem[original.Length - conflicts.Count]; + var result = new ITaskItem[original!.Length - conflicts.Count]; int index = 0; foreach (var originalItem in original) diff --git a/src/Tasks/Common/ConflictResolution/ResolvePublishOutputConflicts.cs b/src/Tasks/Common/ConflictResolution/ResolvePublishOutputConflicts.cs index 595f395081b5..b2be50e2bd5f 100644 --- a/src/Tasks/Common/ConflictResolution/ResolvePublishOutputConflicts.cs +++ b/src/Tasks/Common/ConflictResolution/ResolvePublishOutputConflicts.cs @@ -8,20 +8,20 @@ namespace Microsoft.NET.Build.Tasks.ConflictResolution public class ResolveOverlappingItemGroupConflicts : TaskBase { [Required] - public ITaskItem[] ItemGroup1 { get; set; } + public ITaskItem[]? ItemGroup1 { get; set; } [Required] - public ITaskItem[] ItemGroup2 { get; set; } + public ITaskItem[]? ItemGroup2 { get; set; } - public string[] PreferredPackages { get; set; } + public string[]? PreferredPackages { get; set; } - public ITaskItem[] PackageOverrides { get; set; } + public ITaskItem[]? PackageOverrides { get; set; } [Output] - public ITaskItem[] RemovedItemGroup1 { get; set; } + public ITaskItem?[]? RemovedItemGroup1 { get; set; } [Output] - public ITaskItem[] RemovedItemGroup2 { get; set; } + public ITaskItem?[]? RemovedItemGroup2 { get; set; } protected override void ExecuteCore() { @@ -40,12 +40,12 @@ protected override void ExecuteCore() (ConflictItem winner, ConflictItem loser) => { conflicts.Add(loser); }); var conflictItems = conflicts.Select(i => i.OriginalItem); - RemovedItemGroup1 = ItemGroup1.Intersect(conflictItems).ToArray(); - RemovedItemGroup2 = ItemGroup2.Intersect(conflictItems).ToArray(); + RemovedItemGroup1 = ItemGroup1?.Intersect(conflictItems).ToArray(); + RemovedItemGroup2 = ItemGroup2?.Intersect(conflictItems!).ToArray(); } } - private IEnumerable GetConflictTaskItems(ITaskItem[] items, ConflictItemType itemType) + private IEnumerable GetConflictTaskItems(ITaskItem[]? items, ConflictItemType itemType) { return (items != null) ? items.Select(i => new ConflictItem(i, itemType)) : Enumerable.Empty(); } diff --git a/src/Tasks/Common/FileUtilities.MetadataReader.cs b/src/Tasks/Common/FileUtilities.MetadataReader.cs index 84965904162f..c3afe4d6033a 100644 --- a/src/Tasks/Common/FileUtilities.MetadataReader.cs +++ b/src/Tasks/Common/FileUtilities.MetadataReader.cs @@ -22,10 +22,15 @@ namespace Microsoft.NET.Build.Tasks { static partial class FileUtilities { - private static Dictionary s_versionCache = new(StringComparer.OrdinalIgnoreCase /* Not strictly correct on *nix. Fix? */); + private static Dictionary s_versionCache = new(StringComparer.OrdinalIgnoreCase /* Not strictly correct on *nix. Fix? */); - private static Version GetAssemblyVersion(string sourcePath) + private static Version? GetAssemblyVersion(string? sourcePath) { + if (sourcePath == null) + { + return null; + } + DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(sourcePath); if (s_versionCache.TryGetValue(sourcePath, out var cacheEntry) @@ -34,7 +39,7 @@ private static Version GetAssemblyVersion(string sourcePath) return cacheEntry.Version; } - Version version = GetAssemblyVersionFromFile(sourcePath); + Version? version = GetAssemblyVersionFromFile(sourcePath); s_versionCache[sourcePath] = (lastWriteTimeUtc, version); @@ -47,11 +52,11 @@ private static Version GetAssemblyVersion(string sourcePath) return version; - static Version GetAssemblyVersionFromFile(string sourcePath) + static Version? GetAssemblyVersionFromFile(string? sourcePath) { - using (var assemblyStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read)) + using (var assemblyStream = new FileStream(sourcePath!, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read)) { - Version result = null; + Version? result = null; try { using (PEReader peReader = new(assemblyStream, PEStreamOptions.LeaveOpen)) diff --git a/src/Tasks/Common/FileUtilities.cs b/src/Tasks/Common/FileUtilities.cs index 0b967a5d7b31..db3747b48b95 100644 --- a/src/Tasks/Common/FileUtilities.cs +++ b/src/Tasks/Common/FileUtilities.cs @@ -7,7 +7,7 @@ namespace Microsoft.NET.Build.Tasks { static partial class FileUtilities { - public static Version GetFileVersion(string sourcePath) + public static Version? GetFileVersion(string? sourcePath) { if (sourcePath != null) { @@ -22,8 +22,8 @@ public static Version GetFileVersion(string sourcePath) return null; } - static readonly HashSet s_assemblyExtensions = new(new[] { ".dll", ".exe", ".winmd" }, StringComparer.OrdinalIgnoreCase); - public static Version TryGetAssemblyVersion(string sourcePath) + static readonly HashSet s_assemblyExtensions = new(new[] { ".dll", ".exe", ".winmd" }, StringComparer.OrdinalIgnoreCase); + public static Version? TryGetAssemblyVersion(string? sourcePath) { var extension = Path.GetExtension(sourcePath); diff --git a/src/Tasks/Common/ItemUtilities.cs b/src/Tasks/Common/ItemUtilities.cs index ae6698f5381c..52161b9e82c0 100644 --- a/src/Tasks/Common/ItemUtilities.cs +++ b/src/Tasks/Common/ItemUtilities.cs @@ -41,9 +41,9 @@ public static bool HasMetadataValue(this ITaskItem item, string name, string exp /// /// /// - public static string GetReferenceFileName(ITaskItem item) + public static string? GetReferenceFileName(ITaskItem? item) { - var aliases = item.GetMetadata(MetadataNames.Aliases); + var aliases = item?.GetMetadata(MetadataNames.Aliases); if (!string.IsNullOrEmpty(aliases)) { @@ -79,13 +79,13 @@ public static string GetReferenceFileName(ITaskItem item) } } - public static string GetReferenceTargetPath(ITaskItem item) + public static string? GetReferenceTargetPath(ITaskItem? item) { // Determine if the reference will be copied local. // We're only dealing with primary file references. For these RAR will // copy local if Private is true or unset. - var isPrivate = MSBuildUtilities.ConvertStringToBool(item.GetMetadata(MetadataNames.Private), defaultValue: true); + var isPrivate = MSBuildUtilities.ConvertStringToBool(item?.GetMetadata(MetadataNames.Private), defaultValue: true); if (!isPrivate) { @@ -96,42 +96,42 @@ public static string GetReferenceTargetPath(ITaskItem item) return GetTargetPath(item); } - public static string GetReferenceTargetFileName(ITaskItem item) + public static string? GetReferenceTargetFileName(ITaskItem? item) { var targetPath = GetReferenceTargetPath(item); return targetPath != null ? Path.GetFileName(targetPath) : null; } - public static string GetSourcePath(ITaskItem item) + public static string? GetSourcePath(ITaskItem? item) { - var sourcePath = item.GetMetadata(MetadataNames.HintPath)?.Trim(); + var sourcePath = item?.GetMetadata(MetadataNames.HintPath)?.Trim(); if (string.IsNullOrWhiteSpace(sourcePath)) { // assume item-spec points to the file. // this won't work if it comes from a targeting pack or SDK, but // in that case the file won't exist and we'll skip it. - sourcePath = item.ItemSpec; + sourcePath = item?.ItemSpec; } return sourcePath; } static readonly string[] s_targetPathMetadata = new[] { MetadataNames.TargetPath, MetadataNames.DestinationSubPath }; - public static string GetTargetPath(ITaskItem item) + public static string? GetTargetPath(ITaskItem? item) { // first use TargetPath, then DestinationSubPath, then fallback to filename+extension alone // Can't use Path, as this is the path of the file in the package, which is usually not the target path // (for example the target path for lib/netcoreapp2.0/lib.dll is just lib.dll) foreach (var metadata in s_targetPathMetadata) { - var value = item.GetMetadata(metadata)?.Trim(); + var value = item?.GetMetadata(metadata)?.Trim(); if (!string.IsNullOrWhiteSpace(value)) { // normalize path - return value.Replace('\\', '/'); + return value?.Replace('\\', '/'); } } @@ -140,11 +140,11 @@ public static string GetTargetPath(ITaskItem item) var fileName = Path.GetFileName(sourcePath); // Get subdirectory for satellite assemblies / runtime targets - var destinationSubDirectory = item.GetMetadata("DestinationSubDirectory"); + var destinationSubDirectory = item?.GetMetadata("DestinationSubDirectory"); if (!string.IsNullOrWhiteSpace(destinationSubDirectory)) { - return Path.Combine(destinationSubDirectory, fileName); + return Path.Combine(destinationSubDirectory, fileName!); } return fileName; diff --git a/src/Tasks/Common/MSBuildUtilities.cs b/src/Tasks/Common/MSBuildUtilities.cs index d017074cd487..b540c06b0374 100644 --- a/src/Tasks/Common/MSBuildUtilities.cs +++ b/src/Tasks/Common/MSBuildUtilities.cs @@ -4,7 +4,7 @@ namespace Microsoft.NET.Build.Tasks { /// - /// Internal utilties copied from microsoft/MSBuild repo. + /// Internal utilities copied from microsoft/MSBuild repo. /// class MSBuildUtilities { @@ -15,7 +15,7 @@ class MSBuildUtilities /// /// The string to convert. /// Boolean true or false, corresponding to the string. - internal static bool ConvertStringToBool(string parameterValue, bool defaultValue = false) + internal static bool ConvertStringToBool(string? parameterValue, bool defaultValue = false) { if (string.IsNullOrEmpty(parameterValue)) { @@ -40,7 +40,7 @@ internal static bool ConvertStringToBool(string parameterValue, bool defaultValu /// Returns true if the string represents a valid MSBuild boolean true value, /// such as "on", "!false", "yes" /// - private static bool ValidBooleanTrue(string parameterValue) + private static bool ValidBooleanTrue(string? parameterValue) { return ((string.Compare(parameterValue, "true", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(parameterValue, "on", StringComparison.OrdinalIgnoreCase) == 0) || @@ -54,7 +54,7 @@ private static bool ValidBooleanTrue(string parameterValue) /// Returns true if the string represents a valid MSBuild boolean false value, /// such as "!on" "off" "no" "!true" /// - private static bool ValidBooleanFalse(string parameterValue) + private static bool ValidBooleanFalse(string? parameterValue) { return ((string.Compare(parameterValue, "false", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(parameterValue, "off", StringComparison.OrdinalIgnoreCase) == 0) || diff --git a/src/Tasks/Common/MessageBase.cs b/src/Tasks/Common/MessageBase.cs index 31e0ecd94dcc..891ebba6b5d5 100644 --- a/src/Tasks/Common/MessageBase.cs +++ b/src/Tasks/Common/MessageBase.cs @@ -13,17 +13,17 @@ public abstract class MessageBase : TaskBase /// /// Formatted text for the message /// - public string FormattedText { get; set; } + public string? FormattedText { get; set; } /// /// The name of the resource in Strings.resx that contains the desired error message. /// - public string ResourceName { get; set; } + public string? ResourceName { get; set; } /// /// The arguments provided to along with the retrieved resource as the format. /// - public string[] FormatArguments { get; set; } + public string[]? FormatArguments { get; set; } private static readonly string[] EmptyArguments = new[] { "" }; @@ -33,7 +33,7 @@ internal MessageBase() protected override void ExecuteCore() { - string message = null; + string? message; if (string.IsNullOrEmpty(FormattedText) && string.IsNullOrEmpty(ResourceName)) { throw new ArgumentException($"Either {nameof(FormattedText)} or {nameof(ResourceName)} must be specified."); @@ -53,16 +53,15 @@ protected override void ExecuteCore() FormatArguments = EmptyArguments; } - string format = Strings.ResourceManager.GetString(ResourceName, Strings.Culture); - message = string.Format(CultureInfo.CurrentCulture, format, FormatArguments); + string? format = Strings.ResourceManager.GetString(ResourceName, Strings.Culture); + message = string.Format(CultureInfo.CurrentCulture, format!, FormatArguments); } else { message = FormattedText; } - - LogMessage(message); + LogMessage(message!); } protected abstract void LogMessage(string message); diff --git a/src/Tasks/Common/NuGetUtils.cs b/src/Tasks/Common/NuGetUtils.cs index d6a92ab3932d..5bfb398eedb8 100644 --- a/src/Tasks/Common/NuGetUtils.cs +++ b/src/Tasks/Common/NuGetUtils.cs @@ -10,10 +10,10 @@ internal static partial class NuGetUtils /// /// /// - public static string GetPackageIdFromSourcePath(string sourcePath) + public static string? GetPackageIdFromSourcePath(string sourcePath) { - string packageId, unused; - GetPackageParts(sourcePath, out packageId, out unused); + string? packageId; + GetPackageParts(sourcePath, out packageId, out _); return packageId; } @@ -23,7 +23,7 @@ public static string GetPackageIdFromSourcePath(string sourcePath) /// full path to package file /// package ID /// subpath of asset within package - public static void GetPackageParts(string fullPath, out string packageId, out string packageSubPath) + public static void GetPackageParts(string fullPath, out string? packageId, out string? packageSubPath) { packageId = null; packageSubPath = null; @@ -54,7 +54,6 @@ public static void GetPackageParts(string fullPath, out string packageId, out st { } return; - } } } diff --git a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/AddFacadesToReferences.cs b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/AddFacadesToReferences.cs index fd880023a4bf..c61b73824e40 100644 --- a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/AddFacadesToReferences.cs +++ b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/AddFacadesToReferences.cs @@ -9,18 +9,18 @@ namespace Microsoft.NET.Build.Tasks public class AddFacadesToReferences : TaskBase { [Required] - public ITaskItem[] References { get; set; } + public ITaskItem[]? References { get; set; } [Required] - public ITaskItem[] Facades { get; set; } + public ITaskItem[]? Facades { get; set; } [Output] - public ITaskItem[] UpdatedReferences { get; set; } + public ITaskItem[]? UpdatedReferences { get; set; } protected override void ExecuteCore() { Dictionary facadeDict = new(StringComparer.OrdinalIgnoreCase); - foreach (var facade in Facades) + foreach (var facade in Facades ?? Array.Empty()) { string filename = facade.GetMetadata("FileName"); TaskItem facadeWithMetadata = new(filename); @@ -31,7 +31,7 @@ protected override void ExecuteCore() List updatedReferences = new(); - foreach (var reference in References) + foreach (var reference in References ?? Array.Empty()) { string filename = reference.ItemSpec; if (!facadeDict.ContainsKey(filename)) @@ -52,7 +52,7 @@ protected override void ExecuteCore() } } - foreach (var facade in Facades) + foreach (var facade in Facades ?? Array.Empty()) { string filename = facade.GetMetadata("FileName"); updatedReferences.Add(facadeDict[filename]); diff --git a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/FileUtilities.net45.cs b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/FileUtilities.net45.cs index 8d325419f788..2e53e1004024 100644 --- a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/FileUtilities.net45.cs +++ b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/FileUtilities.net45.cs @@ -10,7 +10,7 @@ namespace Microsoft.NET.Build.Tasks { static partial class FileUtilities { - private static Version GetAssemblyVersion(string sourcePath) + private static Version? GetAssemblyVersion(string? sourcePath) { try { diff --git a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/GetDependsOnNETStandard.cs b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/GetDependsOnNETStandard.cs index b0a22e66bb0d..8b4fa07c9db4 100644 --- a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/GetDependsOnNETStandard.cs +++ b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/GetDependsOnNETStandard.cs @@ -24,7 +24,7 @@ public partial class GetDependsOnNETStandard : TaskBase /// Set of reference items to analyze. /// [Required] - public ITaskItem[] References { get; set; } + public ITaskItem[]? References { get; set; } /// /// True if any of the references depend on netstandard.dll @@ -39,7 +39,7 @@ protected override void ExecuteCore() private bool AnyReferenceDependsOnNETStandard() { - foreach (var reference in References) + foreach (var reference in References ?? Array.Empty()) { var referenceSourcePath = ItemUtilities.GetSourcePath(reference); diff --git a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/GetDependsOnNETStandard.net46.cs b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/GetDependsOnNETStandard.net46.cs index d030ddf4be2c..f5dac67268f4 100644 --- a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/GetDependsOnNETStandard.net46.cs +++ b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/GetDependsOnNETStandard.net46.cs @@ -178,7 +178,7 @@ internal interface IMetaDataDispenser internal interface IMetaDataAssemblyImport { void GetAssemblyProps(uint mdAsm, out IntPtr pPublicKeyPtr, out uint ucbPublicKeyPtr, out uint uHashAlg, StringBuilder strName, uint cchNameIn, out uint cchNameRequired, IntPtr amdInfo, out uint dwFlags); - void GetAssemblyRefProps(uint mdAsmRef, out IntPtr ppbPublicKeyOrToken, out uint pcbPublicKeyOrToken, StringBuilder strName, uint cchNameIn, out uint pchNameOut, ref ASSEMBLYMETADATA amdInfo, out IntPtr ppbHashValue, out uint pcbHashValue, out uint pdwAssemblyRefFlags); + void GetAssemblyRefProps(uint mdAsmRef, out IntPtr ppbPublicKeyOrToken, out uint pcbPublicKeyOrToken, StringBuilder? strName, uint cchNameIn, out uint pchNameOut, ref ASSEMBLYMETADATA amdInfo, out IntPtr ppbHashValue, out uint pcbHashValue, out uint pdwAssemblyRefFlags); void GetFileProps([In] uint mdFile, StringBuilder strName, uint cchName, out uint cchNameRequired, out IntPtr bHashData, out uint cchHashBytes, out uint dwFileFlags); void GetExportedTypeProps(); void GetManifestResourceProps(); diff --git a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj index 315a95696ae8..3f80c7a02250 100644 --- a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj +++ b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj @@ -7,6 +7,7 @@ Microsoft.NET.Build.Extensions $(Configuration)\Sdks\$(PackageId)\msbuildExtensions\Microsoft\Microsoft.NET.Build.Extensions\tools + enable From 6cee4007920af4959589f7a4d261d23e6c5eb6b0 Mon Sep 17 00:00:00 2001 From: Michael Yanni Date: Tue, 2 Apr 2024 12:19:45 -0700 Subject: [PATCH 5/7] Had to set #nullable enable in the PublicAPI files. https://github.com/dotnet/roslyn-analyzers/blob/main/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md#nullable-reference-type-support Converted Microsoft.DotNet.Configurer.csproj to nullable. Realized the other projects that need nullable are massive, so putting this on the backburner. --- .../TelemetryEventEntry.cs | 18 +++++++++--------- .../CliFolderPathCalculator.cs | 2 +- .../DotnetFirstTimeUseConfigurer.cs | 4 ++-- .../FileSentinel.cs | 2 +- .../Microsoft.DotNet.Configurer.csproj | 1 + src/Cli/dotnet/dotnet.csproj | 1 + .../LocalDaemons/DockerCli.cs | 6 +----- .../PublicAPI/net472/PublicAPI.Shipped.txt | 2 +- .../PublicAPI/net9.0/PublicAPI.Shipped.txt | 2 +- .../Tool/Microsoft.NET.Sdk.Razor.Tool.csproj | 3 ++- .../Microsoft.NET.TestFramework.csproj | 1 + 11 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/TelemetryEventEntry.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/TelemetryEventEntry.cs index 033112bc996f..01d92e392303 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/TelemetryEventEntry.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/TelemetryEventEntry.cs @@ -12,7 +12,7 @@ public static class TelemetryEventEntry public static void TrackEvent( string? eventName = null, - IDictionary? properties = null, + IDictionary? properties = null, IDictionary? measurements = null) { EntryPosted?.Invoke(typeof(TelemetryEventEntry), @@ -32,7 +32,7 @@ public static void SendFiltered(object? o = null) } } - public static void Subscribe(Action?, IDictionary?> subscriber) + public static void Subscribe(Action?, IDictionary?> subscriber) { void Handler(object? sender, InstrumentationEventArgs eventArgs) { @@ -49,7 +49,7 @@ public sealed class PerformanceMeasurement : IDisposable private readonly Dictionary? _data; private readonly string? _name; - public PerformanceMeasurement(Dictionary data, string name) + public PerformanceMeasurement(Dictionary? data, string name) { // Measurement is a no-op if we don't have a dictionary to store the entry. if (data == null) @@ -77,7 +77,7 @@ public class InstrumentationEventArgs : EventArgs { internal InstrumentationEventArgs( string? eventName, - IDictionary? properties, + IDictionary? properties, IDictionary? measurements) { EventName = eventName; @@ -86,7 +86,7 @@ internal InstrumentationEventArgs( } public string? EventName { get; } - public IDictionary? Properties { get; } + public IDictionary? Properties { get; } public IDictionary? Measurements { get; } } @@ -94,7 +94,7 @@ public class ApplicationInsightsEntryFormat { public ApplicationInsightsEntryFormat( string? eventName = null, - IDictionary? properties = null, + IDictionary? properties = null, IDictionary? measurements = null) { EventName = eventName; @@ -103,12 +103,12 @@ public ApplicationInsightsEntryFormat( } public string? EventName { get; } - public IDictionary? Properties { get; } + public IDictionary? Properties { get; } public IDictionary? Measurements { get; } - public ApplicationInsightsEntryFormat WithAppliedToPropertiesValue(Func func) + public ApplicationInsightsEntryFormat WithAppliedToPropertiesValue(Func func) { - var appliedProperties = Properties?.ToDictionary(p => p.Key, p => func(p.Value)); + var appliedProperties = Properties?.ToDictionary(p => p.Key, p => (string?)func(p.Value)); return new ApplicationInsightsEntryFormat(EventName, appliedProperties, Measurements); } } diff --git a/src/Cli/Microsoft.DotNet.Configurer/CliFolderPathCalculator.cs b/src/Cli/Microsoft.DotNet.Configurer/CliFolderPathCalculator.cs index 40ddbc9f0131..19a72ee8e9a3 100644 --- a/src/Cli/Microsoft.DotNet.Configurer/CliFolderPathCalculator.cs +++ b/src/Cli/Microsoft.DotNet.Configurer/CliFolderPathCalculator.cs @@ -15,7 +15,7 @@ public static class CliFolderPathCalculator public static string CliFallbackFolderPath => Environment.GetEnvironmentVariable("DOTNET_CLI_TEST_FALLBACKFOLDER") ?? - Path.Combine(new DirectoryInfo(AppContext.BaseDirectory).Parent.FullName, "NuGetFallbackFolder"); + Path.Combine(new DirectoryInfo(AppContext.BaseDirectory).Parent!.FullName, "NuGetFallbackFolder"); public static string ToolsShimPath => Path.Combine(DotnetUserProfileFolderPath, ToolsShimFolderName); diff --git a/src/Cli/Microsoft.DotNet.Configurer/DotnetFirstTimeUseConfigurer.cs b/src/Cli/Microsoft.DotNet.Configurer/DotnetFirstTimeUseConfigurer.cs index 6fabd4d080eb..87d8d66a50af 100644 --- a/src/Cli/Microsoft.DotNet.Configurer/DotnetFirstTimeUseConfigurer.cs +++ b/src/Cli/Microsoft.DotNet.Configurer/DotnetFirstTimeUseConfigurer.cs @@ -15,7 +15,7 @@ public class DotnetFirstTimeUseConfigurer private readonly IAspNetCoreCertificateGenerator _aspNetCoreCertificateGenerator; private readonly IFileSentinel _toolPathSentinel; private readonly IEnvironmentPath _pathAdder; - private readonly Dictionary _performanceMeasurements; + private readonly Dictionary? _performanceMeasurements; public DotnetFirstTimeUseConfigurer( IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel, @@ -25,7 +25,7 @@ public DotnetFirstTimeUseConfigurer( DotnetFirstRunConfiguration dotnetFirstRunConfiguration, IReporter reporter, IEnvironmentPath pathAdder, - Dictionary performanceMeasurements = null) + Dictionary? performanceMeasurements = null) { _firstTimeUseNoticeSentinel = firstTimeUseNoticeSentinel; _aspNetCertificateSentinel = aspNetCertificateSentinel; diff --git a/src/Cli/Microsoft.DotNet.Configurer/FileSentinel.cs b/src/Cli/Microsoft.DotNet.Configurer/FileSentinel.cs index 90424de7ad52..a09a862de266 100644 --- a/src/Cli/Microsoft.DotNet.Configurer/FileSentinel.cs +++ b/src/Cli/Microsoft.DotNet.Configurer/FileSentinel.cs @@ -15,7 +15,7 @@ public FileSentinel(FilePath file) : { } - internal FileSentinel(FilePath file, IFileSystem fileSystem) + internal FileSentinel(FilePath file, IFileSystem? fileSystem) { _file = file; _fileSystem = fileSystem ?? FileSystemWrapper.Default; diff --git a/src/Cli/Microsoft.DotNet.Configurer/Microsoft.DotNet.Configurer.csproj b/src/Cli/Microsoft.DotNet.Configurer/Microsoft.DotNet.Configurer.csproj index eadc99c85f94..bf3ffccbcb81 100644 --- a/src/Cli/Microsoft.DotNet.Configurer/Microsoft.DotNet.Configurer.csproj +++ b/src/Cli/Microsoft.DotNet.Configurer/Microsoft.DotNet.Configurer.csproj @@ -9,6 +9,7 @@ git $(DefineConstants);EXCLUDE_ASPNETCORE true + enable diff --git a/src/Cli/dotnet/dotnet.csproj b/src/Cli/dotnet/dotnet.csproj index 7edf6bb03da3..1027445d16bd 100644 --- a/src/Cli/dotnet/dotnet.csproj +++ b/src/Cli/dotnet/dotnet.csproj @@ -13,6 +13,7 @@ false true true + diff --git a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/DockerCli.cs b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/DockerCli.cs index b7b0733ad52a..cfa143ba1b73 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/DockerCli.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/DockerCli.cs @@ -185,7 +185,6 @@ internal static JsonDocument GetDockerConfig() dockerCommand.CaptureStdErr(); CommandResult dockerCommandResult = dockerCommand.Execute(); - if (dockerCommandResult.ExitCode != 0) { throw new DockerLoadException(Resource.FormatString( @@ -195,9 +194,7 @@ internal static JsonDocument GetDockerConfig() dockerCommandResult.StdErr)); } - return JsonDocument.Parse(dockerCommandResult.StdOut); - - + return JsonDocument.Parse(dockerCommandResult.StdOut!); } catch (Exception e) when (e is not DockerLoadException) { @@ -212,7 +209,6 @@ public static async Task WriteImageToStreamAsync(BuiltImage image, SourceImageRe cancellationToken.ThrowIfCancellationRequested(); using TarWriter writer = new(imageStream, TarEntryFormat.Pax, leaveOpen: true); - // Feed each layer tarball into the stream JsonArray layerTarballPaths = new(); diff --git a/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net472/PublicAPI.Shipped.txt b/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net472/PublicAPI.Shipped.txt index 5f282702bb03..ab058de62d44 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net472/PublicAPI.Shipped.txt +++ b/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net472/PublicAPI.Shipped.txt @@ -1 +1 @@ - \ No newline at end of file +#nullable enable diff --git a/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net9.0/PublicAPI.Shipped.txt b/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net9.0/PublicAPI.Shipped.txt index 5f282702bb03..ab058de62d44 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net9.0/PublicAPI.Shipped.txt +++ b/src/Containers/Microsoft.NET.Build.Containers/PublicAPI/net9.0/PublicAPI.Shipped.txt @@ -1 +1 @@ - \ No newline at end of file +#nullable enable diff --git a/src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj b/src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj index 19fb2f2610d7..b014fa49c9ed 100644 --- a/src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj +++ b/src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj @@ -1,4 +1,4 @@ - + Razor is a markup syntax for adding server-side logic to web pages. This assembly contains infrastructure supporting Razor MSBuild integration. @@ -14,6 +14,7 @@ false + diff --git a/test/Microsoft.NET.TestFramework/Microsoft.NET.TestFramework.csproj b/test/Microsoft.NET.TestFramework/Microsoft.NET.TestFramework.csproj index f41fc0d4c6df..24b75b30e62a 100644 --- a/test/Microsoft.NET.TestFramework/Microsoft.NET.TestFramework.csproj +++ b/test/Microsoft.NET.TestFramework/Microsoft.NET.TestFramework.csproj @@ -4,6 +4,7 @@ false + From 2a5ca26fb55a5f7f495e122c098fd2fc814308e0 Mon Sep 17 00:00:00 2001 From: Michael Yanni Date: Mon, 18 Nov 2024 13:50:54 -0800 Subject: [PATCH 6/7] Added #nullable enable to certain shared files to get the build working. --- .../BuiltInCommand.cs | 2 +- src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs | 6 +- .../Microsoft.DotNet.Cli.Utils/ICommand.cs | 2 +- .../Microsoft.DotNet.Cli.Utils/PathUtility.cs | 2 +- .../dotnet/commands/dotnet-run/RunCommand.cs | 2 +- src/Common/CliFolderPathCalculatorCore.cs | 4 + src/Common/EnvironmentVariableNames.cs | 4 + src/Common/WorkloadFileBasedInstall.cs | 7 +- src/Common/WorkloadSetVersion.cs | 4 + .../FXVersion.cs | 6 +- .../CachingWorkloadResolver.cs | 4 + ....NET.Sdk.WorkloadMSBuildSdkResolver.csproj | 1 - .../WorkloadSdkResolver.cs | 7 +- .../IWorkloadManifestProvider.cs | 4 + .../IWorkloadResolver.cs | 4 + .../ManifestId.cs | 4 + .../ManifestVersion.cs | 4 + .../ManifestVersionUpdate.cs | 4 + ...soft.NET.Sdk.WorkloadManifestReader.csproj | 1 - .../ReadableWorkloadManifest.cs | 4 + ...rkloadManifestProvider.GlobalJsonReader.cs | 3 + ...toryWorkloadManifestProvider.JsonReader.cs | 3 + .../SdkDirectoryWorkloadManifestProvider.cs | 6 +- .../SdkFeatureBand.cs | 4 + .../TempDirectoryWorkloadManifestProvider.cs | 4 + .../WorkloadDefinition.cs | 4 + .../WorkloadId.cs | 4 + .../WorkloadInstallType.cs | 4 +- .../WorkloadManifest.cs | 4 + .../WorkloadManifestFormatException.cs | 4 + .../WorkloadManifestReader.Localization.cs | 4 + .../WorkloadManifestReader.SystemTextJson.cs | 4 + .../WorkloadManifestReader.cs | 4 + .../WorkloadPack.cs | 4 + .../WorkloadPackId.cs | 4 + .../WorkloadResolver.cs | 4 + .../WorkloadRootPath.cs | 4 + .../WorkloadSet.cs | 6 +- .../WorkloadSuggestionFinder.cs | 6 +- .../GivenAAllowEmptyTelemetry.cs | 4 + .../Tasks/Tasks/Http/HttpClientExtensions.cs | 46 ++++++----- .../Http/HttpResponseMessageForStatusCode.cs | 4 +- .../Tasks/Http/HttpResponseMessageWrapper.cs | 10 +-- .../Publish/Tasks/Tasks/Http/IHttpResponse.cs | 2 +- .../Tasks/Tasks/MsDeploy/VsMsdeploy.cs | 11 ++- .../Tasks/OneDeploy/CreatePackageFile.cs | 10 +-- .../Tasks/OneDeploy/DeploymentResponse.cs | 21 +++-- .../OneDeploy/IDeploymentStatusService.cs | 2 +- .../Tasks/Tasks/OneDeploy/OneDeploy.WebJob.cs | 18 ++--- .../Tasks/Tasks/OneDeploy/OneDeploy.cs | 78 +++++++++---------- .../Tasks/OneDeploy/OneDeployStatusService.cs | 16 ++-- .../Tasks/Tasks/ZipDeploy/ZipDeploy.cs | 6 +- .../Tasks/ZipDeploy/ZipDeploymentStatus.cs | 12 +-- .../Mapping/AssemblyMapperTests.cs | 2 +- .../Mapping/AssemblySetMapperTests.cs | 2 +- .../Mapping/NamespaceMapperTests.cs | 2 +- .../Mapping/TypeMapperTests.cs | 4 +- .../EndToEndTests.cs | 5 +- .../ManifestTests.cs | 4 +- .../InMemoryLoggerProvider.cs | 4 + .../TestLoggerFactory.cs | 4 + .../Utilities/BufferedReporter.cs | 4 + .../XunitLoggerProvider.cs | 4 + .../DotnetNewDetailsTest.Approval.cs | 4 +- .../dotnet-new.Tests/DotnetNewInstallTests.cs | 6 +- test/dotnet-new.Tests/DotnetNewSearchTests.cs | 4 +- .../NuGetSignatureVerificationEnablerTests.cs | 4 + .../dotnet-new/DotnetAddPostActionTests.cs | 4 + .../DotnetRestorePostActionTests.cs | 4 + .../dotnet-new/DotnetSlnPostActionTests.cs | 4 + .../dotnet-new/SdkInfoProviderTests.cs | 4 + 71 files changed, 313 insertions(+), 152 deletions(-) diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs index 1f3eba55f381..6d78579048ca 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs @@ -163,7 +163,7 @@ public ICommand CaptureStdOut() return this; } - public ICommand EnvironmentVariable(string name, string value) + public ICommand EnvironmentVariable(string name, string? value) { throw new NotImplementedException(); } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs index da623090feb3..17e4d868a679 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs @@ -18,7 +18,7 @@ public class Command : ICommand private bool _trimTrailingNewlines = false; - public Command(Process process, bool trimtrailingNewlines = false) + public Command(Process? process, bool trimtrailingNewlines = false) { _trimTrailingNewlines = trimtrailingNewlines; _process = process ?? throw new ArgumentNullException(nameof(process)); @@ -28,7 +28,7 @@ public CommandResult Execute() { return Execute(null); } - public CommandResult Execute(Action processStarted) + public CommandResult Execute(Action? processStarted) { Reporter.Verbose.WriteLine(string.Format( LocalizableStrings.RunningFileNameArguments, @@ -98,7 +98,7 @@ public ICommand WorkingDirectory(string projectDirectory) return this; } - public ICommand EnvironmentVariable(string name, string value) + public ICommand EnvironmentVariable(string name, string? value) { _process.StartInfo.Environment[name] = value; return this; diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs index 8c6af48001e9..e7fe553a8757 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs @@ -9,7 +9,7 @@ public interface ICommand ICommand WorkingDirectory(string projectDirectory); - ICommand EnvironmentVariable(string name, string value); + ICommand EnvironmentVariable(string name, string? value); ICommand CaptureStdOut(); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/PathUtility.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/PathUtility.cs index f0778699153f..88a30207abc2 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/PathUtility.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/PathUtility.cs @@ -112,7 +112,7 @@ public static bool DeleteFileAndEmptyParents(string path, int maxDirectoriesToDe int directoriesDeleted = 0; - while (!Directory.EnumerateFileSystemEntries(dir).Any() && + while (dir is not null && !Directory.EnumerateFileSystemEntries(dir).Any() && directoriesDeleted < maxDirectoriesToDelete) { Directory.Delete(dir); diff --git a/src/Cli/dotnet/commands/dotnet-run/RunCommand.cs b/src/Cli/dotnet/commands/dotnet-run/RunCommand.cs index 56e10007691a..e22a4d510e9c 100644 --- a/src/Cli/dotnet/commands/dotnet-run/RunCommand.cs +++ b/src/Cli/dotnet/commands/dotnet-run/RunCommand.cs @@ -317,7 +317,7 @@ static ICommand CreateCommandFromRunProperties(ProjectInstance project, RunPrope CommandSpec commandSpec = new(runProperties.RunCommand, runProperties.RunArguments); var command = CommandFactoryUsingResolver.Create(commandSpec) - .WorkingDirectory(runProperties.RunWorkingDirectory); + .WorkingDirectory(runProperties.RunWorkingDirectory ?? string.Empty); var rootVariableName = EnvironmentVariableNames.TryGetDotNetRootVariableName( project.GetPropertyValue("RuntimeIdentifier"), diff --git a/src/Common/CliFolderPathCalculatorCore.cs b/src/Common/CliFolderPathCalculatorCore.cs index fad9b944281d..44cfb9182b8b 100644 --- a/src/Common/CliFolderPathCalculatorCore.cs +++ b/src/Common/CliFolderPathCalculatorCore.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.DotNet.Configurer { static class CliFolderPathCalculatorCore diff --git a/src/Common/EnvironmentVariableNames.cs b/src/Common/EnvironmentVariableNames.cs index 07a19c1fdc8a..ddf0071528a4 100644 --- a/src/Common/EnvironmentVariableNames.cs +++ b/src/Common/EnvironmentVariableNames.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.DotNet.Cli { static class EnvironmentVariableNames diff --git a/src/Common/WorkloadFileBasedInstall.cs b/src/Common/WorkloadFileBasedInstall.cs index fd4ada305022..7e1ff235f383 100644 --- a/src/Common/WorkloadFileBasedInstall.cs +++ b/src/Common/WorkloadFileBasedInstall.cs @@ -1,5 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. + +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using System.Text.Json; #if DotnetCsproj using Microsoft.DotNet.Workloads.Workload.History; @@ -57,7 +62,7 @@ public static IEnumerable GetWorkloadHistoryRecords(strin try { var historyRecord = JsonSerializer.Deserialize(File.ReadAllText(file)); - historyRecords.Add(historyRecord); + historyRecords.Add(historyRecord!); } catch (JsonException) { diff --git a/src/Common/WorkloadSetVersion.cs b/src/Common/WorkloadSetVersion.cs index 2057b0620af7..0fa5fb6756a7 100644 --- a/src/Common/WorkloadSetVersion.cs +++ b/src/Common/WorkloadSetVersion.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.Deployment.DotNet.Releases; using Microsoft.NET.Sdk.WorkloadManifestReader; diff --git a/src/Resolvers/Microsoft.DotNet.MSBuildSdkResolver/FXVersion.cs b/src/Resolvers/Microsoft.DotNet.MSBuildSdkResolver/FXVersion.cs index c1b76e8ed3d4..50b000d4cf94 100644 --- a/src/Resolvers/Microsoft.DotNet.MSBuildSdkResolver/FXVersion.cs +++ b/src/Resolvers/Microsoft.DotNet.MSBuildSdkResolver/FXVersion.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.DotNet.MSBuildSdkResolver { // Note: This is SemVer 2.0.0 https://semver.org/spec/v2.0.0.html @@ -57,7 +61,7 @@ public static int Compare(FXVersion s1, FXVersion s2) // First character of pre is '-' when it is not empty - // First idenitifier starts at position 1 + // First identifier starts at position 1 int idStart = 1; for (int i = idStart; true; ++i) { diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs index 2bcb8b7342cb..62eb34e16938 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/CachingWorkloadResolver.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.Build.Framework; using Microsoft.NET.Sdk.WorkloadManifestReader; using System.Collections.Immutable; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.csproj b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.csproj index f0d1305091c2..d713f088b96c 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.csproj +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.csproj @@ -3,7 +3,6 @@ $(ResolverTargetFramework) true - enable diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/WorkloadSdkResolver.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/WorkloadSdkResolver.cs index 6230bf03f208..846b28d67dd1 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/WorkloadSdkResolver.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver/WorkloadSdkResolver.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.Build.Framework; using Microsoft.NET.Sdk.WorkloadManifestReader; using Microsoft.DotNet.Configurer; @@ -13,7 +17,6 @@ namespace Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver { - // This SdkResolver is used by the .NET SDK version of MSBuild. Workload resolution logic which // is shared with Full Framework / Visual Studio MSBuild is in CachingWorkloadResolver. public class WorkloadSdkResolver : SdkResolver @@ -41,7 +44,6 @@ private class CachedState cachedState = resolverContextState; } - if (cachedState == null) { var dotnetRootPath = GetDotNetRoot(resolverContext); @@ -82,7 +84,6 @@ private class CachedState return sdkResolutionResult.ResolvedSdkDirectory; #endif - } private string? GetDotNetRoot(SdkResolverContext context) diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/IWorkloadManifestProvider.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/IWorkloadManifestProvider.cs index 4dc7392e9d14..5bf8af64192e 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/IWorkloadManifestProvider.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/IWorkloadManifestProvider.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { /// diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/IWorkloadResolver.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/IWorkloadResolver.cs index 9caf5257f4a9..a7448bf6d994 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/IWorkloadResolver.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/IWorkloadResolver.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { public interface IWorkloadResolver diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestId.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestId.cs index 5834645d424c..01a8ae7b7f8c 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestId.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestId.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { public struct ManifestId : IEquatable, IComparable diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestVersion.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestVersion.cs index 5f2d3ded59a6..c622dab22307 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestVersion.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestVersion.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.DotNet.MSBuildSdkResolver; using Strings = Microsoft.NET.Sdk.Localization.Strings; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestVersionUpdate.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestVersionUpdate.cs index 07119281d9a4..4b80e6d5f4ed 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestVersionUpdate.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ManifestVersionUpdate.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { // TODO: Do we need this class, or the existing version information anymore now that workload manifest are side by side? diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/Microsoft.NET.Sdk.WorkloadManifestReader.csproj b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/Microsoft.NET.Sdk.WorkloadManifestReader.csproj index 77cd7cdef063..c9771ab10f0a 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/Microsoft.NET.Sdk.WorkloadManifestReader.csproj +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/Microsoft.NET.Sdk.WorkloadManifestReader.csproj @@ -3,7 +3,6 @@ $(ResolverTargetFramework);net472 MicrosoftAspNetCore - enable true diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ReadableWorkloadManifest.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ReadableWorkloadManifest.cs index c255212768cc..e13148faed03 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ReadableWorkloadManifest.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/ReadableWorkloadManifest.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { public class ReadableWorkloadManifest diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.GlobalJsonReader.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.GlobalJsonReader.cs index 4fa2878d5b43..8036508908ff 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.GlobalJsonReader.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.GlobalJsonReader.cs @@ -1,6 +1,9 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 using Microsoft.NET.Sdk.Localization; using static Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadManifestReader; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.JsonReader.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.JsonReader.cs index b1198f9fa0e7..768b82534dad 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.JsonReader.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.JsonReader.cs @@ -1,6 +1,9 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 using Microsoft.NET.Sdk.Localization; using static Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadManifestReader; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.cs index d66321466e19..6b01743d9fcb 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkDirectoryWorkloadManifestProvider.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using System.Security.Cryptography; using Microsoft.Deployment.DotNet.Releases; using Microsoft.DotNet.Cli; @@ -15,7 +19,7 @@ public partial class SdkDirectoryWorkloadManifestProvider : IWorkloadManifestPro public const string WorkloadSetsFolderName = "workloadsets"; private readonly string? _sdkRootPath; - private readonly string _sdkOrUserLocalPath; + private readonly string? _sdkOrUserLocalPath; private readonly SdkFeatureBand _sdkVersionBand; private readonly string[] _manifestRoots; private static HashSet _outdatedManifestIds = new(StringComparer.OrdinalIgnoreCase) { "microsoft.net.workload.android", "microsoft.net.workload.blazorwebassembly", "microsoft.net.workload.ios", diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkFeatureBand.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkFeatureBand.cs index 336f5d0f1a42..ee65dbf09aba 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkFeatureBand.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/SdkFeatureBand.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.Deployment.DotNet.Releases; namespace Microsoft.NET.Sdk.WorkloadManifestReader diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/TempDirectoryWorkloadManifestProvider.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/TempDirectoryWorkloadManifestProvider.cs index 8aee9c940b02..770ec194704a 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/TempDirectoryWorkloadManifestProvider.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/TempDirectoryWorkloadManifestProvider.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { public class TempDirectoryWorkloadManifestProvider : IWorkloadManifestProvider diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadDefinition.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadDefinition.cs index 797ead52e489..a3eb30493950 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadDefinition.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadDefinition.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { public abstract class BaseWorkloadDefinition diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadId.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadId.cs index c6adcff13fbc..754853428655 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadId.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadId.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { /// diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadInstallType.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadInstallType.cs index 5de761d0eb73..e2654bb7a4b8 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadInstallType.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadInstallType.cs @@ -1,7 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Reflection; +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 namespace Microsoft.NET.Sdk.WorkloadManifestReader { diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifest.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifest.cs index 80f2ad7f662b..790f46e6cf8f 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifest.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifest.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.DotNet.MSBuildSdkResolver; namespace Microsoft.NET.Sdk.WorkloadManifestReader diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestFormatException.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestFormatException.cs index e63e7812a7a5..148103fd0970 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestFormatException.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestFormatException.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { class WorkloadManifestFormatException : WorkloadManifestException diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.Localization.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.Localization.cs index 340ef241a301..49d38d2d3557 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.Localization.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.Localization.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using System.Globalization; using System.Runtime.CompilerServices; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.SystemTextJson.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.SystemTextJson.cs index f27bef172ad3..97c0d5f00757 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.SystemTextJson.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.SystemTextJson.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using System.Buffers; using System.Text.Json; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.cs index 6b66ef9167d1..ffeff031e3bd 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadManifestReader.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.NET.Sdk.Localization; using FXVersion = Microsoft.DotNet.MSBuildSdkResolver.FXVersion; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadPack.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadPack.cs index 0cdd8022bf8d..a2ae5610a1fa 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadPack.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadPack.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { public class WorkloadPack diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadPackId.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadPackId.cs index cb09d54def75..19ef5341a633 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadPackId.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadPackId.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using System.Text.Json; using System.Text.Json.Serialization; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadResolver.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadResolver.cs index ec7586a44464..b609d3b67a67 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadResolver.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadResolver.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.DotNet.Cli; using Microsoft.DotNet.Workloads.Workload; using Microsoft.NET.Sdk.Localization; diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadRootPath.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadRootPath.cs index 24d9ab70c4bc..ed25df6f4595 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadRootPath.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadRootPath.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { public record WorkloadRootPath(string? Path, bool Installable); diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadSet.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadSet.cs index 4f30dd17dd8e..b351a644046e 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadSet.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadSet.cs @@ -1,12 +1,14 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -// + +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 using Microsoft.DotNet.MSBuildSdkResolver; using Strings = Microsoft.NET.Sdk.Localization.Strings; using System.Text.Json; -using Microsoft.DotNet.Workloads.Workload; namespace Microsoft.NET.Sdk.WorkloadManifestReader { diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadSuggestionFinder.cs b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadSuggestionFinder.cs index 85ed48aacda5..e0adea34610c 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadSuggestionFinder.cs +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/WorkloadSuggestionFinder.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + namespace Microsoft.NET.Sdk.WorkloadManifestReader { internal class WorkloadSuggestionFinder @@ -33,7 +37,7 @@ public WorkloadSuggestionFinder(HashSet installedPacks, HashSet< } /// - /// Serachest the list of expanded workloads for workloads that are "simple" complete suggestions themselves and workloads that could be part of a more complex complete suggestion. + /// Search the list of expanded workloads for workloads that are "simple" complete suggestions themselves and workloads that could be part of a more complex complete suggestion. /// /// The packs that a complete suggestion must include /// The full set of workloads, flattened to include the packs in the workloads they extend diff --git a/src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAAllowEmptyTelemetry.cs b/src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAAllowEmptyTelemetry.cs index 3b5677518a0c..c4a6d7abd500 100644 --- a/src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAAllowEmptyTelemetry.cs +++ b/src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/GivenAAllowEmptyTelemetry.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using FluentAssertions; using Microsoft.Build.Framework; using Microsoft.Build.Tasks; diff --git a/src/WebSdk/Publish/Tasks/Tasks/Http/HttpClientExtensions.cs b/src/WebSdk/Publish/Tasks/Tasks/Http/HttpClientExtensions.cs index 5565638afd51..d3d7d72e37d8 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/Http/HttpClientExtensions.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/Http/HttpClientExtensions.cs @@ -34,13 +34,13 @@ internal static class HttpClientExtensions /// encoding /// message payload /// HTTP response - public static async Task PostRequestAsync( + public static async Task PostRequestAsync( this IHttpClient client, Uri uri, - string username, - string password, + string? username, + string? password, string contentType, - string userAgent, + string? userAgent, Encoding encoding, Stream messageBody) { @@ -89,14 +89,14 @@ public static async Task PostRequestAsync( /// encoding /// message payload /// HTTP response - public static async Task PutRequestAsync( + public static async Task PutRequestAsync( this IHttpClient client, Uri uri, - string username, - string password, + string? username, + string? password, string contentType, - string userAgent, - string fileName, + string? userAgent, + string? fileName, Encoding encoding, Stream messageBody, CancellationToken cancellationToken) @@ -145,11 +145,11 @@ public static async Task PutRequestAsync( /// 'User-Agent' header value /// /// HTTP response - public static async Task GetRequestAsync( + public static async Task GetRequestAsync( this IHttpClient client, Uri uri, - string username, - string password, + string? username, + string? password, string userAgent, CancellationToken cancellationToken) { @@ -185,30 +185,30 @@ public static async Task GetRequestAsync( /// time to wait between attempts; usually in seconds /// cancellation token /// response of given type; default value if response status code is not of success - public static async Task RetryGetRequestAsync( + public static async Task RetryGetRequestAsync( this IHttpClient client, - string url, - string username, - string password, + string? url, + string? username, + string? password, string userAgent, int retries, TimeSpan delay, CancellationToken cancellationToken) { - if (client is null) + if (client is null || url is null) { return default; } // retry GET request - IHttpResponse response = null; + IHttpResponse? response = null; await RetryTaskAsync(async (ct) => { response = await client.GetRequestAsync(new Uri(url, UriKind.RelativeOrAbsolute), username, password, userAgent, ct); }, retries, delay, cancellationToken); // response is not valid; return default value - if (!response.IsResponseSuccessful()) + if (!(response?.IsResponseSuccessful() ?? false)) { return default; } @@ -259,7 +259,7 @@ public static async Task GetTextResponseAsync(this IHttpResponse respons /// type to serialize to /// cancellation token /// object - public static async Task GetJsonResponseAsync(this IHttpResponse response, CancellationToken cancellation) + public static async Task GetJsonResponseAsync(this IHttpResponse response, CancellationToken cancellation) { if (response is null || cancellation.IsCancellationRequested) { @@ -267,12 +267,16 @@ public static async Task GetJsonResponseAsync(this IHttpResponse response, } using var stream = await response.GetResponseBodyAsync(); + if (stream is null) + { + return default; + } var reader = new StreamReader(stream, Encoding.UTF8); return JsonSerializer.Deserialize(reader.ReadToEnd(), s_defaultSerializerOptions); } - private static void AddAuthenticationHeader(string username, string password, IHttpClient client) + private static void AddAuthenticationHeader(string? username, string? password, IHttpClient client) { client.DefaultRequestHeaders.Remove("Connection"); diff --git a/src/WebSdk/Publish/Tasks/Tasks/Http/HttpResponseMessageForStatusCode.cs b/src/WebSdk/Publish/Tasks/Tasks/Http/HttpResponseMessageForStatusCode.cs index e5de396a718d..bd7175ad8286 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/Http/HttpResponseMessageForStatusCode.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/Http/HttpResponseMessageForStatusCode.cs @@ -11,9 +11,9 @@ internal class HttpResponseMessageForStatusCode(HttpStatusCode statusCode) : IHt public HttpStatusCode StatusCode { get; private set; } = statusCode; /// - public Task GetResponseBodyAsync() + public Task GetResponseBodyAsync() { - return System.Threading.Tasks.Task.FromResult(new MemoryStream()); + return System.Threading.Tasks.Task.FromResult(new MemoryStream()); } /// diff --git a/src/WebSdk/Publish/Tasks/Tasks/Http/HttpResponseMessageWrapper.cs b/src/WebSdk/Publish/Tasks/Tasks/Http/HttpResponseMessageWrapper.cs index 61cc82f02fad..c6fb5f6c3b38 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/Http/HttpResponseMessageWrapper.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/Http/HttpResponseMessageWrapper.cs @@ -9,12 +9,12 @@ namespace Microsoft.NET.Sdk.Publish.Tasks; internal class HttpResponseMessageWrapper : IHttpResponse { private readonly HttpResponseMessage _message; - private readonly Lazy> _responseBodyTask; + private readonly Lazy?> _responseBodyTask; public HttpResponseMessageWrapper(HttpResponseMessage message) { _message = message; - _responseBodyTask = new Lazy>(GetResponseStream); + _responseBodyTask = new Lazy?>(GetResponseStream); StatusCode = message?.StatusCode ?? HttpStatusCode.InternalServerError; } @@ -23,7 +23,7 @@ public HttpResponseMessageWrapper(HttpResponseMessage message) public HttpStatusCode StatusCode { get; private set; } /// - public async Task GetResponseBodyAsync() + public async Task GetResponseBodyAsync() { return _responseBodyTask.Value is not null ? await _responseBodyTask.Value @@ -35,7 +35,7 @@ public IEnumerable GetHeader(string name) { if (_message is not null && _message.Headers is not null - && _message.Headers.TryGetValues(name, out IEnumerable values)) + && _message.Headers.TryGetValues(name, out IEnumerable? values)) { return values; } @@ -43,7 +43,7 @@ public IEnumerable GetHeader(string name) return []; } - private Task GetResponseStream() + private Task? GetResponseStream() { return _message is not null && _message.Content is not null ? _message.Content.ReadAsStreamAsync() diff --git a/src/WebSdk/Publish/Tasks/Tasks/Http/IHttpResponse.cs b/src/WebSdk/Publish/Tasks/Tasks/Http/IHttpResponse.cs index 29ca812209df..13e3082f9821 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/Http/IHttpResponse.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/Http/IHttpResponse.cs @@ -18,7 +18,7 @@ internal interface IHttpResponse /// /// Gets the body of the response /// - Task GetResponseBodyAsync(); + Task GetResponseBodyAsync(); /// /// Gets the value of an HTTP Response header diff --git a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/VsMsdeploy.cs b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/VsMsdeploy.cs index 67ff80f41334..a26b0428b10f 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/VsMsdeploy.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/MsDeploy/VsMsdeploy.cs @@ -447,16 +447,19 @@ private static void AddAllPropertiesToCustomBuildWithPropertyEventArgs(ExtendedC if (obj != null) { Type thisType = obj.GetType(); - cbpEventArg.ExtendedMetadata["ArgumentType"] = thisType.ToString(); + if (cbpEventArg.ExtendedMetadata is not null) + { + cbpEventArg.ExtendedMetadata["ArgumentType"] = thisType.ToString(); + } System.Reflection.MemberInfo[] arrayMemberInfo = thisType.FindMembers(System.Reflection.MemberTypes.Property, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null); if (arrayMemberInfo != null) { foreach (System.Reflection.MemberInfo memberInfo in arrayMemberInfo) { object val = thisType.InvokeMember(memberInfo.Name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty, null, obj, null, System.Globalization.CultureInfo.InvariantCulture); - if (val != null) + if (val is not null && cbpEventArg.ExtendedMetadata is not null) { - cbpEventArg.ExtendedMetadata[memberinfo.Name] = val.ToString(); + cbpEventArg.ExtendedMetadata[memberInfo.Name] = val.ToString(); } } } @@ -509,7 +512,7 @@ protected override void LogTrace(dynamic args, IDictionary(StringComparer.OrdinalIgnoreCase) + ExtendedMetadata = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "TaskName", TaskName }, { "EventType", strEventType } diff --git a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/CreatePackageFile.cs b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/CreatePackageFile.cs index 237fc484bc52..178b83411443 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/CreatePackageFile.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/CreatePackageFile.cs @@ -24,16 +24,16 @@ internal CreatePackageFile(IFilePackager filePackager) } [Required] - public string ContentToPackage { get; set; } + public string? ContentToPackage { get; set; } [Required] - public string ProjectName { get; set; } + public string? ProjectName { get; set; } [Required] - public string IntermediateTempPath { get; set; } + public string? IntermediateTempPath { get; set; } [Output] - public string CreatedPackageFilePath { get; set; } + public string? CreatedPackageFilePath { get; set; } /// public override bool Execute() @@ -49,7 +49,7 @@ public override bool Execute() var packageFilePath = Path.Combine(IntermediateTempPath, packageFileName); // package content - var packageFileTask = _filePackager.CreatePackageAsync(ContentToPackage, packageFilePath, CancellationToken.None); + var packageFileTask = _filePackager.CreatePackageAsync(ContentToPackage!, packageFilePath, CancellationToken.None); packageFileTask.Wait(); CreatedPackageFilePath = packageFileTask.Result ? packageFilePath : string.Empty; diff --git a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/DeploymentResponse.cs b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/DeploymentResponse.cs index c750d9867685..0d3d70613431 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/DeploymentResponse.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/DeploymentResponse.cs @@ -17,31 +17,31 @@ internal class DeploymentResponse }; [JsonPropertyName("id")] - public string Id { get; set; } + public string? Id { get; set; } [JsonPropertyName("end_time")] - public string EndTime { get; set; } + public string? EndTime { get; set; } [JsonPropertyName("log_url")] - public string LogUrl { get; set; } + public string? LogUrl { get; set; } [JsonPropertyName("message")] - public string Message { get; set; } + public string? Message { get; set; } [JsonPropertyName("status")] public DeploymentStatus? Status { get; set; } = DeploymentStatus.Unknown; [JsonPropertyName("site_name")] - public string SiteName { get; set; } + public string? SiteName { get; set; } [JsonPropertyName("status_text")] - public string StatusText { get; set; } + public string? StatusText { get; set; } [JsonPropertyName("start_time")] - public string StartTime { get; set; } + public string? StartTime { get; set; } [JsonPropertyName("url")] - public string Url { get; set; } + public string? Url { get; set; } /// public override string ToString() @@ -50,7 +50,6 @@ public override string ToString() ? string.Format(Resources.DeploymentStatus, Status) : string.Format(Resources.DeploymentStatusWithText, Status, StatusText); } - } /// @@ -72,7 +71,7 @@ internal static bool IsFailedResponse(this DeploymentResponse response) || response.Status.Value.IsFailedStatus(); } - public static string GetLogUrlWithId(this DeploymentResponse deploymentResponse) + public static string? GetLogUrlWithId(this DeploymentResponse deploymentResponse) { if (deploymentResponse is null || string.IsNullOrEmpty(deploymentResponse.LogUrl) @@ -90,7 +89,7 @@ public static string GetLogUrlWithId(this DeploymentResponse deploymentResponse) if (!string.IsNullOrEmpty(pathAndQuery)) { string[] pathAndQueryParts = pathAndQuery.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); - string[] pathWithIdParts = new string[pathAndQueryParts.Length]; + string?[] pathWithIdParts = new string[pathAndQueryParts.Length]; for (int i = pathAndQueryParts.Length - 1; i >= 0; i--) { diff --git a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/IDeploymentStatusService.cs b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/IDeploymentStatusService.cs index 94242b6574c1..a2fb7ff140e8 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/IDeploymentStatusService.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/IDeploymentStatusService.cs @@ -19,5 +19,5 @@ internal interface IDeploymentStatusService /// 'UserAgent' header value /// cancellation token /// the resulting deployment response - Task PollDeploymentAsync(IHttpClient httpClient, string url, string user, string password, string userAgent, CancellationToken cancellation); + Task PollDeploymentAsync(IHttpClient httpClient, string? url, string? user, string? password, string userAgent, CancellationToken cancellation); } diff --git a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeploy.WebJob.cs b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeploy.WebJob.cs index 92eb1fc55149..fd56390245e3 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeploy.WebJob.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeploy.WebJob.cs @@ -13,25 +13,25 @@ public partial class OneDeploy private const string ContinuousWebJobApiPath = "continuouswebjobs"; private const string TriggeredWebJobsApiPath = "triggeredwebjobs"; - public string WebJobName { get; set; } + public string? WebJobName { get; set; } - public string WebJobType { get; set; } + public string? WebJobType { get; set; } /// /// Whether the name is a non-empty value and type is either 'Continuous' or 'Triggered'. /// - private bool IsWebJobProject(string webjobName, string webjobType) => + private bool IsWebJobProject(string? webjobName, string? webjobType) => !string.IsNullOrEmpty(webjobName) && (string.Equals(ContinuousWebJobType, webjobType, StringComparison.OrdinalIgnoreCase) || string.Equals(TriggeredWebJobType, webjobType, StringComparison.OrdinalIgnoreCase)); - private async Task DeployWebJobAsync( + private async Task DeployWebJobAsync( IHttpClient httpClient, Uri publishUri, - string username, - string password, - string userAgent, - string fileToPublish, + string? username, + string? password, + string? userAgent, + string? fileToPublish, FileStream fileToPublishStream, CancellationToken cancellationToken) { @@ -41,7 +41,7 @@ private async Task DeployWebJobAsync( return response; } - private bool GetWebJobPublishUri(string publishUrl, string webjobName, string webjobType, out Uri publishUri) + private bool GetWebJobPublishUri(string publishUrl, string? webjobName, string? webjobType, out Uri publishUri) { // action path differs by WebJob type var path = string.Equals(ContinuousWebJobType, webjobType, StringComparison.OrdinalIgnoreCase) diff --git a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeploy.cs b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeploy.cs index 102ada7e76de..bbfeda2f28b6 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeploy.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeploy.cs @@ -32,17 +32,17 @@ internal OneDeploy(ITaskLogger taskLogger) } [Required] - public string FileToPublishPath { get; set; } + public string? FileToPublishPath { get; set; } - public string PublishUrl { get; set; } + public string? PublishUrl { get; set; } [Required] - public string Username { get; set; } + public string? Username { get; set; } - public string Password { get; set; } + public string? Password { get; set; } [Required] - public string UserAgentVersion { get; set; } + public string? UserAgentVersion { get; set; } /// public override bool Execute() @@ -54,13 +54,13 @@ public override bool Execute() } public async Task OneDeployAsync( - string fileToPublishPath, - string username, - string password, - string url, - string userAgentVersion, - string webjobName = null, - string webjobType = null, + string? fileToPublishPath, + string? username, + string? password, + string? url, + string? userAgentVersion, + string? webjobName = null, + string? webjobType = null, CancellationToken cancellationToken = default) { using DefaultHttpClient httpClient = new(); @@ -73,13 +73,13 @@ public async Task OneDeployAsync( } internal async Task OneDeployAsync( - string fileToPublishPath, - string username, - string password, - string url, + string? fileToPublishPath, + string? username, + string? password, + string? url, string userAgent, - string webjobName, - string webjobType, + string? webjobName, + string? webjobType, IHttpClient httpClient, IDeploymentStatusService deploymentStatusService, CancellationToken cancellationToken = default) @@ -99,7 +99,7 @@ internal async Task OneDeployAsync( } // 'PublishUrl' must be valid - if (!GetPublishUrl(url, webjobName, webjobType, out var oneDeployPublishUri)) + if (!GetPublishUrl(url, webjobName, webjobType, out var oneDeployPublishUri) || oneDeployPublishUri is null) { _taskLogger.LogError(string.Format(Resources.ONEDEPLOY_InvalidPublishUrl, url)); return false; @@ -116,9 +116,9 @@ internal async Task OneDeployAsync( httpClient, oneDeployPublishUri, username, password, userAgent, fileToPublishPath, webjobName, webjobType, fileToPublishStream, cancellationToken); // if push failed, finish operation - if (!response.IsResponseSuccessful()) + if (!(response?.IsResponseSuccessful() ?? false)) { - var responseText = await response.GetTextResponseAsync(cancellationToken); + var responseText = response is null ? string.Empty : await response.GetTextResponseAsync(cancellationToken); var errorMessage = !string.IsNullOrEmpty(responseText) ? string.Format(Resources.ONEDEPLOY_FailedDeployRequest_With_ResponseText, oneDeployPublishUri, response?.StatusCode, responseText) @@ -136,19 +136,19 @@ internal async Task OneDeployAsync( { var deploymentResponse = await deploymentStatusService.PollDeploymentAsync(httpClient, deploymentUrl, username, password, userAgent, cancellationToken); - if (deploymentResponse.IsSuccessfulResponse()) + if (deploymentResponse?.IsSuccessfulResponse() ?? false) { _taskLogger.LogMessage(MessageImportance.High, Resources.ONEDEPLOY_Success); return true; } - if (deploymentResponse.IsFailedResponse()) + if (deploymentResponse?.IsFailedResponse() ?? true) { _taskLogger.LogError(string.Format(Resources.ONEDEPLOY_FailedWithLogs, fileToPublishPath, oneDeployPublishUri, - deploymentResponse.Status ?? DeploymentStatus.Unknown, - deploymentResponse.GetLogUrlWithId())); + deploymentResponse?.Status ?? DeploymentStatus.Unknown, + deploymentResponse?.GetLogUrlWithId())); return false; } @@ -166,15 +166,15 @@ private bool GetCredentialsFromTask(out string user, out string password) return hostObj.ExtractCredentials(out user, out password); } - private Task DeployAsync( + private Task DeployAsync( IHttpClient httpClient, Uri publishUri, - string username, - string password, - string userAgent, - string fileToPublish, - string webjobName, - string webjobType, + string? username, + string? password, + string? userAgent, + string? fileToPublish, + string? webjobName, + string? webjobType, FileStream fileToPublishStream, CancellationToken cancellationToken) { @@ -183,7 +183,7 @@ private Task DeployAsync( : DefaultDeployAsync(httpClient, publishUri, username, password, userAgent, fileToPublishStream, cancellationToken); } - private bool GetPublishUrl(string publishUrl, string webjobName, string webjobType, out Uri publishUri) + private bool GetPublishUrl(string? publishUrl, string? webjobName, string? webjobType, out Uri? publishUri) { publishUri = null; @@ -194,16 +194,16 @@ private bool GetPublishUrl(string publishUrl, string webjobName, string webjobTy } return IsWebJobProject(webjobName, webjobType) - ? GetWebJobPublishUri(publishUrl, webjobName, webjobType, out publishUri) - : GetDefaultPublishUri(publishUrl, out publishUri); + ? GetWebJobPublishUri(publishUrl!, webjobName, webjobType, out publishUri) + : GetDefaultPublishUri(publishUrl!, out publishUri); } - private async Task DefaultDeployAsync( + private async Task DefaultDeployAsync( IHttpClient httpClient, Uri publishUri, - string username, - string password, - string userAgent, + string? username, + string? password, + string? userAgent, FileStream fileToPublishStream, CancellationToken cancellationToken) { diff --git a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeployStatusService.cs b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeployStatusService.cs index 2929437335b5..292d7b4c33fb 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeployStatusService.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/OneDeploy/OneDeployStatusService.cs @@ -6,21 +6,21 @@ namespace Microsoft.NET.Sdk.Publish.Tasks.OneDeploy; -internal class OneDeployStatusService(ITaskLogger taskLogger = null) : IDeploymentStatusService +internal class OneDeployStatusService(ITaskLogger? taskLogger = null) : IDeploymentStatusService { private static readonly TimeSpan s_maximumWaitForResult = TimeSpan.FromMinutes(3); private static readonly TimeSpan s_refreshDelay = TimeSpan.FromSeconds(3); private static readonly TimeSpan s_retryDelay = TimeSpan.FromSeconds(1); private static readonly int s_retryCount = 3; - private readonly ITaskLogger _taskLogger = taskLogger; + private readonly ITaskLogger? _taskLogger = taskLogger; /// - public async Task PollDeploymentAsync( + public async Task PollDeploymentAsync( IHttpClient httpClient, - string url, - string user, - string password, + string? url, + string? user, + string? password, string userAgent, CancellationToken cancellationToken) { @@ -41,7 +41,7 @@ public async Task PollDeploymentAsync( var retryTokenSource = CancellationTokenSource.CreateLinkedTokenSource(maxWaitForResultTokenSource.Token, cancellationToken); var retryToken = retryTokenSource.Token; - DeploymentResponse deploymentResponse = null; + DeploymentResponse? deploymentResponse = null; DeploymentStatus deployStatus = DeploymentStatus.Pending; try @@ -60,7 +60,7 @@ public async Task PollDeploymentAsync( ? deploymentResponse.Status.Value : DeploymentStatus.Unknown; - _taskLogger?.LogMessage(deploymentResponse.ToString()); + _taskLogger?.LogMessage(deploymentResponse!.ToString()); await System.Threading.Tasks.Task.Delay(s_refreshDelay, retryToken); } diff --git a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploy.cs b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploy.cs index e38f065ee84e..739b5cdb0f3e 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploy.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploy.cs @@ -91,12 +91,12 @@ public async Task ZipDeployAsync(string? zipToPublishPath, string? userNam Uri uri = new($"{zipDeployPublishUrl}?isAsync=true", UriKind.Absolute); string userAgent = $"{UserAgentName}/{userAgentVersion}"; FileStream stream = File.OpenRead(zipToPublishPath); - IHttpResponse response = await client.PostRequestAsync(uri, userName, password, "application/zip", userAgent, Encoding.UTF8, stream); - if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Accepted) + IHttpResponse? response = await client.PostRequestAsync(uri, userName, password, "application/zip", userAgent, Encoding.UTF8, stream); + if (response?.StatusCode != HttpStatusCode.OK && response?.StatusCode != HttpStatusCode.Accepted) { if (logMessages) { - Log.LogError(string.Format(Resources.ZIPDEPLOY_FailedDeploy, zipDeployPublishUrl, response.StatusCode)); + Log.LogError(string.Format(Resources.ZIPDEPLOY_FailedDeploy, zipDeployPublishUrl, response?.StatusCode)); } return false; diff --git a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploymentStatus.cs b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploymentStatus.cs index 8be6f2ebc8cc..3bc87941b272 100644 --- a/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploymentStatus.cs +++ b/src/WebSdk/Publish/Tasks/Tasks/ZipDeploy/ZipDeploymentStatus.cs @@ -83,14 +83,14 @@ await RetryAsync(async () => { return default; } - else + + using var stream = await response.GetResponseBodyAsync(); + if (stream is null) { - using (var stream = await response.GetResponseBodyAsync()) - { - var reader = new StreamReader(stream, Encoding.UTF8); - return FromJson(reader.ReadToEnd()); - } + return default; } + var reader = new StreamReader(stream, Encoding.UTF8); + return FromJson(reader.ReadToEnd()); } private async System.Threading.Tasks.Task RetryAsync(Func func, int retryCount, TimeSpan retryDelay) diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblyMapperTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblyMapperTests.cs index 1ebe43d3e73f..2ce6db12f258 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblyMapperTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblyMapperTests.cs @@ -72,7 +72,7 @@ public class A { } IEnumerable namespaceMappers = assemblyMapper.GetNamespaces(); Assert.Equal(3, namespaceMappers.Count()); - Assert.Equal(new string?[] { "AssemblyMapperTestNamespace1", "AssemblyMapperTestNamespace2", null }, namespaceMappers.Select(n => n.Left?.Name)); + Assert.Equal(new string[] { "AssemblyMapperTestNamespace1", "AssemblyMapperTestNamespace2", null }, namespaceMappers.Select(n => n.Left?.Name)); Assert.Equal(new string[] { "AssemblyMapperTestNamespace1", "AssemblyMapperTestNamespace2", "AssemblyMapperTestNamespace3" }, namespaceMappers.SelectMany(n => n.Right).Select(r => r?.Name)); } } diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblySetMapperTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblySetMapperTests.cs index 5e3084e2b10e..5e1068ba041e 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblySetMapperTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/AssemblySetMapperTests.cs @@ -124,7 +124,7 @@ public class First { } Assert.Equal(4, assemblySetMapper.AssemblyCount); Assert.Equal(4, assemblyMappers.Count()); - Assert.Equal(new string?[] { + Assert.Equal(new string[] { nameof(AssemblySetMapper_GetAssemblies_ReturnsExpected) + "-0", nameof(AssemblySetMapper_GetAssemblies_ReturnsExpected) + "-1", nameof(AssemblySetMapper_GetAssemblies_ReturnsExpected) + "-2", diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/NamespaceMapperTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/NamespaceMapperTests.cs index b8b11b47ee6e..b65911768e7c 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/NamespaceMapperTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/NamespaceMapperTests.cs @@ -64,7 +64,7 @@ public class B { } IEnumerable typeMappers = namespaceMappers.Single().GetTypes(); Assert.Equal(2, typeMappers.Count()); - Assert.Equal(new string?[] { "A", null }, typeMappers.Select(n => n.Left?.Name)); + Assert.Equal(new string[] { "A", null }, typeMappers.Select(n => n.Left?.Name)); Assert.Equal(new string[] { "A", "B" }, typeMappers.SelectMany(n => n.Right).Select(r => r?.Name)); } } diff --git a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/TypeMapperTests.cs b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/TypeMapperTests.cs index d9c631d44d4e..0bbd1c8ea4f6 100644 --- a/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/TypeMapperTests.cs +++ b/test/Microsoft.DotNet.ApiCompatibility.Tests/Mapping/TypeMapperTests.cs @@ -79,7 +79,7 @@ protected internal class D { } IEnumerable nestedTypeMappers = typeMappers.Single().GetNestedTypes(); Assert.Equal(3, nestedTypeMappers.Count()); - Assert.Equal(new string?[] { "B", "C", null }, nestedTypeMappers.Select(n => n.Left?.Name)); + Assert.Equal(new string[] { "B", "C", null }, nestedTypeMappers.Select(n => n.Left?.Name)); Assert.Equal(new string[] { "B", "C", "D" }, nestedTypeMappers.SelectMany(n => n.Right).Select(r => r?.Name)); } @@ -120,7 +120,7 @@ public A() { } IEnumerable memberMappers = typeMappers.Single().GetMembers(); Assert.Equal(4, memberMappers.Count()); - Assert.Equal(new string?[] { ".ctor", "B", "C", null }, memberMappers.Select(n => n.Left?.Name)); + Assert.Equal(new string[] { ".ctor", "B", "C", null }, memberMappers.Select(n => n.Left?.Name)); Assert.Equal(new string[] { ".ctor", "B", "C", "D" }, memberMappers.SelectMany(n => n.Right).Select(r => r?.Name)); } diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs index 717421b9dd83..b6a8cf0df4ed 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs @@ -401,16 +401,13 @@ public async Task EndToEnd_NoAPI_ProjectType(string projectType, bool addPackage string appContainerId = processResult.StdOut.Trim(); bool everSucceeded = false; - - - if (projectType == "webapi") { var portCommand = ContainerCli.PortCommand(_testOutput, containerName, 8080) .Execute(); portCommand.Should().Pass(); - var port = portCommand.StdOut.Trim().Split("\n")[0]; // only take the first port, which should be 0.0.0.0:PORT. the second line will be an ip6 port, if any. + var port = portCommand.StdOut?.Trim().Split("\n")[0]; // only take the first port, which should be 0.0.0.0:PORT. the second line will be an ip6 port, if any. _testOutput.WriteLine($"Discovered port was '{port}'"); var tempUri = new Uri($"http://{port}", UriKind.Absolute); var appUri = new UriBuilder(tempUri) diff --git a/test/Microsoft.NET.Sdk.WorkloadManifestReader.Tests/ManifestTests.cs b/test/Microsoft.NET.Sdk.WorkloadManifestReader.Tests/ManifestTests.cs index aac239981b00..cc0b2491adad 100644 --- a/test/Microsoft.NET.Sdk.WorkloadManifestReader.Tests/ManifestTests.cs +++ b/test/Microsoft.NET.Sdk.WorkloadManifestReader.Tests/ManifestTests.cs @@ -110,7 +110,7 @@ void TestMultiplePackRoots(bool defaultExists, bool additionalExists) } var manifestProvider = new FakeManifestProvider(ManifestPath); - var resolver = WorkloadResolver.CreateForTests(manifestProvider, new[] { (additionalRoot, false), (dotnetRoot, true), ("other", true) }); + var resolver = WorkloadResolver.CreateForTests(manifestProvider, [ new(additionalRoot, false), new(dotnetRoot, true), new("other", true) ]); var pack = resolver.TryGetPackInfo(new WorkloadPackId("Xamarin.Android.Sdk")); pack.Should().NotBeNull(); @@ -132,7 +132,7 @@ public void GivenNonExistentPackRoot_ItIgnoresIt() Directory.CreateDirectory(defaultPackPath); var manifestProvider = new FakeManifestProvider(ManifestPath); - var resolver = WorkloadResolver.CreateForTests(manifestProvider, new[] { (additionalRoot, false), (dotnetRoot, true) }); + var resolver = WorkloadResolver.CreateForTests(manifestProvider, [ new(additionalRoot, false), new(dotnetRoot, true) ]); var pack = resolver.TryGetPackInfo(new WorkloadPackId("Xamarin.Android.Sdk")); pack.Should().NotBeNull(); diff --git a/test/Microsoft.NET.TestFramework/InMemoryLoggerProvider.cs b/test/Microsoft.NET.TestFramework/InMemoryLoggerProvider.cs index e97c2ed7e68e..890613392f1b 100644 --- a/test/Microsoft.NET.TestFramework/InMemoryLoggerProvider.cs +++ b/test/Microsoft.NET.TestFramework/InMemoryLoggerProvider.cs @@ -1,6 +1,10 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.Extensions.Logging; namespace Microsoft.NET.TestFramework diff --git a/test/Microsoft.NET.TestFramework/TestLoggerFactory.cs b/test/Microsoft.NET.TestFramework/TestLoggerFactory.cs index 0995a260e6cf..8c48f1cd58e9 100644 --- a/test/Microsoft.NET.TestFramework/TestLoggerFactory.cs +++ b/test/Microsoft.NET.TestFramework/TestLoggerFactory.cs @@ -1,6 +1,10 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.Extensions.Logging; namespace Microsoft.NET.TestFramework diff --git a/test/Microsoft.NET.TestFramework/Utilities/BufferedReporter.cs b/test/Microsoft.NET.TestFramework/Utilities/BufferedReporter.cs index c54607a9f03f..cdcec84f34ce 100644 --- a/test/Microsoft.NET.TestFramework/Utilities/BufferedReporter.cs +++ b/test/Microsoft.NET.TestFramework/Utilities/BufferedReporter.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.DotNet.Cli.Utils; namespace Microsoft.NET.TestFramework.Utilities diff --git a/test/Microsoft.NET.TestFramework/XunitLoggerProvider.cs b/test/Microsoft.NET.TestFramework/XunitLoggerProvider.cs index 080e6be34b03..f25771bdc311 100644 --- a/test/Microsoft.NET.TestFramework/XunitLoggerProvider.cs +++ b/test/Microsoft.NET.TestFramework/XunitLoggerProvider.cs @@ -1,6 +1,10 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.Extensions.Logging; using ILogger = Microsoft.Extensions.Logging.ILogger; using LogLevel = Microsoft.Extensions.Logging.LogLevel; diff --git a/test/dotnet-new.Tests/DotnetNewDetailsTest.Approval.cs b/test/dotnet-new.Tests/DotnetNewDetailsTest.Approval.cs index 25e9d00d8b5c..3bd14607b92b 100644 --- a/test/dotnet-new.Tests/DotnetNewDetailsTest.Approval.cs +++ b/test/dotnet-new.Tests/DotnetNewDetailsTest.Approval.cs @@ -203,9 +203,9 @@ private async Task GetLatestVersion(string packageName) } } - private string ExtractVersion(string stdOut) + private string ExtractVersion(string? stdOut) { - var match = Regex.Match(stdOut, @"Package version:\s*(\S+)"); + var match = Regex.Match(stdOut ?? string.Empty, @"Package version:\s*(\S+)"); if (match.Success) { return match.Groups[1].Value; diff --git a/test/dotnet-new.Tests/DotnetNewInstallTests.cs b/test/dotnet-new.Tests/DotnetNewInstallTests.cs index 2ebcaff0bb44..a7bca8cf6e46 100644 --- a/test/dotnet-new.Tests/DotnetNewInstallTests.cs +++ b/test/dotnet-new.Tests/DotnetNewInstallTests.cs @@ -76,7 +76,7 @@ public void CanInstallRemoteNuGetPackage_LatestVariations(string commandName) // Install command are expected to output the requested version literaly as they got it on input, // but otherwise the outputs are expected to be equal - string command3Out = command3.StdOut.Replace( + string? command3Out = command3.StdOut?.Replace( "Microsoft.DotNet.Common.ProjectTemplates.5.0::*", "Microsoft.DotNet.Common.ProjectTemplates.5.0"); @@ -135,11 +135,11 @@ public void CanInstallRemoteNuGetPackageWithVersionWildcard(string commandName) // Install command are expected to output the requested version literaly as they got it on input, // but otherwise the outputs are expected to be equal - string command1Out = command1.StdOut.Replace( + string? command1Out = command1.StdOut?.Replace( "Microsoft.DotNet.Common.ProjectTemplates.5.0::5.*", "Microsoft.DotNet.Common.ProjectTemplates.5.0"); - string command2Out = command2.StdOut.Replace( + string? command2Out = command2.StdOut?.Replace( "Microsoft.DotNet.Common.ProjectTemplates.5.0::5.0.*", "Microsoft.DotNet.Common.ProjectTemplates.5.0"); diff --git a/test/dotnet-new.Tests/DotnetNewSearchTests.cs b/test/dotnet-new.Tests/DotnetNewSearchTests.cs index ebbf75b7ec62..9596ac84b58a 100644 --- a/test/dotnet-new.Tests/DotnetNewSearchTests.cs +++ b/test/dotnet-new.Tests/DotnetNewSearchTests.cs @@ -876,9 +876,9 @@ private static bool AtLeastOneRowIsNotEmpty(List> tableOutput, stri return tableOutput.Any(row => !string.IsNullOrWhiteSpace(row[columnIndex])); } - private static List> ParseTableOutput(string stdOut, string[] expectedColumns) + private static List> ParseTableOutput(string? stdOut, string[] expectedColumns) { - string[] lines = stdOut.Split(Environment.NewLine); + string[] lines = stdOut?.Split(Environment.NewLine) ?? Array.Empty(); int headerLineIndex = Array.FindIndex(lines, line => expectedColumns.All(column => line.Contains(column))); string headerLine = lines[headerLineIndex]; diff --git a/test/dotnet.Tests/NuGetSignatureVerificationEnablerTests.cs b/test/dotnet.Tests/NuGetSignatureVerificationEnablerTests.cs index 246abf721406..7ea18ce8c8d0 100644 --- a/test/dotnet.Tests/NuGetSignatureVerificationEnablerTests.cs +++ b/test/dotnet.Tests/NuGetSignatureVerificationEnablerTests.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using System.Diagnostics; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.Utils; diff --git a/test/dotnet.Tests/dotnet-new/DotnetAddPostActionTests.cs b/test/dotnet.Tests/dotnet-new/DotnetAddPostActionTests.cs index 7ac74c584005..66a41605cc57 100644 --- a/test/dotnet.Tests/dotnet-new/DotnetAddPostActionTests.cs +++ b/test/dotnet.Tests/dotnet-new/DotnetAddPostActionTests.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.DotNet.Tools.New.PostActionProcessors; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Mocks; diff --git a/test/dotnet.Tests/dotnet-new/DotnetRestorePostActionTests.cs b/test/dotnet.Tests/dotnet-new/DotnetRestorePostActionTests.cs index a4c85a4b31fd..c4f38952b689 100644 --- a/test/dotnet.Tests/dotnet-new/DotnetRestorePostActionTests.cs +++ b/test/dotnet.Tests/dotnet-new/DotnetRestorePostActionTests.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.DotNet.Tools.New.PostActionProcessors; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Mocks; diff --git a/test/dotnet.Tests/dotnet-new/DotnetSlnPostActionTests.cs b/test/dotnet.Tests/dotnet-new/DotnetSlnPostActionTests.cs index a516e68391df..e52dc6797d2f 100644 --- a/test/dotnet.Tests/dotnet-new/DotnetSlnPostActionTests.cs +++ b/test/dotnet.Tests/dotnet-new/DotnetSlnPostActionTests.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.DotNet.Tools.New.PostActionProcessors; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Mocks; diff --git a/test/dotnet.Tests/dotnet-new/SdkInfoProviderTests.cs b/test/dotnet.Tests/dotnet-new/SdkInfoProviderTests.cs index c6a38738cef4..c9cf04a4d91c 100644 --- a/test/dotnet.Tests/dotnet-new/SdkInfoProviderTests.cs +++ b/test/dotnet.Tests/dotnet-new/SdkInfoProviderTests.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable IDE0240 +#nullable enable +#pragma warning restore IDE0240 + using Microsoft.DotNet.Tools.New; using Microsoft.TemplateEngine.Abstractions.Components; From cd3b4e6878e6ac4ec0696dcc4b8b95ae9eec1776 Mon Sep 17 00:00:00 2001 From: Michael Yanni Date: Mon, 18 Nov 2024 14:36:41 -0800 Subject: [PATCH 7/7] Fixes based on looking over the PR diff. Removed commented code and accidental removal of nullable on the WorkloadManifestReader. --- src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj | 1 - .../Microsoft.NET.Sdk.WorkloadManifestReader.csproj | 1 + .../Microsoft.NET.Build.Extensions.Tasks.csproj | 1 - .../Microsoft.NET.TestFramework.csproj | 1 - 4 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj b/src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj index b014fa49c9ed..469762294a6e 100644 --- a/src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj +++ b/src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj @@ -14,7 +14,6 @@ false - diff --git a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/Microsoft.NET.Sdk.WorkloadManifestReader.csproj b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/Microsoft.NET.Sdk.WorkloadManifestReader.csproj index c9771ab10f0a..77cd7cdef063 100644 --- a/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/Microsoft.NET.Sdk.WorkloadManifestReader.csproj +++ b/src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/Microsoft.NET.Sdk.WorkloadManifestReader.csproj @@ -3,6 +3,7 @@ $(ResolverTargetFramework);net472 MicrosoftAspNetCore + enable true diff --git a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj index f72fb0eb7df7..164f0381338e 100644 --- a/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj +++ b/src/Tasks/Microsoft.NET.Build.Extensions.Tasks/Microsoft.NET.Build.Extensions.Tasks.csproj @@ -7,7 +7,6 @@ Microsoft.NET.Build.Extensions $(Configuration)\Sdks\$(PackageId)\msbuildExtensions\Microsoft\Microsoft.NET.Build.Extensions\tools - enable diff --git a/test/Microsoft.NET.TestFramework/Microsoft.NET.TestFramework.csproj b/test/Microsoft.NET.TestFramework/Microsoft.NET.TestFramework.csproj index 4f704ecc5c53..7ef173306cc0 100644 --- a/test/Microsoft.NET.TestFramework/Microsoft.NET.TestFramework.csproj +++ b/test/Microsoft.NET.TestFramework/Microsoft.NET.TestFramework.csproj @@ -4,7 +4,6 @@ false -