diff --git a/src/DacpacTool/ActualConsole.cs b/src/DacpacTool/ActualConsole.cs index 381472c6..431375a9 100644 --- a/src/DacpacTool/ActualConsole.cs +++ b/src/DacpacTool/ActualConsole.cs @@ -2,7 +2,7 @@ namespace MSBuild.Sdk.SqlProj.DacpacTool { public class ActualConsole : IConsole { - public string ReadLine() + public string? ReadLine() { return Console.ReadLine(); } diff --git a/src/DacpacTool/BuildOptions.cs b/src/DacpacTool/BuildOptions.cs index 190473a1..ea245ba7 100644 --- a/src/DacpacTool/BuildOptions.cs +++ b/src/DacpacTool/BuildOptions.cs @@ -9,52 +9,52 @@ namespace MSBuild.Sdk.SqlProj.DacpacTool public class BuildOptions : BaseOptions { [CliOption(Description = "Name of the package", Required = true, Name = "--name", Alias = "-n")] - public string Name { get; set; } + public required string Name { get; set; } [CliOption(Description = "Version of the package", Required = false, Name = "--version", Alias = "-v")] - public string Version { get; set; } + public string? Version { get; set; } [CliOption(Description = "Filename of the output package", Required = false, Name = "--output", Alias = "-o")] - public FileInfo Output { get; set; } + public FileInfo? Output { get; set; } [CliOption(Description = "Target version of the model", Required = false, Name = "--sqlServerVersion", Alias = "-sv")] public SqlServerVersion SqlServerVersion { get; set; } = SqlServerVersion.Sql170; [CliOption(Description = "Text file listing all input files", Name = "--inputfile", Required = false, Alias = "-i")] - public FileInfo InputFile { get; set; } + public FileInfo? InputFile { get; set; } [CliOption(Description = "Reference(s) to include", Required = false, Name = "--reference", Alias = "-r")] - public string[] Reference { get; set; } + public string[] Reference { get; set; } = []; [CliOption(Description = "Build properties to be set on the model", Name = "--buildproperty", Required = false, Alias = "-bp")] - public string[] BuildProperty { get; set; } + public string[] BuildProperty { get; set; } = []; [CliOption(Description = "Deploy properties to be set for the create script", Name = "--deployproperty", Required = false, Alias = "-dp")] - public string[] DeployProperty { get; set; } + public string[] DeployProperty { get; set; } = []; [CliOption(Description = "SqlCmdVariable(s) to include", Name = "--sqlcmdvar", Required = false, Alias = "-sc")] - public string[] SqlCmdVar { get; set; } + public string[] SqlCmdVar { get; set; } = []; [CliOption(Description = "Filename of optional pre-deployment script", Name = "--predeploy", Required = false)] - public FileInfo PreDeploy { get; set; } + public FileInfo? PreDeploy { get; set; } [CliOption(Description = "Filename of optional pre-plan script", Name = "--preplan", Required = false)] - public FileInfo PrePlan { get; set; } + public FileInfo? PrePlan { get; set; } [CliOption(Description = "Filename of optional post-deployment script", Name = "--postdeploy", Required = false)] - public FileInfo PostDeploy { get; set; } + public FileInfo? PostDeploy { get; set; } [CliOption(Description = "Filename of optional refactor log script", Name = "--refactorlog", Required = false)] - public FileInfo RefactorLog { get; set; } + public FileInfo? RefactorLog { get; set; } [CliOption(Description = "Run static code analysis", Name = "--runcodeanalysis", Required = false, Alias = "-an")] public bool RunCodeAnalysis { get; set; } [CliOption(Description = "List of rules to suppress in format '-Microsoft.Rules.Data.SR0001;-Microsoft.Rules.Data.SR0008'", Name = "--codeanalysisrules", Required = false, Alias = "-ar")] - public string CodeAnalysisRules { get; set; } + public string? CodeAnalysisRules { get; set; } [CliOption(Description = "Custom code analysis rule assemblies to use", Name = "--codeanalysisassemblies", Required = false, Alias = "-aa")] - public FileInfo[] CodeAnalysisAssemblies { get; set; } + public FileInfo[] CodeAnalysisAssemblies { get; set; } = []; [CliOption(Description = "Treat T-SQL Warnings As Errors", Name = "--warnaserror", Required = false)] public bool WarnAsError { get; set; } @@ -63,22 +63,22 @@ public class BuildOptions : BaseOptions public bool GenerateCreateScript { get; set; } [CliOption(Description = "Name of the database to use in the generated create script", Name = "--targetdatabasename", Required = false, Alias = "-tdn")] - public string TargetDatabaseName { get; set; } + public string? TargetDatabaseName { get; set; } [CliOption(Description = "Warning(s) to suppress", Name = "--suppresswarnings", Required = false, Alias = "-spw")] - public string SuppressWarnings { get; set; } + public string? SuppressWarnings { get; set; } [CliOption(Description = "Filename for warning(s) to suppress for particular files", Name = "--suppresswarningslistfile", Required = false, Alias = "-spl")] - public FileInfo SuppressWarningsListFile { get; set; } + public FileInfo? SuppressWarningsListFile { get; set; } [CliOption(Description = "Generate ER diagram from the dacpac", Name = "--generateerdiagram", Required = false, Alias = "-ged")] public bool GenerateErDiagram { get; set; } [CliOption(Description = "JSON config file for ER diagram generation", Name = "--erdiagramconfig", Required = false, Alias = "-edc")] - public FileInfo[] ErDiagramConfig { get; set; } + public FileInfo[] ErDiagramConfig { get; set; } = []; [CliOption(Description = "Optional ProjectGuid", Name = "--projectguid", Required = false, Alias = "-pg")] - public string ProjectGuid { get; set; } + public string? ProjectGuid { get; set; } public async Task RunAsync() { diff --git a/src/DacpacTool/DacpacTool.csproj b/src/DacpacTool/DacpacTool.csproj index a7dbe344..5bc68d4f 100644 --- a/src/DacpacTool/DacpacTool.csproj +++ b/src/DacpacTool/DacpacTool.csproj @@ -9,7 +9,7 @@ true latest true - warnings + enable enable diff --git a/src/DacpacTool/DeployOptions.cs b/src/DacpacTool/DeployOptions.cs index f9be3f60..b204078e 100644 --- a/src/DacpacTool/DeployOptions.cs +++ b/src/DacpacTool/DeployOptions.cs @@ -9,28 +9,28 @@ internal sealed class DeployOptions : BaseOptions #pragma warning restore CA1812 // Avoid uninstantiated internal classes { [CliOption(Description = "Path to the .dacpac package to deploy", Required = true, Name = "--input", Alias = "-i")] - public FileInfo Input { get; set; } + public required FileInfo Input { get; set; } [CliOption(Description = "Name of the server to deploy the package to", Required = true, Name = "--targetServerName", Alias = "-tsn")] - public string TargetServerName { get; set; } + public required string TargetServerName { get; set; } [CliOption(Description = "Port number to connect on (leave blank for default)", Name = "--targetPort", Required = false, Alias = "-tprt")] public int? TargetPort { get; set; } [CliOption(Description = "Name of the database to deploy the package to", Required = true, Name = "--targetDatabaseName", Alias = "-tdn")] - public string TargetDatabaseName { get; set; } + public required string TargetDatabaseName { get; set; } [CliOption(Description = "Username used to connect to the target server, using SQL Server authentication", Required = false, Name = "--targetUser", Alias = "-tu")] - public string TargetUser { get; set; } + public string? TargetUser { get; set; } [CliOption(Description = "Password used to connect to the target server, using SQL Server authentication", Required = false, Name = "--targetPassword", Alias = "-tp")] - public string TargetPassword { get; set; } + public string? TargetPassword { get; set; } [CliOption(Description = "Properties used to control the deployment", Required = false, Name = "--property", Alias = "-p")] - public string[] Property { get; set; } + public string[] Property { get; set; } = []; [CliOption(Description = "SqlCmdVariable(s) and their associated values, separated by an equals sign", Name = "--sqlcmdvar", Required = false, Alias = "-sc")] - public string[] SqlCmdVar { get; set; } + public string[] SqlCmdVar { get; set; } = []; [CliOption(Description = "Whether to run pre- and postdeployment scripts from references", Name = "--runScriptsFromReferences", Required = false, Alias = "-sff")] public bool RunScriptsFromReferences { get; set; } diff --git a/src/DacpacTool/Extensions.cs b/src/DacpacTool/Extensions.cs index 9fceacb5..884a04e4 100644 --- a/src/DacpacTool/Extensions.cs +++ b/src/DacpacTool/Extensions.cs @@ -13,9 +13,9 @@ namespace MSBuild.Sdk.SqlProj.DacpacTool public static class Extensions #pragma warning restore CA1724 // Type names should not match namespaces { - static Type CustomSchemaDataType; + static Type CustomSchemaDataType = null!; - static MethodInfo SetMetadataMethod; + static MethodInfo SetMetadataMethod = null!; private static readonly Regex ExternalPartsRegex = new Regex(@"dbl=(?\w+)|dbv=(?\w+)|srv=(?\w+)", RegexOptions.CultureInvariant | RegexOptions.Compiled, TimeSpan.FromSeconds(1)); @@ -49,7 +49,7 @@ static Extensions() SetMetadataMethod = setMetadataMethod; } - public static string Format(this BatchErrorEventArgs args, string source) + public static string Format(this BatchErrorEventArgs args, string? source) { ArgumentNullException.ThrowIfNull(args); @@ -77,7 +77,7 @@ public static string Format(this BatchErrorEventArgs args, string source) return outputMessageBuilder.ToString(); } - public static string Format(this BatchParserExecutionErrorEventArgs args, string source) + public static string Format(this BatchParserExecutionErrorEventArgs args, string? source) { ArgumentNullException.ThrowIfNull(args); @@ -137,7 +137,7 @@ public static string Format(this DacModelException exception, string fileName) return stringBuilder.ToString().Trim(); } - public static string GetPreDeploymentScript(this DacPackage package) + public static string? GetPreDeploymentScript(this DacPackage package) { ArgumentNullException.ThrowIfNull(package); @@ -151,7 +151,7 @@ public static string GetPreDeploymentScript(this DacPackage package) return streamReader.ReadToEnd(); } - public static string GetPrePlanScript(this DacPackage package) + public static string? GetPrePlanScript(this DacPackage package) { ArgumentNullException.ThrowIfNull(package); @@ -165,7 +165,7 @@ public static string GetPrePlanScript(this DacPackage package) return streamReader.ReadToEnd(); } - public static string GetPostDeploymentScript(this DacPackage package) + public static string? GetPostDeploymentScript(this DacPackage package) { ArgumentNullException.ThrowIfNull(package); @@ -179,7 +179,7 @@ public static string GetPostDeploymentScript(this DacPackage package) return streamReader.ReadToEnd(); } - public static void AddReference(this TSqlModel model, string referencePath, string externalParts, bool suppressErrorsForMissingDependencies) + public static void AddReference(this TSqlModel model, string referencePath, string? externalParts, bool suppressErrorsForMissingDependencies) { ArgumentNullException.ThrowIfNull(model); ArgumentNullException.ThrowIfNull(referencePath); @@ -212,16 +212,16 @@ public static void AddReference(this TSqlModel model, string referencePath, stri AddCustomData(dataSchemaModel, customData); } - private static string ParseExternalParts(string externalParts) + private static string? ParseExternalParts(string externalParts) { return ParseExternalParts(externalParts, ExternalPartsRegex); } - private static string ParseExternalParts(string externalParts, Regex externalPartsRegex) + private static string? ParseExternalParts(string externalParts, Regex externalPartsRegex) { - string serverVariableName = null; - string databaseVariableName = null; - string databaseVariableLiteralValue = null; + string? serverVariableName = null; + string? databaseVariableName = null; + string? databaseVariableLiteralValue = null; // If there are '=' sign in argument assumes that this is formula, else assume that a single value passed and that it is database literal. if (externalParts.Contains('=', StringComparison.Ordinal)) @@ -274,7 +274,7 @@ private static string ParseExternalParts(string externalParts, Regex externalPar /// /// Cached method info for FileUtils.EnsureIsDelimited /// - private static MethodInfo _ensureIsDelimitedMethod; + private static MethodInfo? _ensureIsDelimitedMethod; /// /// This method found in Microsoft.Data.Tools.Utilities in class FileUtils. because of it is internal we do call through Reflection /// @@ -298,7 +298,7 @@ private static string EnsureIsDelimited(string name) throw new InvalidOperationException("Unable to find EnsureIsDelimited method in Microsoft.Data.Tools.Utilities assembly."); } - return (string)_ensureIsDelimitedMethod.Invoke(null, new object[]{ name }); + return (string)_ensureIsDelimitedMethod.Invoke(null, new object[]{ name })!; } public static IEnumerable GetReferencedDacPackages(this TSqlModel model) @@ -315,14 +315,14 @@ public static IEnumerable GetReferencedDacPackages(this TSqlModel model) throw new InvalidOperationException("Unable to find GetCustomData method on DataSchemaModel."); } - var references = (IEnumerable) getCustomDataMethod.Invoke(dataSchemaModel, new object[] { "Reference", "SqlSchema" }); + var references = (IEnumerable?) getCustomDataMethod.Invoke(dataSchemaModel, new object[] { "Reference", "SqlSchema" }); if (references == null) { return result; } - MethodInfo getMetadataMethod = null; + MethodInfo? getMetadataMethod = null; foreach (var reference in references) { if (getMetadataMethod == null) @@ -335,7 +335,7 @@ public static IEnumerable GetReferencedDacPackages(this TSqlModel model) throw new InvalidOperationException("Unable to find GetMetadata method on reference."); } - var fileName = (string)getMetadataMethod.Invoke(reference, new object[] { "FileName" }); + var fileName = (string?)getMetadataMethod.Invoke(reference, new object[] { "FileName" }); if (!string.IsNullOrEmpty(fileName)) { result.Add(fileName); @@ -408,7 +408,7 @@ public static IEnumerable GetModelValidationErrors(this TS } var result = new List(); - PropertyInfo documentProperty = null; + PropertyInfo? documentProperty = null; foreach (var modelValidationError in modelValidationErrors) { if (documentProperty == null) @@ -421,7 +421,8 @@ public static IEnumerable GetModelValidationErrors(this TS throw new InvalidOperationException("Unable to find Document property on model validation error."); } - var dacModelError = createDacModelErrorMethod.Invoke(service, new[] { modelValidationError }) as DacModelError; + var dacModelError = createDacModelErrorMethod.Invoke(service, new[] { modelValidationError }) as DacModelError + ?? throw new InvalidOperationException("Unable to create DacModelError for model validation error."); result.Add(new ModelValidationError(dacModelError, documentProperty.GetValue(modelValidationError) as string)); } diff --git a/src/DacpacTool/IConsole.cs b/src/DacpacTool/IConsole.cs index 4e2b0223..1cee55ea 100644 --- a/src/DacpacTool/IConsole.cs +++ b/src/DacpacTool/IConsole.cs @@ -3,6 +3,6 @@ namespace MSBuild.Sdk.SqlProj.DacpacTool public interface IConsole { void WriteLine(string value); - string ReadLine(); + string? ReadLine(); } } diff --git a/src/DacpacTool/InspectOptions.cs b/src/DacpacTool/InspectOptions.cs index 7cbf52e6..d794f0e8 100644 --- a/src/DacpacTool/InspectOptions.cs +++ b/src/DacpacTool/InspectOptions.cs @@ -7,13 +7,13 @@ namespace MSBuild.Sdk.SqlProj.DacpacTool public class InspectOptions : BaseOptions { [CliOption(Description = "Filename of optional pre-deployment script", Name = "--predeploy", Required = false)] - public FileInfo PreDeploy { get; set; } + public FileInfo? PreDeploy { get; set; } [CliOption(Description = "Filename of optional pre-plan script", Name = "--preplan", Required = false)] - public FileInfo PrePlan { get; set; } + public FileInfo? PrePlan { get; set; } [CliOption(Description = "Filename of optional post-deployment script", Name = "--postdeploy", Required = false)] - public FileInfo PostDeploy { get; set; } + public FileInfo? PostDeploy { get; set; } public int Run() { diff --git a/src/DacpacTool/ModelValidationError.cs b/src/DacpacTool/ModelValidationError.cs index b4a5ab39..dfe9e5ae 100644 --- a/src/DacpacTool/ModelValidationError.cs +++ b/src/DacpacTool/ModelValidationError.cs @@ -17,7 +17,7 @@ public class ModelValidationError private readonly int _errorCode; private readonly string _message; - public ModelValidationError(DacModelError modelError, string sourceName) + public ModelValidationError(DacModelError modelError, string? sourceName) { modelError = modelError ?? throw new ArgumentNullException(nameof(modelError)); _sourceName = string.IsNullOrEmpty(sourceName) ? diff --git a/src/DacpacTool/PackageAnalyzer.cs b/src/DacpacTool/PackageAnalyzer.cs index bb5c702a..ee3e1cd5 100644 --- a/src/DacpacTool/PackageAnalyzer.cs +++ b/src/DacpacTool/PackageAnalyzer.cs @@ -13,7 +13,7 @@ public sealed class PackageAnalyzer private readonly Dictionary> _suppressedProblemsByRule = new(StringComparer.Ordinal); private readonly char[] separator = new[] { ';' }; - public PackageAnalyzer(IConsole console, string rulesExpression) + public PackageAnalyzer(IConsole console, string? rulesExpression) { _console = console ?? throw new ArgumentNullException(nameof(console)); @@ -103,7 +103,7 @@ public void Analyze(TSqlModel model, FileInfo outputFile, FileInfo[] analyzers) #pragma warning restore CA1031 // Do not catch general exception types } - private void BuildRuleLists(string rulesExpression) + private void BuildRuleLists(string? rulesExpression) { if (!string.IsNullOrWhiteSpace(rulesExpression)) { diff --git a/src/DacpacTool/PackageBuilder.cs b/src/DacpacTool/PackageBuilder.cs index ba11f8a5..d9a14e89 100644 --- a/src/DacpacTool/PackageBuilder.cs +++ b/src/DacpacTool/PackageBuilder.cs @@ -1,4 +1,5 @@ -using System.Globalization; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.IO.Packaging; using System.Reflection; using System.Text; @@ -26,7 +27,7 @@ public void UsingVersion(SqlServerVersion version) _console.WriteLine($"Using SQL Server version {version}"); } - public void AddReference(string referenceFile, string externalParts = null, bool suppressErrorsForMissingDependencies = false) + public void AddReference(string referenceFile, string? externalParts = null, bool suppressErrorsForMissingDependencies = false) { // Ensure that the model has been created EnsureModelCreated(); @@ -89,7 +90,7 @@ public bool AddInputFile(FileInfo inputFile) } } - public void AddOutputArtifacts(FileInfo prePlanScript, FileInfo preDeployScript, FileInfo postDeployScript, Guid? projectGuid, FileInfo outputFile) + public void AddOutputArtifacts(FileInfo? prePlanScript, FileInfo? preDeployScript, FileInfo? postDeployScript, Guid? projectGuid, FileInfo outputFile) { ArgumentNullException.ThrowIfNull(outputFile); @@ -105,6 +106,7 @@ public void AddOutputArtifacts(FileInfo prePlanScript, FileInfo preDeployScript, } } + [MemberNotNull(nameof(Model))] public bool ValidateModel() { // Ensure that the model has been created @@ -161,7 +163,7 @@ void ProcessWarning(ModelValidationError modelError) } } - public void SaveToDisk(FileInfo outputFile, PackageOptions packageOptions = null) + public void SaveToDisk(FileInfo outputFile, PackageOptions? packageOptions = null) { ArgumentNullException.ThrowIfNull(outputFile); @@ -182,7 +184,7 @@ public void SaveToDisk(FileInfo outputFile, PackageOptions packageOptions = null DacPackageExtensions.BuildPackage(outputFile.FullName, Model, Metadata, packageOptions ?? new PackageOptions { }); } - public void SetMetadata(string name, string version) + public void SetMetadata(string name, string? version) { Metadata = new PackageMetadata { @@ -276,7 +278,7 @@ public void SetProperty(string key, string value) _ => throw new ArgumentException($"Unknown property with name {key}", nameof(key)) }; - PropertyInfo property = typeof(TSqlModelOptions).GetProperty(key, BindingFlags.Public | BindingFlags.Instance); + PropertyInfo? property = typeof(TSqlModelOptions).GetProperty(key, BindingFlags.Public | BindingFlags.Instance); if (property == null) { @@ -313,10 +315,11 @@ public void Dispose() } public TSqlModelOptions Options { get; } = new TSqlModelOptions(); - public TSqlModel Model { get; private set; } + public TSqlModel? Model { get; private set; } - public PackageMetadata Metadata { get; private set; } + public PackageMetadata? Metadata { get; private set; } + [MemberNotNull(nameof(Model))] private void EnsureModelCreated() { if (Model == null) @@ -325,6 +328,7 @@ private void EnsureModelCreated() } } + [MemberNotNull(nameof(Metadata))] private void EnsureMetadataCreated() { if (Metadata == null) @@ -341,7 +345,7 @@ private void EnsureModelValidated() } } - public void AddScript(FileInfo script, Package package, string path) + public void AddScript(FileInfo? script, Package package, string path) { ArgumentNullException.ThrowIfNull(package); @@ -385,7 +389,7 @@ public void AddWarningsToSuppress(string suppressionList) _suppressedWarnings.AddRange(ParseSuppressionList(suppressionList)); } - public void AddFileWarningsToSuppress(FileInfo inputFile, string suppressionList) + public void AddFileWarningsToSuppress(FileInfo inputFile, string? suppressionList) { ArgumentNullException.ThrowIfNull(inputFile); @@ -404,7 +408,7 @@ public void AddFileWarningsToSuppress(FileInfo inputFile, string suppressionList } - private static List ParseSuppressionList(string suppressionList) + private static List ParseSuppressionList(string? suppressionList) { var result = new List(); if (!string.IsNullOrEmpty(suppressionList)) diff --git a/src/DacpacTool/PackageDeployer.cs b/src/DacpacTool/PackageDeployer.cs index ede1783d..59704b52 100644 --- a/src/DacpacTool/PackageDeployer.cs +++ b/src/DacpacTool/PackageDeployer.cs @@ -8,7 +8,7 @@ namespace MSBuild.Sdk.SqlProj.DacpacTool public sealed class PackageDeployer : IBatchEventsHandler { private readonly IConsole _console; - private string _currentSource; + private string? _currentSource; public PackageDeployer(IConsole console) { @@ -30,7 +30,7 @@ public void UseTargetServerAndPort(string targetServer, int targetPort) ConnectionStringBuilder.DataSource = $"{targetServer},{targetPort}"; } - public void UseSqlAuthentication(string username, string password) + public void UseSqlAuthentication(string username, string? password) { ConnectionStringBuilder.UserID = username; if (string.IsNullOrWhiteSpace(password)) @@ -196,7 +196,7 @@ private Dictionary AddSqlCmdVariables(string targetDatabaseName) return result; } - private void HandleDacServicesMessage(object sender, DacMessageEventArgs args) + private void HandleDacServicesMessage(object? sender, DacMessageEventArgs args) { var message = args.Message; if (message.MessageType == DacMessageType.Message) diff --git a/src/DacpacTool/Program.cs b/src/DacpacTool/Program.cs index f3635303..a4e1f6c0 100644 --- a/src/DacpacTool/Program.cs +++ b/src/DacpacTool/Program.cs @@ -37,20 +37,17 @@ internal static async Task BuildDacpac(BuildOptions options) packageBuilder.SetMetadata(options.Name, options.Version); // Set properties on the model (if defined) - if (options.BuildProperty != null) + foreach (var propertyValue in options.BuildProperty) { - foreach (var propertyValue in options.BuildProperty) + string[] keyValuePair = propertyValue.Split('=', 2); + try { - string[] keyValuePair = propertyValue.Split('=', 2); - try - { - packageBuilder.SetProperty(keyValuePair[0], keyValuePair[1]); - } - catch (ArgumentException ex) - { - Console.WriteLine($"ERROR: {ex.Message}"); - return 1; - } + packageBuilder.SetProperty(keyValuePair[0], keyValuePair[1]); + } + catch (ArgumentException ex) + { + Console.WriteLine($"ERROR: {ex.Message}"); + return 1; } } @@ -58,33 +55,30 @@ internal static async Task BuildDacpac(BuildOptions options) packageBuilder.UsingVersion(options.SqlServerVersion); // Add references to the model - if (options.Reference != null) + foreach (var reference in options.Reference) { - foreach (var reference in options.Reference) + string[] referenceDetails = reference.Split(';', 3, StringSplitOptions.RemoveEmptyEntries); + if (referenceDetails.Length == 1) { - string[] referenceDetails = reference.Split(';', 3, StringSplitOptions.RemoveEmptyEntries); - if (referenceDetails.Length == 1) - { - packageBuilder.AddReference(referenceDetails[0]); - } - if (referenceDetails.Length == 2) - { - packageBuilder.AddReference(referenceDetails[0], referenceDetails[1]); - } - else + packageBuilder.AddReference(referenceDetails[0]); + } + if (referenceDetails.Length == 2) + { + packageBuilder.AddReference(referenceDetails[0], referenceDetails[1]); + } + else + { + if (!bool.TryParse(referenceDetails[2], out bool suppressErrorsForMissingDependencies)) { - if (!bool.TryParse(referenceDetails[2], out bool suppressErrorsForMissingDependencies)) - { - throw new ArgumentException( - $"Invalid Option for SuppressMissingDependenciesErrors on {referenceDetails[0]}, must be True/False"); - } - packageBuilder.AddReference(referenceDetails[0], referenceDetails[1], suppressErrorsForMissingDependencies); + throw new ArgumentException( + $"Invalid Option for SuppressMissingDependenciesErrors on {referenceDetails[0]}, must be True/False"); } + packageBuilder.AddReference(referenceDetails[0], referenceDetails[1], suppressErrorsForMissingDependencies); } } // Add SqlCmdVariables to the package (if defined) - if (options.SqlCmdVar != null) + if (options.SqlCmdVar.Length > 0) { packageBuilder.AddSqlCmdVariables(options.SqlCmdVar); } @@ -146,6 +140,7 @@ internal static async Task BuildDacpac(BuildOptions options) } // Save the package to disk + ArgumentNullException.ThrowIfNull(options.Output); packageBuilder.SaveToDisk(options.Output, new PackageOptions() { RefactorLogPath = options.RefactorLog?.FullName }); // Add pre-plan, predeployment, and postdeployment scripts and set the ProjectGuid in Origin.xml @@ -174,7 +169,7 @@ internal static async Task BuildDacpac(BuildOptions options) { var analyzer = new PackageAnalyzer(new ActualConsole(), options.CodeAnalysisRules); - analyzer.Analyze(packageBuilder.Model, options.Output, options.CodeAnalysisAssemblies ?? Array.Empty()); + analyzer.Analyze(packageBuilder.Model, options.Output, options.CodeAnalysisAssemblies); } if (options.GenerateErDiagram) @@ -224,20 +219,14 @@ internal static int DeployDacpac(DeployOptions options) { var deployer = new PackageDeployer(new ActualConsole()); - if (options.Property != null) - { - deployer.SetDeployProperties(options.Property); - } + deployer.SetDeployProperties(options.Property); deployer.UseEncrypt(options.Encrypt); - if (options.SqlCmdVar != null) + foreach (var sqlCmdVar in options.SqlCmdVar) { - foreach (var sqlCmdVar in options.SqlCmdVar) - { - string[] keyValuePair = sqlCmdVar.Split('=', 2); - deployer.SetSqlCmdVariable(keyValuePair[0], keyValuePair[1]); - } + string[] keyValuePair = sqlCmdVar.Split('=', 2); + deployer.SetSqlCmdVariable(keyValuePair[0], keyValuePair[1]); } if (options.TargetPort.HasValue) diff --git a/src/DacpacTool/PropertyParser.cs b/src/DacpacTool/PropertyParser.cs index b0646cda..32638856 100644 --- a/src/DacpacTool/PropertyParser.cs +++ b/src/DacpacTool/PropertyParser.cs @@ -30,15 +30,12 @@ public static DacDeployOptions ExtractDeployOptions(this BuildOptions options) var deployOptions = new DacDeployOptions(); - if (options.DeployProperty != null) - { - deployOptions.SetDeployProperties(options.DeployProperty); - } + deployOptions.SetDeployProperties(options.DeployProperty); return deployOptions; } - private static PropertyInfo GetDacDeployOptionsProperty(string propertyName) + private static PropertyInfo? GetDacDeployOptionsProperty(string propertyName) { var property = typeof(DacDeployOptions).GetProperties() .SingleOrDefault(p => string.Equals(p.Name, propertyName, StringComparison.OrdinalIgnoreCase)); @@ -104,7 +101,7 @@ public static DacAzureDatabaseSpecification ParseDatabaseSpecification(string va }; } - public static void SetDeployProperties(this DacDeployOptions deployOptions, string[] deployProperties, IConsole console = null) + public static void SetDeployProperties(this DacDeployOptions deployOptions, string[] deployProperties, IConsole? console = null) { foreach (var deployProperty in deployProperties.Where(p => string.IsNullOrWhiteSpace(p) == false)) { @@ -117,7 +114,7 @@ public static void SetDeployProperties(this DacDeployOptions deployOptions, stri { ObjectType[] o => string.Join(',', o), DacAzureDatabaseSpecification s => $"{s.Edition},{s.MaximumSize},{s.ServiceObjective}", - _ => propertyValue.ToString() + _ => $"{propertyValue}" }; console.WriteLine($"Setting property {databaseProperty.Name} to value {parsedValue}"); @@ -125,9 +122,9 @@ public static void SetDeployProperties(this DacDeployOptions deployOptions, stri } } - public static object SetDeployProperty(this DacDeployOptions deployOptions, string name, string value) + public static object? SetDeployProperty(this DacDeployOptions deployOptions, string name, string value) { - object propertyValue; + object? propertyValue; var property = GetDacDeployOptionsProperty(name); if (property == null) @@ -164,9 +161,9 @@ public static object SetDeployProperty(this DacDeployOptions deployOptions, stri return propertyValue; } - private static object StringToTypedValue(string stringValue, Type targetType) + private static object? StringToTypedValue(string stringValue, Type targetType) { - object result = null; + object? result = null; var converter = TypeDescriptor.GetConverter(targetType); diff --git a/src/DacpacTool/ScriptParser.cs b/src/DacpacTool/ScriptParser.cs index d857a729..48495ae9 100644 --- a/src/DacpacTool/ScriptParser.cs +++ b/src/DacpacTool/ScriptParser.cs @@ -28,7 +28,7 @@ private void Parse() } catch (BatchParserException ex) { - string mostRecentFile = _includedFileNames.LastOrDefault(); + string? mostRecentFile = _includedFileNames.LastOrDefault(); throw new InvalidOperationException( mostRecentFile == null ? ex.Message : diff --git a/test/DacpacTool.Tests/ExtensionsTest.cs b/test/DacpacTool.Tests/ExtensionsTest.cs index 2822b977..c2ca5a85 100644 --- a/test/DacpacTool.Tests/ExtensionsTest.cs +++ b/test/DacpacTool.Tests/ExtensionsTest.cs @@ -286,9 +286,9 @@ public void GetDeploymentScripts_WithEmbeddedScripts_ReturnScriptContents() using var package = DacPackage.Load(tempFile.FullName); - package.GetPrePlanScript().ShouldMatch(@"PRINT N'Pre plan'[\r\n]*PRINT N'Pre-plan include'[\r\n]*GO[\r\n]*"); - package.GetPreDeploymentScript().ShouldMatch(@"PRINT N'Pre deploy'[\r\n]*PRINT N'Script1.sql'[\r\n]*GO[\r\n]*"); - var postDeploymentScript = package.GetPostDeploymentScript(); + package.GetPrePlanScript()!.ShouldMatch(@"PRINT N'Pre plan'[\r\n]*PRINT N'Pre-plan include'[\r\n]*GO[\r\n]*"); + package.GetPreDeploymentScript()!.ShouldMatch(@"PRINT N'Pre deploy'[\r\n]*PRINT N'Script1.sql'[\r\n]*GO[\r\n]*"); + var postDeploymentScript = package.GetPostDeploymentScript()!; postDeploymentScript.ShouldContain("PRINT 'Inserting record into MyTable'"); postDeploymentScript.ShouldContain("ALTER ROLE db_datareader ADD MEMBER [DbReader];"); postDeploymentScript.ShouldEndWith($"{Environment.NewLine}GO{Environment.NewLine}"); diff --git a/test/DacpacTool.Tests/PackageBuilderTests.cs b/test/DacpacTool.Tests/PackageBuilderTests.cs index 0d6a773e..94888439 100644 --- a/test/DacpacTool.Tests/PackageBuilderTests.cs +++ b/test/DacpacTool.Tests/PackageBuilderTests.cs @@ -26,7 +26,7 @@ public void UsingVersion() packageBuilder.UsingVersion(SqlServerVersion.Sql170); // Assert - packageBuilder.Model.Version.ShouldBe(SqlServerVersion.Sql170); + packageBuilder.Model!.Version.ShouldBe(SqlServerVersion.Sql170); } [TestMethod] @@ -52,7 +52,7 @@ public void AddInputFile_FileExists() // Assert result.ShouldBe(true); - packageBuilder.Model.GetObject(Table.TypeClass, new ObjectIdentifier("dbo", "MyTable"), DacQueryScopes.Default).ShouldNotBeNull(); + packageBuilder.Model!.GetObject(Table.TypeClass, new ObjectIdentifier("dbo", "MyTable"), DacQueryScopes.Default).ShouldNotBeNull(); } [TestMethod] @@ -118,7 +118,7 @@ public void AddReference_FileExists() packageBuilder.AddReference(reference); // Assert - packageBuilder.Model.GetObject(Procedure.TypeClass, new ObjectIdentifier("dbo", "MyStoredProcedure"), DacQueryScopes.All).ShouldNotBeNull(); + packageBuilder.Model!.GetObject(Procedure.TypeClass, new ObjectIdentifier("dbo", "MyStoredProcedure"), DacQueryScopes.All).ShouldNotBeNull(); // Cleanup File.Delete(reference); @@ -139,7 +139,7 @@ public void AddReference_DifferentDatabase() // Assert var referencingStoredProcedure = "CREATE PROCEDURE [MyOtherStoredProcedure] AS BEGIN EXEC [SomeOtherDatabase].[dbo].[MyStoredProcedure] END"; - packageBuilder.Model.AddObjects(referencingStoredProcedure); + packageBuilder.Model!.AddObjects(referencingStoredProcedure); packageBuilder.Model.Validate().ShouldBeEmpty(); // Cleanup @@ -163,7 +163,7 @@ public void AddReference_CircularReferenceCanLoadWhenSuppressed() // Act packageBuilder.AddReference(model1File, "Model1", true); - packageBuilder.Model.AddObjects($"CREATE VIEW [View2] AS SELECT Col2 FROM [Model1].[dbo].[View1]"); + packageBuilder.Model!.AddObjects($"CREATE VIEW [View2] AS SELECT Col2 FROM [Model1].[dbo].[View1]"); DacPackageExtensions.BuildPackage(model2File, packageBuilder.Model, new PackageMetadata()); // Assert Does not throw @@ -191,7 +191,7 @@ public void AddReference_CircularReferenceThrowsWhenNotSuppressed() // Act packageBuilder.AddReference(model1File, "Model1", false); - packageBuilder.Model.AddObjects($"CREATE VIEW [View2] AS SELECT Col2 FROM [Model1].[dbo].[View1]"); + packageBuilder.Model!.AddObjects($"CREATE VIEW [View2] AS SELECT Col2 FROM [Model1].[dbo].[View1]"); DacPackageExtensions.BuildPackage(model2File, packageBuilder.Model, new PackageMetadata()); // Assert @@ -643,7 +643,7 @@ public void SetMetadata() packageBuilder.SetMetadata("MyPackage", "1.0.0.0"); // Assert - packageBuilder.Metadata.Name.ShouldBe("MyPackage"); + packageBuilder.Metadata!.Name.ShouldBe("MyPackage"); packageBuilder.Metadata.Version.ShouldBe("1.0.0.0"); } @@ -654,7 +654,7 @@ public void ValidateModel_ValidModel() var packageBuilder = new PackageBuilder(new TestConsole()); packageBuilder.UsingVersion(SqlServerVersion.Sql170); packageBuilder.SetMetadata("MyPackage", "1.0.0.0"); - packageBuilder.Model.AddObjects("CREATE PROCEDURE [csp_Test] AS BEGIN SELECT 1 END"); + packageBuilder.Model!.AddObjects("CREATE PROCEDURE [csp_Test] AS BEGIN SELECT 1 END"); // Act bool result = packageBuilder.ValidateModel(); @@ -670,7 +670,7 @@ public void ValidateModel_Warnings() var packageBuilder = new PackageBuilder(new TestConsole()); packageBuilder.UsingVersion(SqlServerVersion.Sql170); packageBuilder.SetMetadata("MyPackage", "1.0.0.0"); - packageBuilder.Model.AddObjects("CREATE PROCEDURE [csp_Test] AS BEGIN SELECT * FROM [dbo].[MyTable] END"); + packageBuilder.Model!.AddObjects("CREATE PROCEDURE [csp_Test] AS BEGIN SELECT * FROM [dbo].[MyTable] END"); // Act bool result = packageBuilder.ValidateModel(); @@ -687,7 +687,7 @@ public void ValidateModel_WarningsAsErrors() packageBuilder.UsingVersion(SqlServerVersion.Sql170); packageBuilder.TreatTSqlWarningsAsErrors = true; packageBuilder.SetMetadata("MyPackage", "1.0.0.0"); - packageBuilder.Model.AddObjects("CREATE PROCEDURE [csp_Test] AS BEGIN SELECT * FROM [dbo].[MyTable] END"); + packageBuilder.Model!.AddObjects("CREATE PROCEDURE [csp_Test] AS BEGIN SELECT * FROM [dbo].[MyTable] END"); // Act bool result = packageBuilder.ValidateModel(); @@ -706,7 +706,7 @@ public void ValidateModel_WarningsAsErrorsSuppressGlobal() packageBuilder.TreatTSqlWarningsAsErrors = true; packageBuilder.AddWarningsToSuppress("71502"); packageBuilder.SetMetadata("MyPackage", "1.0.0.0"); - packageBuilder.Model.AddObjects("CREATE PROCEDURE [csp_Test] AS BEGIN SELECT * FROM [dbo].[MyTable] END"); + packageBuilder.Model!.AddObjects("CREATE PROCEDURE [csp_Test] AS BEGIN SELECT * FROM [dbo].[MyTable] END"); // Act bool result = packageBuilder.ValidateModel(); @@ -744,7 +744,7 @@ public void ValidateModel_Errors() var packageBuilder = new PackageBuilder(new TestConsole()); packageBuilder.UsingVersion(SqlServerVersion.Sql170); packageBuilder.SetMetadata("MyPackage", "1.0.0.0"); - packageBuilder.Model.AddObjects("CREATE PROCEDURE [csp_Test] @p_Parameter [dbo].[CustomType] AS BEGIN SELECT 1 END"); + packageBuilder.Model!.AddObjects("CREATE PROCEDURE [csp_Test] @p_Parameter [dbo].[CustomType] AS BEGIN SELECT 1 END"); // Act bool result = packageBuilder.ValidateModel(); @@ -862,7 +862,7 @@ public void GenerateCreateScript_NoName() packageBuilder.SetMetadata(null, "1.0.0.0"); packageBuilder.ValidateModel(); - var buildOptions = new BuildOptions(); + var buildOptions = new BuildOptions { Name = "MyPackage" }; buildOptions.Output = tempFile; // Act diff --git a/test/DacpacTool.Tests/PropertyParserTest.cs b/test/DacpacTool.Tests/PropertyParserTest.cs index efd9e4e7..aa84977f 100644 --- a/test/DacpacTool.Tests/PropertyParserTest.cs +++ b/test/DacpacTool.Tests/PropertyParserTest.cs @@ -12,7 +12,7 @@ public class PropertyParserTest public void ExtractDeployOptions_WithBooleanProperties_ShouldParse() { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { "CreateNewDatabase=True", "IgnoreAuthorizer=True" @@ -30,7 +30,7 @@ public void ExtractDeployOptions_WithBooleanProperties_ShouldParse() public void ExtractDeployOptions_WithIntegerProperty_ShouldParse() { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] { "CommandTimeout=200" } }; + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { "CommandTimeout=200" } }; // Act var deployOptions = buildOptions.ExtractDeployOptions(); @@ -45,6 +45,7 @@ public void ExtractDeployOptions_WithCaseInsensitivePropertyNames_ShouldParse() // Arrange var buildOptions = new BuildOptions { + Name = "MyPackage", DeployProperty = new[] { "createNewDatabase=True", @@ -68,7 +69,7 @@ public void ExtractDeployOptions_WithCaseInsensitivePropertyNames_ShouldParse() public void ExtractDeployOptions_WithObjectTypesProperties_ShouldParse() { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { $"ExcludeObjectTypes={ObjectType.Audits},{ObjectType.Endpoints},{ObjectType.Queues}", $"DoNotDropObjectTypes={ObjectType.Certificates},{ObjectType.Contracts}" @@ -94,7 +95,7 @@ public void ExtractDeployOptions_WithObjectTypesProperties_ShouldParse() public void ExtractDeployOptions_WithIncorrectObjectTypesProperty_ShouldThrowException(string property) { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] { property } }; + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { property } }; // Act Action action = () => buildOptions.ExtractDeployOptions(); @@ -107,7 +108,7 @@ public void ExtractDeployOptions_WithIncorrectObjectTypesProperty_ShouldThrowExc public void ExtractDeployOptions_WithDacAzureDatabaseSpecificationProperty_ShouldParse() { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] { $"DatabaseSpecification={DacAzureEdition.DataWarehouse},20,S3" } }; + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { $"DatabaseSpecification={DacAzureEdition.DataWarehouse},20,S3" } }; // Act var deployOptions = buildOptions.ExtractDeployOptions(); @@ -127,7 +128,7 @@ public void ExtractDeployOptions_WithDacAzureDatabaseSpecificationProperty_Shoul public void ExtractDeployOptions_WithIncorrectDacAzureDatabaseSpecificationProperty_ShouldThrowException(string propertyValue, string exceptionMessage) { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] { $"DatabaseSpecification={propertyValue}" } }; + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { $"DatabaseSpecification={propertyValue}" } }; // Act Action action = () => buildOptions.ExtractDeployOptions(); @@ -140,7 +141,7 @@ public void ExtractDeployOptions_WithIncorrectDacAzureDatabaseSpecificationPrope public void ExtractDeployOptions_WithIncorrectIntegerProperty_ShouldThrowException() { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] { "CommandTimeout=WrongValue" } }; + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { "CommandTimeout=WrongValue" } }; // Act Action action = () => buildOptions.ExtractDeployOptions(); @@ -153,7 +154,7 @@ public void ExtractDeployOptions_WithIncorrectIntegerProperty_ShouldThrowExcepti public void ExtractDeployOptions_WithIncorrectBooleanProperty_ShouldThrowException() { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] { "CreateNewDatabase=WrongValue" } }; + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { "CreateNewDatabase=WrongValue" } }; // Act Action action = () => buildOptions.ExtractDeployOptions(); @@ -169,7 +170,7 @@ public void ExtractDeployOptions_WithIncorrectBooleanProperty_ShouldThrowExcepti public void ExtractDeployOptions_WithWronglyFormattedOrhUnknownProperty_ShouldThrowException(string property, Type exceptionType) { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] { property } }; + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { property } }; // Act Action action = () => buildOptions.ExtractDeployOptions(); @@ -185,7 +186,7 @@ public void ExtractDeployOptions_WithWronglyFormattedOrhUnknownProperty_ShouldTh public void ExtractDeployOptions_WithNullOrEmptyProperty_ShouldNotThrowException(string property) { // Arrange - var buildOptions = new BuildOptions { DeployProperty = new[] { property } }; + var buildOptions = new BuildOptions { Name = "MyPackage", DeployProperty = new[] { property } }; // Act Action action = () => buildOptions.ExtractDeployOptions(); diff --git a/test/IntegrationTests/ReferencedDeploymentScriptTests.cs b/test/IntegrationTests/ReferencedDeploymentScriptTests.cs index 1db4458d..432e5a95 100644 --- a/test/IntegrationTests/ReferencedDeploymentScriptTests.cs +++ b/test/IntegrationTests/ReferencedDeploymentScriptTests.cs @@ -130,7 +130,7 @@ private static FileInfo BuildPackage(DirectoryInfo directory, string name, strin builder.AddReference(reference.FullName); } - builder.Model.AddObjects(sql); + builder.Model!.AddObjects(sql); builder.ValidateModel().ShouldBeTrue(); var package = new FileInfo(Path.Combine(directory.FullName, $"{name}.dacpac")); builder.SaveToDisk(package);