diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json
new file mode 100644
index 0000000..da200cd
--- /dev/null
+++ b/.config/dotnet-tools.json
@@ -0,0 +1,12 @@
+{
+ "version": 1,
+ "isRoot": true,
+ "tools": {
+ "cake.tool": {
+ "version": "4.0.0",
+ "commands": [
+ "dotnet-cake"
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..6a0c63d
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,91 @@
+# EditorConfig is awesome: http://EditorConfig.org
+
+# top-most EditorConfig file
+root = true
+
+# indentation
+[*]
+indent_style = space
+indent_size = 4
+trim_trailing_whitespace = true
+
+# Code files
+[*.{cs,csx,vb,vbx}]
+indent_size = 4
+insert_final_newline = true
+charset = utf-8-bom
+
+# Xml project files
+[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
+indent_size = 2
+
+# Xml config files
+[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
+indent_size = 2
+
+# JSON files
+[*.json]
+indent_size = 2
+
+# YML files
+[*.yml]
+indent_size = 2
+
+# Dotnet code style settings:
+[*.{cs,vb}]
+# Sort using and Import directives with System.* appearing first
+dotnet_sort_system_directives_first = true
+# Avoid "this." and "Me." if not necessary
+dotnet_style_qualification_for_field = false:suggestion
+dotnet_style_qualification_for_property = false:suggestion
+dotnet_style_qualification_for_method = false:suggestion
+dotnet_style_qualification_for_event = false:suggestion
+
+# Use language keywords instead of framework type names for type references
+dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
+dotnet_style_predefined_type_for_member_access = true:suggestion
+
+# Suggest more modern language features when available
+dotnet_style_object_initializer = true:suggestion
+dotnet_style_collection_initializer = true:suggestion
+dotnet_style_coalesce_expression = true:suggestion
+dotnet_style_null_propagation = true:suggestion
+dotnet_style_explicit_tuple_names = true:suggestion
+
+# CSharp code style settings:
+[*.cs]
+# Prefer "var" everywhere
+csharp_style_var_for_built_in_types = true:suggestion
+csharp_style_var_when_type_is_apparent = true:suggestion
+csharp_style_var_elsewhere = true:suggestion
+
+# Prefer method-like constructs to have a block body
+csharp_style_expression_bodied_methods = false:none
+csharp_style_expression_bodied_constructors = false:none
+csharp_style_expression_bodied_operators = false:none
+
+# Prefer property-like constructs to have an expression-body
+csharp_style_expression_bodied_properties = true:none
+csharp_style_expression_bodied_indexers = true:none
+csharp_style_expression_bodied_accessors = true:none
+
+# Suggest more modern language features when available
+csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
+csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
+csharp_style_inlined_variable_declaration = true:suggestion
+csharp_style_throw_expression = true:suggestion
+csharp_style_conditional_delegate_call = true:suggestion
+
+# Newline settings
+csharp_new_line_before_open_brace = all
+csharp_new_line_before_else = true
+csharp_new_line_before_catch = true
+csharp_new_line_before_finally = true
+csharp_new_line_before_members_in_object_initializers = true
+csharp_new_line_before_members_in_anonymous_types = true
+
+# Stylecop
+dotnet_diagnostic.SA1101.severity = none
+dotnet_diagnostic.SA1309.severity = none
+dotnet_diagnostic.SA1600.severity = none
+dotnet_diagnostic.SA1633.severity = none
\ No newline at end of file
diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 0000000..0cc4f21
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,16 @@
+
+
+
+ latest
+ enable
+ true
+
+ $(NoWarn);1701;1702;1591
+ true
+
+
+
+
+
+
+
diff --git a/ReleaseNotes.md b/ReleaseNotes.md
index aebe593..3bd58fa 100644
--- a/ReleaseNotes.md
+++ b/ReleaseNotes.md
@@ -1,3 +1,7 @@
+### New in 2.0.0 (Released 2021/04/29)
+* [Improvement] Supports Cake 4.0
+* [Improvement] Changed .NET targets to .NET 6, .NET 7 and .NET 8
+
### New in 1.0.2 (Released 2021/04/29)
* [Improvement] Loading native libs for NET 4.6.1
diff --git a/appveyor.yml b/appveyor.yml
index 93c40af..549cc14 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -1,12 +1,14 @@
-# Build script
+# Initalize
init:
- - git config --global core.autocrlf true
-
-image: Visual Studio 2019
+ - git config --global core.autocrlf false
+
+install:
+ - sh: curl -sSL https://dot.net/v1/dotnet-install.sh | sudo bash /dev/stdin --install-dir /usr/share/dotnet --version 8.0.100
+
+image: Ubuntu
-# Build script
build_script:
- - cmd: powershell -NoProfile -ExecutionPolicy unrestricted -Command .\build.ps1 -Target "AppVeyor"
+ - sh: ./build.sh --target="appveyor"
# Tests
test: off
@@ -17,3 +19,5 @@ branches:
only:
- master
- develop
+
+skip_tags: true
\ No newline at end of file
diff --git a/build.cake b/build.cake
index ffe9df6..9be94b0 100644
--- a/build.cake
+++ b/build.cake
@@ -21,12 +21,19 @@ var projectNames = new List()
"Cake.SqlTools"
};
-
-
+Task("Clean")
+ .Does(() =>
+{
+ EnsureDirectoryDoesNotExist(buildResultDir, new DeleteDirectorySettings {
+ Recursive = true,
+ Force = true
+ });
+ CreateDirectory(buildResultDir);
+});
///////////////////////////////////////////////////////////////////////////////
// LOAD
///////////////////////////////////////////////////////////////////////////////
-#load "./build/scripts/load.cake"
\ No newline at end of file
+#load "./build/scripts/load.cake"
diff --git a/build.ps1 b/build.ps1
index 1fd7a95..21821d2 100644
--- a/build.ps1
+++ b/build.ps1
@@ -1,244 +1,13 @@
-<#
-.SYNOPSIS
-This is a Powershell script to bootstrap a Cake build.
-.DESCRIPTION
-This Powershell script will download NuGet if missing, restore NuGet tools (including Cake)
-and execute your Cake build script with the parameters you provide.
-.LINK
-https://cakebuild.net
+$ErrorActionPreference = 'Stop'
-.PARAMETER Script
-The build script file to run.
-.PARAMETER Tools
-The tools directory to use.
+Set-Location -LiteralPath $PSScriptRoot
-.PARAMETER Target
-The build script target to run.
-.PARAMETER Configuration
-The build configuration to use.
+$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = '1'
+$env:DOTNET_CLI_TELEMETRY_OPTOUT = '1'
+$env:DOTNET_NOLOGO = '1'
-.PARAMETER Verbosity
-Specifies the amount of information to be displayed.
-.PARAMETER WhatIf
-Performs a dry run of the build script.
-No tasks will be executed.
+dotnet tool restore
+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
-.PARAMETER ScriptArgs
-Remaining arguments are added here.
-#>
-
-
-
-
-
-###########################################################################
-# Define Parameters
-###########################################################################
-
-[CmdletBinding()]
-Param(
- [string]$Script = "build.cake",
- [string]$Tools,
-
- [string]$Target = "Default",
- [ValidateSet("Release", "Debug")]
- [string]$Configuration = "Release",
- [ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")]
-
- [string]$Verbosity = "Verbose",
- [switch]$WhatIf,
-
- [Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)]
- [string[]]$ScriptArgs
-)
-
-
-
-$CakeVersion = "1.0.0"
-$DotNetChannel = "Current";
-$DotNetVersion = "5.0.103";
-$DotNetInstallerUri = "https://dot.net/v1/dotnet-install.ps1";
-$NugetUrl = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
-
-# Temporarily skip verification and opt-in to new in-proc NuGet
-$ENV:CAKE_SETTINGS_SKIPPACKAGEVERSIONCHECK='true'
-
-# Use TLS 1.2
-[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
-
-
-
-
-
-###########################################################################
-# Define Paths
-###########################################################################
-
-# Get Script root
-$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
-
-# Find tools
-if($Tools)
-{
- # Parameter
- Write-Verbose -Message "Using tools parameter"
- $TOOLS_DIR = Join-Path $PSScriptRoot $Tools
-}
-elseif (Test-Path "C:/Tools/")
-{
- # Shared location
- Write-Verbose -Message "Using shared tools"
- $TOOLS_DIR = "C:/Tools"
-}
-else
-{
- # Local path
- Write-Verbose -Message "Using local tools"
- $TOOLS_DIR = Join-Path $PSScriptRoot "tools"
-}
-
-# Make sure tools folder exists
-if (!(Test-Path $TOOLS_DIR))
-{
- Write-Verbose "Creating tools directory..."
- New-Item -Path $TOOLS_DIR -Type directory | out-null
-}
-
-
-
-# Define directories
-$ADDINS_DIR = Join-Path $TOOLS_DIR "/Addins"
-$MODULES_DIR = Join-Path $TOOLS_DIR "/Modules"
-
-Write-Verbose -Message $ADDINS_DIR
-
-# Save paths to environment for use in child processes
-$ENV:CAKE_PATHS_TOOLS = $TOOLS_DIR
-$ENV:CAKE_PATHS_ADDINS = $ADDINS_DIR
-$ENV:CAKE_PATHS_MODULES = $MODULES_DIR
-
-
-
-
-
-###########################################################################
-# INSTALL .NET CORE CLI
-###########################################################################
-
-Function Remove-PathVariable([string]$VariableToRemove)
-{
- $SplitChar = ';'
- if ($IsMacOS -or $IsLinux) {
- $SplitChar = ':'
- }
-
- $path = [Environment]::GetEnvironmentVariable("PATH", "User")
- if ($path -ne $null)
- {
- $newItems = $path.Split($SplitChar, [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { "$($_)" -inotlike $VariableToRemove }
- [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join($SplitChar, $newItems), "User")
- }
-
- $path = [Environment]::GetEnvironmentVariable("PATH", "Process")
- if ($path -ne $null)
- {
- $newItems = $path.Split($SplitChar, [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { "$($_)" -inotlike $VariableToRemove }
- [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join($SplitChar, $newItems), "Process")
- }
-}
-
-
-
-# Get .NET Core CLI path if installed.
-$FoundDotNetCliVersion = $null;
-
-if (Get-Command dotnet -ErrorAction SilentlyContinue)
-{
- $FoundDotNetCliVersion = dotnet --version;
-}
-
-if($FoundDotNetCliVersion -ne $DotNetVersion)
-{
- $InstallPath = Join-Path $TOOLS_DIR "DotNet"
- if (!(Test-Path $InstallPath)) {
- New-Item -Path $InstallPath -ItemType Directory -Force | Out-Null;
- }
-
- if ($IsMacOS -or $IsLinux) {
- $ScriptPath = Join-Path $InstallPath 'dotnet-install.sh'
- (New-Object System.Net.WebClient).DownloadFile($DotNetUnixInstallerUri, $ScriptPath);
- & bash $ScriptPath --version "$DotNetVersion" --install-dir "$InstallPath" --channel "$DotNetChannel" --no-path
-
- Remove-PathVariable "$InstallPath"
- $env:PATH = "$($InstallPath):$env:PATH"
- }
- else {
- $ScriptPath = Join-Path $InstallPath 'dotnet-install.ps1'
- (New-Object System.Net.WebClient).DownloadFile($DotNetInstallerUri, $ScriptPath);
- & $ScriptPath -Channel $DotNetChannel -Version $DotNetVersion -InstallDir $InstallPath;
-
- Remove-PathVariable "$InstallPath"
- $env:PATH = "$InstallPath;$env:PATH"
- }
- $env:DOTNET_ROOT=$InstallPath
-}
-
-
-
-
-
-###########################################################################
-# INSTALL NUGET
-###########################################################################
-
-# Make sure nuget.exe exists.
-$NugetPath = Join-Path $TOOLS_DIR "nuget.exe"
-
-if (!(Test-Path $NugetPath))
-{
- Write-Host "Downloading NuGet.exe..."
- (New-Object System.Net.WebClient).DownloadFile($NugetUrl, $NugetPath);
-}
-
-
-
-
-
-###########################################################################
-# INSTALL CAKE
-###########################################################################
-
-# Make sure Cake has been installed.
-$CakePath = Join-Path $TOOLS_DIR "Cake.$CakeVersion/Cake.exe"
-
-if (!(Test-Path $CakePath))
-{
- Write-Host "Installing Cake..."
- Invoke-Expression "&`"$NugetPath`" install Cake -Version $CakeVersion -OutputDirectory `"$TOOLS_DIR`"" | Out-Null;
-
- if ($LASTEXITCODE -ne 0)
- {
- Throw "An error occured while restoring Cake from NuGet."
- }
-}
-
-
-
-
-###########################################################################
-# RUN BUILD SCRIPT
-###########################################################################
-
-# Build the argument list.
-$Arguments = @{
- target=$Target;
- configuration=$Configuration;
- verbosity=$Verbosity;
- dryrun=$WhatIf;
-}.GetEnumerator() | %{"--{0}=`"{1}`"" -f $_.key, $_.value };
-
-# Start Cake
-Write-Host "Running build script..."
-Invoke-Expression "& `"$CakePath`" `"$Script`" $Arguments $ScriptArgs"
-
-exit $LASTEXITCODE
\ No newline at end of file
+dotnet cake @args
+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
diff --git a/build.sh b/build.sh
new file mode 100755
index 0000000..31be886
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+set -euox pipefail
+
+cd "$(dirname "${BASH_SOURCE[0]}")"
+
+export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
+export DOTNET_CLI_TELEMETRY_OPTOUT=1
+export DOTNET_NOLOGO=1
+
+dotnet tool restore
+
+dotnet cake "$@"
diff --git a/build/scripts/appveyor.cake b/build/scripts/appveyor.cake
index b88f669..c910436 100644
--- a/build/scripts/appveyor.cake
+++ b/build/scripts/appveyor.cake
@@ -9,12 +9,10 @@ Task("Update-AppVeyor-Build-Number")
AppVeyor.UpdateBuildVersion(semVersion);
});
-
-
Task("Upload-AppVeyor-Artifacts")
- .IsDependentOn("Zip-Files")
+ .IsDependentOn("Build")
.WithCriteria(() => isRunningOnAppVeyor)
.Does(() =>
{
- AppVeyor.UploadArtifact(zipPackage);
+ AppVeyor.UploadArtifact(packageFileName);
});
\ No newline at end of file
diff --git a/build/scripts/build.cake b/build/scripts/build.cake
index 73971e2..e6bdbde 100644
--- a/build/scripts/build.cake
+++ b/build/scripts/build.cake
@@ -2,53 +2,24 @@
// BUILD
///////////////////////////////////////////////////////////////////////////////
-Task("Patch-Assembly-Info")
- .IsDependentOn("Restore-Nuget-Packages")
- .Does(() =>
-{
- // Create Solution Info
- var file = "./src/SolutionInfo.cs";
-
- CreateAssemblyInfo(file, new AssemblyInfoSettings
- {
- Version = version,
- FileVersion = version,
- InformationalVersion = semVersion,
- Copyright = "Copyright (c) 2015 - " + DateTime.Now.Year.ToString() + " " + copyright
- });
-
-
-
- // Copy Solution Info
- foreach (string project in projectDirs)
- {
- CopyFileToDirectory(file, project + "/Properties");
- }
-});
-
-
-
Task("Build")
- .IsDependentOn("Patch-Assembly-Info")
+ .IsDependentOn("Clean")
.Does(() =>
{
Information("Building {0}", solution);
- // Check Logger folder
- if (!DirectoryExists(loggerResultsDir))
- {
- CreateDirectory(loggerResultsDir);
- }
-
// Create build settings
- var buildSettings = new DotNetCoreMSBuildSettings
- {
- Verbosity = DotNetCoreVerbosity.Normal,
- TreatAllWarningsAs = Cake.Common.Tools.DotNetCore.MSBuild.MSBuildTreatAllWarningsAs.Error,
-
- MaxCpuCount = 3
+ var buildSettings = new DotNetMSBuildSettings
+ {
+ MaxCpuCount = 3,
+ Version = version,
+ FileVersion = version,
+ InformationalVersion = semVersion,
+ PackageVersion = version
};
+ buildSettings.WithProperty("PackageOutputPath", nugetDir.FullPath);
+
// Add Logger
buildSettings.AddFileLogger(new MSBuildFileLoggerSettings
{
@@ -61,19 +32,12 @@ Task("Build")
ForceNoAlign = true,
HideItemAndPropertyList = true,
- Verbosity = DotNetCoreVerbosity.Minimal
+ Verbosity = DotNetVerbosity.Minimal
});
-
-
- // Build Solution
- Information("Building {0}", solution);
-
- DotNetCoreBuild(solution, new DotNetCoreBuildSettings
+ DotNetBuild(solution, new DotNetBuildSettings
{
Configuration = configuration,
-
- NoRestore = true,
MSBuildSettings = buildSettings
});
})
@@ -132,4 +96,5 @@ Task("Build")
}
throw exception;
-});
\ No newline at end of file
+});
+
diff --git a/build/scripts/imports.cake b/build/scripts/imports.cake
index c1eabe0..23c3d4c 100644
--- a/build/scripts/imports.cake
+++ b/build/scripts/imports.cake
@@ -2,8 +2,8 @@
// IMPORTS
//////////////////////////////////////////////////////////////////////
-#addin nuget:?package=Cake.FileHelpers&version=3.3.0
-#addin nuget:?package=Cake.Slack&version=1.0.0
+#addin nuget:?package=Cake.FileHelpers&version=6.1.3
+#addin nuget:?package=Cake.Slack&version=2.0.0
#tool nuget:?package=ReportUnit&version=1.2.1
diff --git a/build/scripts/load.cake b/build/scripts/load.cake
index 44e2f67..20355e9 100644
--- a/build/scripts/load.cake
+++ b/build/scripts/load.cake
@@ -4,11 +4,8 @@
#load "./variables.cake"
#load "./setup.cake"
-#load "./prepare.cake"
#load "./loggers.cake"
#load "./build.cake"
-#load "./test.cake"
-#load "./package.cake"
#load "./publish.cake"
#load "./appveyor.cake"
#load "./message.cake"
diff --git a/build/scripts/loggers.cake b/build/scripts/loggers.cake
index 11cb7de..8513d43 100644
--- a/build/scripts/loggers.cake
+++ b/build/scripts/loggers.cake
@@ -1,259 +1,3 @@
-///////////////////////////////////////////////////////////////////////////////
-// JUNIT
-///////////////////////////////////////////////////////////////////////////////
-
-using System.Xml.Linq;
-
-public IList GetJunitResults(string filePath)
-{
- // Load Document
- XDocument doc = XDocument.Load(filePath);
-
-
-
- // Get Suites
- IList lstSuite = doc.Descendants("testsuite").ToList();
- IList results = new List();
-
- foreach (XElement itmSuite in lstSuite)
- {
- XAttribute package = itmSuite.Attribute("package");
- XAttribute name = itmSuite.Attribute("name");
- XAttribute time = itmSuite.Attribute("time");
-
- JunitSuite suite = new JunitSuite()
- {
- Package = package != null ? package.Value : "",
- Name = name != null ? name.Value : "",
- Time = time != null ? Convert.ToInt32(time.Value) : 0,
-
- Cases = new List()
- };
-
-
-
- // Get Name
- string prefix = GetPrefix(suite.Name);
-
- if (!String.IsNullOrEmpty(prefix))
- {
- suite.Name = suite.Name.Replace(prefix, "");
- }
-
- suite.Name = suite.Name.Replace(@"\", "/");
-
-
-
- // Get Cases
- IList lstCase = itmSuite.Descendants("testcase").ToList();
-
- foreach (XElement itmCase in lstCase)
- {
- // Create Test
- name = itmCase.Attribute("name");
- time = itmCase.Attribute("time");
-
- JunitCase test = new JunitCase()
- {
- Name = name != null ? name.Value : "",
- Time = time != null ? Convert.ToInt32(time.Value) : 0,
-
- Failures = new List(),
- Errors = new List()
- };
-
-
-
- // Get Errors
- IList lstError = itmCase.Descendants("error").ToList();
-
- foreach (XElement itmError in lstError)
- {
- XAttribute message = itmError.Attribute("message");
-
- test.Errors.Add(GetJunitResult(name != null ? name.Value : "", message != null ? message.Value : "", itmError.Value, filePath.EndsWith("js.xml") ? "JS" : "CSS"));
- }
-
-
-
- // Get Failures
- IList lstFailure = itmCase.Descendants("failure").ToList();
-
- foreach (XElement itmFailure in lstFailure)
- {
- XAttribute message = itmFailure.Attribute("message");
-
- test.Failures.Add(GetJunitResult(name != null ? name.Value : "", message != null ? message.Value : "", itmFailure.Value, filePath.EndsWith("js.xml") ? "JS" : "CSS"));
- }
-
-
-
- // Add Test
- if ((test.Errors.Count > 0) || (test.Failures.Count > 0))
- {
- suite.Cases.Add(test);
- }
- }
-
- results.Add(suite);
- }
-
- return results;
-}
-
-
-
-public JunitResult GetJunitResult(string name, string message, string inner, string type)
-{
- inner = inner.Replace("", "");
- string location = "";
-
- if (type == "JS")
- {
- name = name.Replace("org.eslint.", "");
- inner = inner.Replace(" (" + name + ")", "");
-
- int start = inner.IndexOf(", Error - ");
-
- if (start > 0)
- {
- location = inner.Substring(0, start);
- location = location.Replace("line ", "(").Replace(", col ", ", ") + ")";
-
- start = start + 10;
- inner = inner.Substring(start, inner.Length - start);
- }
- }
- else
- {
- // Inner
- int start = inner.IndexOf(":");
-
- if (start > 0)
- {
- // Line
- string line = inner.Substring(0, start);
- inner = inner.Substring(start, inner.Length - start);
-
- if (inner.Length > 1)
- {
- inner = inner.Substring(1, inner.Length - 1);
- }
-
-
-
- // Column
- start = inner.IndexOf(":");
-
- if (start > 0)
- {
- string column = inner.Substring(0, start);
- inner = inner.Substring(start, inner.Length - start);
-
- if (inner.Length > 1)
- {
- inner = inner.Substring(1, inner.Length - 1);
- }
-
- location = "(" + line.Replace(":", "") + ", " + column.Replace(":", "") + ")";
- }
- }
- }
-
- return new JunitResult()
- {
- Message = message.Trim(),
-
- Source = inner.Trim(),
- Location = location.Trim()
- };
-}
-
-
-
-public IList GetJunitAttachments(IList lstSuite)
-{
- IList attachments = new List();
-
- foreach(JunitSuite itmSuite in lstSuite)
- {
- foreach(JunitCase itmCase in itmSuite.Cases)
- {
- // Errors
- foreach(JunitResult itmResult in itmCase.Errors)
- {
- attachments.Add(new SlackChatMessageAttachment()
- {
- Pretext = itmSuite.Name.Trim(),
- Title = itmResult.Message.Trim(),
- Text = itmResult.Location.Trim(),
- Color = "danger"
- });
- }
-
- // Warnings
- foreach(JunitResult itmResult in itmCase.Failures)
- {
- attachments.Add(new SlackChatMessageAttachment()
- {
- Pretext = itmSuite.Name.Trim(),
- Title = itmResult.Message.Trim(),
- Text = itmResult.Location.Trim(),
- Color = "warning"
- });
- }
- }
- }
-
- return attachments;
-}
-
-
-
-public class JunitSuite
-{
- public string Package { get; set; }
-
- public string Name { get; set; }
-
-
-
- public int Time { get; set; }
-
- public int Errors { get; set; }
-
- public int Failures { get; set; }
-
-
-
- public IList Cases { get; set; }
-}
-
-public class JunitCase
-{
- public string Name { get; set; }
-
- public int Time { get; set; }
-
-
-
- public IList Failures { get; set; }
-
- public IList Errors { get; set; }
-}
-
-public class JunitResult
-{
- public string Message { get; set; }
-
- public string Source { get; set; }
-
- public string Location { get; set; }
-}
-
-
-
-
///////////////////////////////////////////////////////////////////////////////
// ATTACHMENTS
@@ -275,6 +19,7 @@ public void CombineAttachments(IList lstOutput, ILis
}
}
+
public string GetPrefix(string name)
{
string prefix = "";
@@ -288,24 +33,12 @@ public string GetPrefix(string name)
prefix = name.Substring(0, start + projectName.Length + 1);
}
}
-
- foreach(string testName in testNames)
- {
- int start = name.IndexOf(testName);
-
- if (start > 0)
- {
- prefix = name.Substring(0, start + testName.Length + 1);
- }
- }
return prefix;
}
-
-
///////////////////////////////////////////////////////////////////////////////
// MS BUILD
///////////////////////////////////////////////////////////////////////////////
@@ -328,15 +61,7 @@ public IList GetMsBuildAttachments(string path, Exce
{
found = true;
}
- }
-
- foreach(string name in testNames)
- {
- if (line.StartsWith(" " + name + " -> "))
- {
- found = true;
- }
- }
+ }
if (!found)
{
diff --git a/build/scripts/package.cake b/build/scripts/package.cake
deleted file mode 100644
index 34d1e10..0000000
--- a/build/scripts/package.cake
+++ /dev/null
@@ -1,88 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// PACKAGE
-///////////////////////////////////////////////////////////////////////////////
-
-Task("Copy-Files")
- .Does(() =>
-{
- if (projectBinDirs.Count > 0)
- {
- bool found = false;
-
- if (appName.Contains("Cake."))
- {
- CleanDirectory("./test/tools/Addins/");
- }
-
- foreach (string project in projectBinDirs)
- {
- if (!project.Contains(".Websites") && !project.Contains(".Tests") && !project.EndsWith(".TestConsole") && !project.EndsWith(".TestSite"))
- {
- found = true;
- CopyDirectory(project + "/" + configuration, binDir);
-
- if (project.Contains("Cake."))
- {
- CopyDirectory(project + "/" + configuration, "./test/tools/Addins/" + appName + "." + version + "/lib/");
- }
- }
- }
-
- if (found)
- {
- // Docs
- CopyFiles(new FilePath[] { "LICENSE", "README.md", "ReleaseNotes.md" }, binDir);
- }
- }
-});
-
-
-
-Task("Zip-Files")
- .IsDependentOn("Copy-Files")
- .Does(() =>
-{
- // Apps
- bool found = false;
-
- foreach (string project in projectNames)
- {
- if (project.Contains(".Websites") && !project.EndsWith(".Tests") && !project.EndsWith(".TestConsole") && !project.EndsWith(".TestSite"))
- {
- found = true;
- Zip(binDir + Directory(project), deployDir + "/" + project + ".zip");
- }
- }
-
- // Libraries
- if (!found)
- {
- Zip(binDir, zipPackage);
- }
-});
-
-
-
-Task("Create-NuGet-Packages")
- .IsDependentOn("Zip-Files")
- .Does(() =>
-{
- foreach (string project in projectNames)
- {
- if (!project.EndsWith(".Tests") && !project.EndsWith(".TestConsole") && !project.EndsWith(".TestSite"))
- {
- // Solution Packages
- NuGetPack("./nuspec/" + project + ".nuspec", new NuGetPackSettings
- {
- Version = version,
- ReleaseNotes = releaseNotes.Notes.ToArray(),
- Copyright = "Copyright (c) 2015 - " + DateTime.Now.Year.ToString() + " " + copyright,
-
- BasePath = binDir,
- OutputDirectory = nugetDir,
- Symbols = false,
- NoPackageAnalysis = true
- });
- }
- }
-});
diff --git a/build/scripts/prepare.cake b/build/scripts/prepare.cake
deleted file mode 100644
index 1efe219..0000000
--- a/build/scripts/prepare.cake
+++ /dev/null
@@ -1,62 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// PREPARE
-///////////////////////////////////////////////////////////////////////////////
-
-Task("Clean")
- .Does(() =>
-{
- Information("Cleaning project files");
-
- CleanDirectories(projectBinDirs);
- CleanDirectories(projectObjDirs);
-
-
-
- Information("Cleaning build files");
-
- CleanDirectories(new DirectoryPath[]
- {
- buildResultDir,
- testResultsDir,
- nugetDir, deployDir, binDir
- });
-
-
-
- Information("Cleaning nuspec temp files");
-
- DeleteFiles("./nuspec/*.temp.nuspec");
-});
-
-
-
-Task("Restore-Nuget-Packages")
- .IsDependentOn("Clean")
- .WithCriteria(() => target != "Skip-Restore")
- .Does(() =>
-{
- // Restore all main projects
- foreach (string project in projectNames)
- {
- if (projectDirs.Contains("./src/" + project))
- {
- Information("Restoring {0}", project);
-
- DotNetCoreRestore("./src/" + project, new DotNetCoreRestoreSettings()
- {
- Verbosity = DotNetCoreVerbosity.Normal
- });
- }
- }
-
- // Restoring test projects
- foreach(string project in testNames)
- {
- Information("Restoring: {0}", project);
-
- DotNetCoreRestore("./src/" + project, new DotNetCoreRestoreSettings()
- {
- Verbosity = DotNetCoreVerbosity.Normal
- });
- }
-});
diff --git a/build/scripts/publish.cake b/build/scripts/publish.cake
index 74c6e5f..0a51a45 100644
--- a/build/scripts/publish.cake
+++ b/build/scripts/publish.cake
@@ -2,37 +2,8 @@
// PUBLISH
///////////////////////////////////////////////////////////////////////////////
-Task("Clear-AppData")
- .IsDependentOn("Create-NuGet-Packages")
- .WithCriteria(() => local)
- .WithCriteria(() => !isPullRequest)
- .Does(() =>
-{
- var dataDir = Context.FileSystem.GetDirectory(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"/.nuget/packages/");
-
- if (dataDir.Exists)
- {
- // Delete
- foreach (string project in projectNames)
- {
- var dirs = dataDir.GetDirectories(project, SearchScope.Current);
-
- foreach(IDirectory dir in dirs)
- {
- DeleteDirectory(dir.Path, new DeleteDirectorySettings()
- {
- Force = true,
- Recursive = true
- });
- }
- }
- }
-});
-
-
-
Task("Publish-Local")
- .IsDependentOn("Clear-AppData")
+ .IsDependentOn("Build")
.WithCriteria(() => local)
.WithCriteria(() => !isPullRequest)
.Does(() =>
@@ -40,53 +11,36 @@ Task("Publish-Local")
var packageDir = Context.FileSystem.GetDirectory(@"C:/Projects/Packages/");
if (packageDir.Exists)
- {
- // Delete
- foreach (string project in projectNames)
- {
- var files = packageDir.GetFiles(project + ".*", SearchScope.Current);
+ {
+ var files = packageDir.GetFiles("Cake.SqlTools.*", SearchScope.Current);
- foreach (IFile file in files)
- {
- DeleteFile(file.Path);
- }
+ foreach (IFile file in files)
+ {
+ DeleteFile(file.Path);
}
-
+
// Copy
- CopyDirectory(nugetDir, packageDir.Path);
+ CopyFileToDirectory(packageFileName, packageDir.Path);
}
});
Task("Publish-Nuget")
- .IsDependentOn("Create-NuGet-Packages")
+ .IsDependentOn("Build")
.WithCriteria(() => isRunningOnAppVeyor || isRunningOnTFS || (target == "Skip-Restore") )
.WithCriteria(() => !isPullRequest)
.Does(() =>
{
- foreach (string project in projectNames)
- {
- if (!project.EndsWith(".Tests") && !project.EndsWith(".TestConsole") && !project.EndsWith(".TestSite"))
- {
- // Check the API key
- var apiKey = EnvironmentVariable("NUGET_API_KEY");
-
- if (string.IsNullOrEmpty(apiKey))
- {
- throw new InvalidOperationException("Could not resolve nuget API key.");
- }
-
-
-
- // Push the packages
- var package = nugetDir + "/" + project + "." + version + ".nupkg";
+ // Check the API key
+ var apiKey = EnvironmentVariable("NUGET_API_KEY");
- NuGetPush(package, new NuGetPushSettings
- {
- Source = "https://www.nuget.org/api/v2/package",
- ApiKey = apiKey
- });
- }
- }
+ if (string.IsNullOrEmpty(apiKey))
+ throw new InvalidOperationException("Could not resolve nuget API key.");
+
+ NuGetPush(packageFileName, new NuGetPushSettings
+ {
+ Source = "https://www.nuget.org/api/v2/package",
+ ApiKey = apiKey
+ });
});
\ No newline at end of file
diff --git a/build/scripts/setup.cake b/build/scripts/setup.cake
index fa7cdb2..b95e6ce 100644
--- a/build/scripts/setup.cake
+++ b/build/scripts/setup.cake
@@ -7,8 +7,6 @@ Setup(context =>
// Executed BEFORE the first task.
Information("Building version {0} of {1}.", semVersion, appName);
Information("Target: {0}.", target);
- Information("Tools dir: {0}.", tools);
- Information("Username: {0}", username);
});
diff --git a/build/scripts/targets.cake b/build/scripts/targets.cake
index 3c035b5..4c5ab1a 100644
--- a/build/scripts/targets.cake
+++ b/build/scripts/targets.cake
@@ -3,9 +3,7 @@
//////////////////////////////////////////////////////////////////////
Task("Package")
- .IsDependentOn("Run-Unit-Tests")
- .IsDependentOn("Zip-Files")
- .IsDependentOn("Create-NuGet-Packages")
+ .IsDependentOn("Build")
.IsDependentOn("Publish-Local");
Task("Publish")
diff --git a/build/scripts/test.cake b/build/scripts/test.cake
deleted file mode 100644
index 5916ee5..0000000
--- a/build/scripts/test.cake
+++ /dev/null
@@ -1,181 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// TEST
-///////////////////////////////////////////////////////////////////////////////
-
-Task("Run-Unit-Tests")
- .WithCriteria(() => (target != "Skip-Test") && (target != "Skip-Restore"))
- .IsDependentOn("Build")
- .Does(() =>
-{
- // Run Test
- foreach(string test in testNames)
- {
- Information("Running unit tests: {0}", test);
-
- string outputPath = testResultsDir + "/" + test.Replace(".Tests", "") + ".xml";
- outputPath = MakeAbsolute(File(outputPath)).FullPath;
-
- DotNetCoreTest("./src/" + test + "/" + test + ".csproj", new DotNetCoreTestSettings
- {
- NoRestore = true,
- ArgumentCustomization = args => args.AppendSwitch("-a", " ", ".".Quote())
- .AppendSwitch("-l", " ", ("xunit;LogFilePath=" + outputPath).Quote())
- });
- }
-
-
-
- // Build Report
- Information("Building report");
-
- if (testNames.Count > 0)
- {
- ReportUnit(testResultsDir);
- }
-})
-.OnError(exception =>
-{
- // Get Errors
- IList errors = new List();
-
- foreach(string test in testNames)
- {
- IList testResults = GetXunitResults(testResultsDir + "/" + test.Replace(".Tests", "") + ".xml");
-
- foreach(XunitResult testResult in testResults)
- {
- errors.Add(testResult.Type + " => " + testResult.Method);
- errors.Add(testResult.StackTrace);
- }
- }
-
- if (errors.Count == 0)
- {
- errors.Add(exception.Message);
- }
-
-
-
- // Get Message
- var title = "Unit-Tests failed for " + appName + " v" + version;
- var text = "";
-
- for (int index = 0; index < errors.Count; index++)
- {
- text += errors[index];
-
- if (index < (errors.Count - 1))
- {
- text += "\n";
- }
- }
-
-
-
- // Resolve the webHook Url.
- var webHookUrl = EnvironmentVariable("SLACK_WEBHOOK_URL");
-
- if (string.IsNullOrEmpty(webHookUrl))
- {
- throw new InvalidOperationException("Could not resolve Slack webHook Url.");
- }
-
-
-
- // Post Message
- SlackChatMessageResult result;
-
- SlackChatMessageSettings settings = new SlackChatMessageSettings()
- {
- IncomingWebHookUrl = webHookUrl,
- UserName = "Cake",
- IconUrl = new System.Uri("https://cdn.jsdelivr.net/gh/cake-build/graphics/png/cake-small.png")
- };
-
- IList attachments = new List();
-
- attachments.Add(new SlackChatMessageAttachment()
- {
- Color = "danger",
- Text = text
- });
-
- result = Slack.Chat.PostMessage("#code", title, attachments, settings);
-
-
-
- // Check Result
- if (result.Ok)
- {
- // Posted
- Information("Message was succcessfully sent to Slack.");
- }
- else
- {
- // Error
- Error("Failed to send message to Slack: {0}", result.Error);
- }
-
- throw exception;
-});
-
-
-
-
-
-using System.Xml.Linq;
-
-public IList GetXunitResults(string filePath)
-{
- // Load Document
- XDocument doc = XDocument.Load(filePath);
- IList elements = doc.Descendants("test").Where(e => e.Attribute("result").Value == "Fail").ToList();
- IList results = new List();
-
- foreach (XElement element in elements)
- {
- XAttribute type = element.Attribute("type");
- XAttribute method = element.Attribute("method");
-
- XElement file = element.Descendants("source-file").FirstOrDefault();
- XElement line = element.Descendants("source-line").FirstOrDefault();
-
- XElement message = element.Descendants("message").FirstOrDefault();
- XElement stackTrace = element.Descendants("stack-trace").FirstOrDefault();
-
- results.Add(new XunitResult()
- {
- Type = type != null ? type.Value : "",
- Method = method != null ? method.Value : "",
-
- File = file != null ? file.Value : "",
- Line = line != null ? line.Value : "",
-
- Message = message != null ? message.Value : "",
- StackTrace = stackTrace != null ? stackTrace.Value : "",
- });
- }
-
- return results;
-}
-
-
-
-public class XunitResult
-{
- public string Type { get; set; }
-
- public string Method { get; set; }
-
-
-
- public string File { get; set; }
-
- public string Line { get; set; }
-
-
-
- public string Message { get; set; }
-
- public string StackTrace { get; set; }
-}
\ No newline at end of file
diff --git a/build/scripts/variables.cake b/build/scripts/variables.cake
index 1a8e9fd..85a7b77 100644
--- a/build/scripts/variables.cake
+++ b/build/scripts/variables.cake
@@ -2,12 +2,6 @@
// VARIABLES
//////////////////////////////////////////////////////////////////////
-// Setup
-var tools = EnvironmentVariable("CAKE_PATHS_TOOLS");
-var username = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile).ToLower().Replace(@"c:\users\", "").Replace(@"c:\windows\serviceprofiles\", "");
-
-
-
// Get whether or not this is a local build.
var local = BuildSystem.IsLocalBuild;
var isRunningOnAppVeyor = AppVeyor.IsRunningOnAppVeyor;
@@ -24,59 +18,15 @@ var version = releaseNotes.Version.ToString();
var semVersion = local ? version : (version + string.Concat("-build-", buildNumber));
// Define directories.
-var buildResultDir = "./build/results";
-var testResultsDir = buildResultDir + "/tests";
-var loggerResultsDir = buildResultDir + "/logger";
-var nugetDir = buildResultDir + "/nuget";
-var deployDir = buildResultDir + "/deploy";
-var binDir = buildResultDir + "/bin";
-
-
-
-// Package Location
-var zipPackage = buildResultDir + "/" + appName.Replace(".", "-") + "-v" + semVersion + ".zip";
+var buildResultDir = new DirectoryPath("./build/results").MakeAbsolute(Context.Environment);;
+var testResultsDir = buildResultDir.Combine("tests");
+var loggerResultsDir = buildResultDir.Combine("logger");
+var nugetDir = buildResultDir.Combine("nuget");
+var deployDir = buildResultDir.Combine("deploy");
+var binDir = buildResultDir.Combine("bin");
// Project Locations
var solution = "./src/" + appName + ".sln";
-var projectDirs = new List();
-var projectBinDirs = new List();
-var projectObjDirs = new List();
-var projectFiles = new List();
-
-foreach (string project in projectNames)
-{
- if (DirectoryExists("./src/" + project))
- {
- projectDirs.Add("./src/" + project);
-
- projectBinDirs.Add("./src/" + project + "/bin");
- projectObjDirs.Add("./src/" + project + "/obj");
-
- projectFiles.Add(File("./src/" + project + "/" + project + ".xproj"));
- }
-}
-
-
-
-// Find Tests
-var testNames = new List();
-
-if (DirectoryExists("./src/" + appName + ".Tests"))
-{
- testNames.Add(appName + ".Tests");
-
- projectBinDirs.Add("./src/" + appName + ".Tests/bin/");
- projectObjDirs.Add("./src/" + appName + ".Tests/obj");
-}
+var packageFileName = nugetDir.CombineWithFilePath($"Cake.SqlTools.{version}.nupkg");
-foreach (string project in projectNames)
-{
- if (DirectoryExists("./src/" + project + ".Tests"))
- {
- testNames.Add(project + ".Tests");
-
- projectBinDirs.Add("./src/" + project + ".Tests/bin");
- projectObjDirs.Add("./src/" + project + ".Tests/obj");
- }
-}
diff --git a/cake.config b/cake.config
deleted file mode 100644
index e340181..0000000
--- a/cake.config
+++ /dev/null
@@ -1,4 +0,0 @@
-[Paths]
-Tools=C:/tools
-Addins=C:/tools/Addins
-Modules=C:/tools/Modules
\ No newline at end of file
diff --git a/nuspec/Cake.SqlTools.nuspec b/nuspec/Cake.SqlTools.nuspec
deleted file mode 100644
index 3eb40f4..0000000
--- a/nuspec/Cake.SqlTools.nuspec
+++ /dev/null
@@ -1,56 +0,0 @@
-
-
-
- Cake.SqlTools
- 0.0.0
- Phillip Sharpe
- Phillip Sharpe
- Cake.SqlTools
- Cake Build addon for executing sql queries.
- Sql tools addon for cake build.
- https://github.com/SharpeRAD/Cake.SqlTools/LICENSE
- https://github.com/SharpeRAD/Cake.SqlTools
- https://cdn.jsdelivr.net/gh/cake-contrib/graphics/png/addin/cake-contrib-addin-medium.png
- false
- Copyright (c) Phillip Sharpe 2015
- Initial Release
- Cake cake-addin Script Build SQL Queries
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/Cake.SqlTools.sln b/src/Cake.SqlTools.sln
index f60a309..5ecb927 100644
--- a/src/Cake.SqlTools.sln
+++ b/src/Cake.SqlTools.sln
@@ -1,7 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.26730.15
+# Visual Studio Version 17
+VisualStudioVersion = 17.8.34322.80
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Source", "Source", "{7B702943-4526-4B9D-B8DD-F50821850150}"
EndProject
@@ -20,11 +20,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{04DD68ED-2
..\ReleaseNotes.md = ..\ReleaseNotes.md
EndProjectSection
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Nuget", "Nuget", "{3A8E8897-6C64-42B0-B336-7A46480003B9}"
- ProjectSection(SolutionItems) = preProject
- ..\nuspec\Cake.SqlTools.nuspec = ..\nuspec\Cake.SqlTools.nuspec
- EndProjectSection
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cake.SqlTools", "Cake.SqlTools\Cake.SqlTools.csproj", "{8FC19DAE-52B1-404B-9439-19C4DDF5E69C}"
EndProject
Global
diff --git a/src/Cake.SqlTools/Aliases/SqlQueryAliases.cs b/src/Cake.SqlTools/Aliases/SqlQueryAliases.cs
index 7dede0c..e3ef8a5 100644
--- a/src/Cake.SqlTools/Aliases/SqlQueryAliases.cs
+++ b/src/Cake.SqlTools/Aliases/SqlQueryAliases.cs
@@ -1,49 +1,38 @@
-#region Using Statements
-using System;
-
-using Cake.Core;
-using Cake.Core.IO;
+using Cake.Core;
using Cake.Core.Annotations;
using Cake.Core.Diagnostics;
-#endregion
-
-
+using Cake.Core.IO;
namespace Cake.SqlTools
{
///
- /// Contains Cake aliases for executing sql queries
+ /// Contains Cake aliases for executing sql queries.
///
- [CakeAliasCategory("SqlTools")]
+ [CakeAliasCategory(nameof(SqlTools))]
public static class SqlQueryAliases
{
- #region Methods
///
/// Executes a sql query against a database
///
/// The cake context.
/// The sql query to execute.
/// The to use to connect with.
+ /// True if command succeeded.
[CakeMethodAlias]
public static bool ExecuteSqlQuery(this ICakeContext context, string query, SqlQuerySettings settings)
{
- if (String.IsNullOrEmpty(query))
- {
- throw new ArgumentNullException("query");
- }
- if (settings == null)
- {
- throw new ArgumentNullException("settings");
- }
+ if (string.IsNullOrEmpty(query))
+ throw new ArgumentNullException(nameof(query));
- ICakeLog log = settings.AllowLogs ? context.Log : new Logging.QuietLog();
+ ArgumentNullException.ThrowIfNull(nameof(settings));
- ISqlQueryRepository repository = null;
+ var log = settings.AllowLogs ? context.Log : new Logging.QuietLog();
+
+ ISqlQueryRepository? repository = null;
switch (settings.Provider)
{
case "MsSql":
- Initializer.InitializeNativeSearchPath();
repository = new MsSqlQueryRepository(log);
break;
@@ -54,57 +43,42 @@ public static bool ExecuteSqlQuery(this ICakeContext context, string query, SqlQ
case "Npgsql":
repository = new NpgsqlQueryRepository(log);
break;
- }
-
-
- if (repository != null)
- {
- return repository.Execute(settings.ConnectionString, query);
+ default:
+ log.Error("Unknown sql provider {0}", settings.Provider);
+ return false;
}
- else
- {
- log.Error("Unknown sql provider {0}", settings.Provider);
- return false;
- }
- }
-
+ return repository.Execute(settings.ConnectionString, query);
+ }
///
- /// Executes a sql file against a database
+ /// Executes a sql file against a database.
///
/// The cake context.
/// The path to the sql file to execute.
/// The to use to connect with.
+ /// True if command succeeded.
[CakeMethodAlias]
public static bool ExecuteSqlFile(this ICakeContext context, FilePath path, SqlQuerySettings settings)
{
- if (path == null)
- {
- throw new ArgumentNullException("path");
- }
- if (settings == null)
- {
- throw new ArgumentNullException("settings");
- }
+ ArgumentNullException.ThrowIfNull(nameof(path));
+ ArgumentNullException.ThrowIfNull(nameof(settings));
- ICakeLog log = settings.AllowLogs ? context.Log : new Logging.QuietLog();
+ var log = settings.AllowLogs ? context.Log : new Logging.QuietLog();
- IFile file = context.FileSystem.GetFile(path);
+ var file = context.FileSystem.GetFile(path);
if (file.Exists)
{
- string query = file.ReadBytes().GetString();
+ var query = file.ReadBytes().GetString();
return context.ExecuteSqlQuery(query, settings);
}
- else
- {
- log.Error("Missing sql file {0}", path.FullPath);
- return false;
- }
+
+ log.Error("Missing sql file {0}", path.FullPath);
+ return false;
+
}
- #endregion
}
-}
\ No newline at end of file
+}
diff --git a/src/Cake.SqlTools/Cake.SqlTools.csproj b/src/Cake.SqlTools/Cake.SqlTools.csproj
index 1b50b0f..6442ef9 100644
--- a/src/Cake.SqlTools/Cake.SqlTools.csproj
+++ b/src/Cake.SqlTools/Cake.SqlTools.csproj
@@ -2,29 +2,59 @@
Cake.SqlTools
Cake.SqlTools
- Cake.SqlTools
- Library
- net461;netstandard2.0;net5.0
+ true
+ snupkg
+ true
+ true
+ true
+ enable
+ true
- false
- false
- false
- false
- false
- true
+ net6.0;net7.0;net8.0
+
+ true
- bin\Debug\net46\Cake.SqlTools.xml
+ Cake.SqlTools
+ 0.0.0
+ Phillip Sharpe
+ Copyright (c) Phillip Sharpe 2015
+ false
+ Cake Build addon for executing sql queries.
+ Cake cake-addin Script Build SQL Queries
+ icon.png
+ https://cdn.jsdelivr.net/gh/cake-contrib/graphics/png/addin/cake-contrib-addin-medium.png
+ https://github.com/SharpeRAD/Cake.SqlTools
+ README.md
+ See release notes file
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
-
-
-
-
+
+
+
+
+
+
diff --git a/src/Cake.SqlTools/ConnectionNullException.cs b/src/Cake.SqlTools/ConnectionNullException.cs
new file mode 100644
index 0000000..0c77b1a
--- /dev/null
+++ b/src/Cake.SqlTools/ConnectionNullException.cs
@@ -0,0 +1,29 @@
+namespace Cake.SqlTools
+{
+#if !NET8_0_OR_GREATER
+ [Serializable]
+#endif
+ public class ConnectionNullException : Exception
+ {
+ public ConnectionNullException()
+ {
+ }
+
+ public ConnectionNullException(string message)
+ : base(message)
+ {
+ }
+
+ public ConnectionNullException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+
+#if !NET8_0_OR_GREATER
+ protected ConnectionNullException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
+ : base(info, context)
+ {
+ }
+#endif
+ }
+}
diff --git a/src/Cake.SqlTools/Extensions/CommandExtensions.cs b/src/Cake.SqlTools/Extensions/CommandExtensions.cs
index df08bd5..7f2bc88 100644
--- a/src/Cake.SqlTools/Extensions/CommandExtensions.cs
+++ b/src/Cake.SqlTools/Extensions/CommandExtensions.cs
@@ -1,36 +1,31 @@
-#region Using Statements
-using System.Data;
+using System.Data;
using System.Data.Common;
-#endregion
-
-
namespace Cake.SqlTools
{
internal static class CommandExtensions
{
- #region Methods
- //Command
internal static IDbCommand CreateCommand(this IDbConnection connection, CommandType type, string text)
{
- return connection.CreateCommand(type, text, null);
+ return connection.CreateCommand(type, text, transaction: null);
}
- internal static IDbCommand CreateCommand(this IDbConnection connection, CommandType type, string text, DbTransaction transaction)
+ internal static IDbCommand CreateCommand(this IDbConnection connection, CommandType type, string text, DbTransaction? transaction)
{
- DbCommand command = (DbCommand)connection.CreateCommand();
+ var command = (DbCommand)connection.CreateCommand();
command.CommandText = text;
command.CommandType = type;
- command.Transaction = transaction;
+ if (transaction is not null)
+ command.Transaction = transaction;
return command;
}
internal static IDbCommand CreateTextCommand(this IDbConnection connection, string text)
{
- return connection.CreateCommand(CommandType.Text, text, null);
+ return connection.CreateCommand(CommandType.Text, text, transaction: null);
}
internal static IDbCommand CreateTextCommand(this IDbConnection connection, string text, DbTransaction transaction)
@@ -38,15 +33,11 @@ internal static IDbCommand CreateTextCommand(this IDbConnection connection, stri
return connection.CreateCommand(CommandType.Text, text, transaction);
}
-
-
- //Timeout
internal static IDbCommand SetTimeout(this IDbCommand command, int timeout)
{
command.CommandTimeout = timeout;
return command;
}
- #endregion
}
-}
\ No newline at end of file
+}
diff --git a/src/Cake.SqlTools/Extensions/FileExtensions.cs b/src/Cake.SqlTools/Extensions/FileExtensions.cs
index 9373b08..636ac6d 100644
--- a/src/Cake.SqlTools/Extensions/FileExtensions.cs
+++ b/src/Cake.SqlTools/Extensions/FileExtensions.cs
@@ -1,33 +1,21 @@
-#region Using Statements
-using System.IO;
-using System.Text;
-
+using System.Text;
using Cake.Core.IO;
-#endregion
-
-
namespace Cake.SqlTools
{
internal static class FileExtensions
{
- #region Methods
internal static byte[] ReadBytes(this IFile file)
{
- using (Stream stream = file.OpenRead())
- {
- using (MemoryStream ms = new MemoryStream())
- {
- stream.CopyTo(ms);
- return ms.ToArray();
- }
- }
+ using var stream = file.OpenRead();
+ using var ms = new MemoryStream();
+ stream.CopyTo(ms);
+ return ms.ToArray();
}
-
+
internal static string GetString(this byte[] bytes)
{
- return Encoding.UTF8.GetString(bytes);
+ return Encoding.UTF8.GetString(bytes);
}
- #endregion
}
-}
\ No newline at end of file
+}
diff --git a/src/Cake.SqlTools/Initializer.cs b/src/Cake.SqlTools/Initializer.cs
deleted file mode 100644
index 324ccd6..0000000
--- a/src/Cake.SqlTools/Initializer.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using System;
-using System.IO;
-using System.Reflection;
-
-namespace Cake.SqlTools
-{
- internal static class Initializer
- {
- private static bool _initialized;
-
- internal static void InitializeNativeSearchPath()
- {
-#if NET461
- if (Environment.OSVersion.Platform == PlatformID.Win32NT)
-#endif
- {
- if (_initialized)
- {
- return;
- }
-
-#if NET461
- var codeBase = Assembly.GetExecutingAssembly().CodeBase;
- var uri = new UriBuilder(codeBase);
- var path = Uri.UnescapeDataString(uri.Path);
- var addinFolder = Path.GetDirectoryName(path);
- NativeMethods.SetDefaultDllDirectories(NativeMethods.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
- NativeMethods.AddDllDirectory(addinFolder);
-#endif
- _initialized = true;
- }
- }
- }
-}
diff --git a/src/Cake.SqlTools/Interfaces/ISqlQueryRepository.cs b/src/Cake.SqlTools/Interfaces/ISqlQueryRepository.cs
index 1abdeff..251518a 100644
--- a/src/Cake.SqlTools/Interfaces/ISqlQueryRepository.cs
+++ b/src/Cake.SqlTools/Interfaces/ISqlQueryRepository.cs
@@ -1,20 +1,16 @@
-
-
-
-namespace Cake.SqlTools
+namespace Cake.SqlTools
{
///
- /// Provides a method to execture sql queries against a database
+ /// Provides a method to execute sql queries against a database.
///
public interface ISqlQueryRepository
{
- #region Methods
///
- /// Executes a sql query against a database
+ /// Executes a sql query against a database.
///
/// The connectionString to connect with.
/// The sql query to execute.
+ /// True if executions succeeded.
bool Execute(string connectionString, string query);
- #endregion
}
-}
\ No newline at end of file
+}
diff --git a/src/Cake.SqlTools/Logging/QuietLog.cs b/src/Cake.SqlTools/Logging/QuietLog.cs
index dfcd19c..0d5c40b 100644
--- a/src/Cake.SqlTools/Logging/QuietLog.cs
+++ b/src/Cake.SqlTools/Logging/QuietLog.cs
@@ -1,36 +1,35 @@
using Cake.Core.Diagnostics;
-using System;
namespace Cake.SqlTools.Logging
{
- ///
- /// A logger implementation which does not log. Can be used to prevent null checking all the way.
- ///
- internal class QuietLog : ICakeLog
- {
- ///
- /// Provides the method to write logs like defined in the ICakeLog interface but does not log anything.
- ///
- /// The ignored verbosity of the log message.
- /// The ignored level of the log message
- /// The ignored format string for the log message
- /// The ignored string format arguments for the log message
- ///
- /// Can be used as logger to prevent the Cake tool from logging at all.
- /// This way, the caller does not have to check for nulls.
- ///
- public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args)
- {
- // log nothing
- }
+ ///
+ /// A logger implementation which does not log. Can be used to prevent null checking all the way.
+ ///
+ internal class QuietLog : ICakeLog
+ {
+ ///
+ /// Provides the method to write logs like defined in the ICakeLog interface but does not log anything.
+ ///
+ /// The ignored verbosity of the log message.
+ /// The ignored level of the log message
+ /// The ignored format string for the log message
+ /// The ignored string format arguments for the log message
+ ///
+ /// Can be used as logger to prevent the Cake tool from logging at all.
+ /// This way, the caller does not have to check for nulls.
+ ///
+ public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args)
+ {
+ // log nothing
+ }
- ///
- /// Gets or sets the verbosity of the logger.
- ///
- public Verbosity Verbosity
- {
- get => Verbosity.Quiet;
- set => throw new NotSupportedException();
- }
- }
-}
\ No newline at end of file
+ ///
+ /// Gets or sets the verbosity of the logger.
+ ///
+ public Verbosity Verbosity
+ {
+ get => Verbosity.Quiet;
+ set => throw new NotSupportedException();
+ }
+ }
+}
diff --git a/src/Cake.SqlTools/NativeMethods.cs b/src/Cake.SqlTools/NativeMethods.cs
deleted file mode 100644
index a35a8fa..0000000
--- a/src/Cake.SqlTools/NativeMethods.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System.Runtime.InteropServices;
-
-namespace Cake.SqlTools
-{
-#if NET461
- internal static class NativeMethods
- {
- internal const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000;
-
- [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- internal static extern bool SetDefaultDllDirectories(uint directoryFlags);
-
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- internal static extern int AddDllDirectory(string newDirectory);
- }
-#endif
-}
diff --git a/src/Cake.SqlTools/Properties/AssemblyInfo.cs b/src/Cake.SqlTools/Properties/AssemblyInfo.cs
deleted file mode 100644
index 0453ca6..0000000
--- a/src/Cake.SqlTools/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("8a284243-67d4-49e0-b61c-18aaf4d23ffa")]
diff --git a/src/Cake.SqlTools/Properties/Namespaces.cs b/src/Cake.SqlTools/Properties/Namespaces.cs
deleted file mode 100644
index a0a5925..0000000
--- a/src/Cake.SqlTools/Properties/Namespaces.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-using System.Runtime.CompilerServices;
-// ReSharper disable CheckNamespace
-
-
-namespace Cake.SqlTools
-{
- ///
- /// This namespace contains sql query aliases and related members.
- ///
- [CompilerGenerated]
- internal class NamespaceDoc
- {
- }
-}
\ No newline at end of file
diff --git a/src/Cake.SqlTools/Repositories/Base/BaseSqlQueryRepository.cs b/src/Cake.SqlTools/Repositories/Base/BaseSqlQueryRepository.cs
index 5064fd8..470fb6d 100644
--- a/src/Cake.SqlTools/Repositories/Base/BaseSqlQueryRepository.cs
+++ b/src/Cake.SqlTools/Repositories/Base/BaseSqlQueryRepository.cs
@@ -1,54 +1,33 @@
-#region Using Statements
-using System;
-using System.Data;
-
+using System.Data;
using Cake.Core.Diagnostics;
-#endregion
-
-
namespace Cake.SqlTools
{
///
- /// Provides a method to execture sql queries against a database
+ /// Provides a method to execute sql queries against a database.
///
public abstract class BaseSqlQueryRepository : ISqlQueryRepository
{
- #region Fields
- private ICakeLog _Logger;
- #endregion
-
+ private readonly ICakeLog _logger;
-
-
-
- #region Constructors
///
/// Initializes a new instance of the class.
///
/// The log.
- public BaseSqlQueryRepository(ICakeLog log)
+ protected BaseSqlQueryRepository(ICakeLog log)
{
- _Logger = log;
+ _logger = log ?? throw new ArgumentNullException(nameof(log));
}
- #endregion
-
-
-
-
- #region Methods
///
/// Opens a connection to the database
///
/// The connectionString to connect with.
- protected virtual IDbConnection OpenConnection(string connectionString)
+ protected virtual IDbConnection? OpenConnection(string connectionString)
{
return null;
}
-
-
///
/// Executes a sql query against a database
///
@@ -58,24 +37,21 @@ public bool Execute(string connectionString, string query)
{
try
{
- using (IDbConnection conn = this.OpenConnection(connectionString))
- {
- //Call Command
- conn.CreateTextCommand(query)
- .SetTimeout(0)
- .ExecuteNonQuery();
- }
+ using var conn = OpenConnection(connectionString) ?? throw new ConnectionNullException();
+
+ conn.CreateTextCommand(query)
+ .SetTimeout(0)
+ .ExecuteNonQuery();
}
catch (Exception e)
{
//Error
- _Logger.Error(e.Message);
+ _logger.Error(e.Message);
throw;
}
-
- _Logger.Information("Sql query executed successfully.");
+
+ _logger.Information("Sql query executed successfully.");
return true;
}
- #endregion
}
}
diff --git a/src/Cake.SqlTools/Repositories/Types/MsSqlQueryRepository.cs b/src/Cake.SqlTools/Repositories/Types/MsSqlQueryRepository.cs
index 691029c..b7b9bac 100644
--- a/src/Cake.SqlTools/Repositories/Types/MsSqlQueryRepository.cs
+++ b/src/Cake.SqlTools/Repositories/Types/MsSqlQueryRepository.cs
@@ -1,21 +1,14 @@
-#region Using Statements
-
-using System.Data;
-using Microsoft.Data.SqlClient;
-
+using System.Data;
using Cake.Core.Diagnostics;
-#endregion
-
-
+using Microsoft.Data.SqlClient;
namespace Cake.SqlTools
{
///
- /// Provides a method to execture sql queries against a MsSql database
+ /// Provides a method to execute sql queries against a MsSql database
///
public class MsSqlQueryRepository : BaseSqlQueryRepository
{
- #region Constructors
///
/// Initializes a new instance of the class.
///
@@ -25,26 +18,19 @@ public MsSqlQueryRepository(ICakeLog log)
{
}
- #endregion
-
-
-
-
- #region Methods
- ///
- /// Opens a connection to the database
- ///
- /// The connectionString to connect with.
- protected override IDbConnection OpenConnection(string connectionString)
+ ///
+ protected override IDbConnection? OpenConnection(string connectionString)
{
- IDbConnection con = SqlClientFactory.Instance.CreateConnection();
+ var connection = SqlClientFactory.Instance.CreateConnection();
- con.ConnectionString = connectionString;
- con.Open();
+ if (connection is not null)
+ {
+ connection.ConnectionString = connectionString;
+ connection.Open();
+ }
- return con;
+ return connection;
}
- #endregion
}
-}
\ No newline at end of file
+}
diff --git a/src/Cake.SqlTools/Repositories/Types/MySqlQueryRepository.cs b/src/Cake.SqlTools/Repositories/Types/MySqlQueryRepository.cs
index fa24b4b..528b8ee 100644
--- a/src/Cake.SqlTools/Repositories/Types/MySqlQueryRepository.cs
+++ b/src/Cake.SqlTools/Repositories/Types/MySqlQueryRepository.cs
@@ -1,21 +1,14 @@
-#region Using Statements
-using System.Data;
-
-using MySql.Data.MySqlClient;
-
+using System.Data;
using Cake.Core.Diagnostics;
-#endregion
-
-
+using MySql.Data.MySqlClient;
namespace Cake.SqlTools
{
///
- /// Provides a method to execture sql queries against a MySql database
+ /// Provides a method to execute sql queries against a MySql database
///
public class MySqlQueryRepository : BaseSqlQueryRepository
{
- #region Constructors
///
/// Initializes a new instance of the class.
///
@@ -25,26 +18,19 @@ public MySqlQueryRepository(ICakeLog log)
{
}
- #endregion
-
-
-
-
- #region Methods
- ///
- /// Opens a connection to the database
- ///
- /// The connectionString to connect with.
- protected override IDbConnection OpenConnection(string connectionString)
+ ///
+ protected override IDbConnection? OpenConnection(string connectionString)
{
- IDbConnection con = MySqlClientFactory.Instance.CreateConnection();
+ var connection = MySqlClientFactory.Instance.CreateConnection();
- con.ConnectionString = connectionString;
- con.Open();
+ if (connection is not null)
+ {
+ connection.ConnectionString = connectionString;
+ connection.Open();
+ }
- return con;
+ return connection;
}
- #endregion
}
-}
\ No newline at end of file
+}
diff --git a/src/Cake.SqlTools/Repositories/Types/NpgsqlQueryRepository.cs b/src/Cake.SqlTools/Repositories/Types/NpgsqlQueryRepository.cs
index 90878c8..3187a42 100644
--- a/src/Cake.SqlTools/Repositories/Types/NpgsqlQueryRepository.cs
+++ b/src/Cake.SqlTools/Repositories/Types/NpgsqlQueryRepository.cs
@@ -1,21 +1,14 @@
-#region Using Statements
-using System.Data;
-
+using System.Data;
using Cake.Core.Diagnostics;
-
using Npgsql;
-#endregion
-
-
namespace Cake.SqlTools
{
///
- /// Provides a method to execture sql queries against a PostgresSql database
+ /// Provides a method to execute sql queries against a PostgresSql database
///
public class NpgsqlQueryRepository : BaseSqlQueryRepository
{
- #region Constructors
///
/// Initializes a new instance of the class.
///
@@ -25,24 +18,15 @@ public NpgsqlQueryRepository(ICakeLog log)
{
}
- #endregion
-
-
-
-
- #region Methods
- ///
- /// Opens a connection to the database
- ///
- /// The connectionString to connect with.
- protected override IDbConnection OpenConnection(string connectionString)
+ ///
+ protected override IDbConnection? OpenConnection(string connectionString)
{
- NpgsqlConnection con = new NpgsqlConnection(connectionString);
- con.Open();
+ var connection = new NpgsqlConnection(connectionString);
+
+ connection.Open();
- return con;
+ return connection;
}
- #endregion
}
}
diff --git a/src/Cake.SqlTools/Settings/SqlQuerySettings.cs b/src/Cake.SqlTools/Settings/SqlQuerySettings.cs
index 19057d5..0f90a05 100644
--- a/src/Cake.SqlTools/Settings/SqlQuerySettings.cs
+++ b/src/Cake.SqlTools/Settings/SqlQuerySettings.cs
@@ -1,44 +1,33 @@
-
-
-
-namespace Cake.SqlTools
+namespace Cake.SqlTools
{
///
- /// The settings to use when executing sql queries
+ /// The settings to use when executing sql queries.
///
public class SqlQuerySettings
{
- #region Constructors
///
/// Initializes a new instance of the class.
///
public SqlQuerySettings()
{
- this.Provider = "MsSql";
- this.ConnectionString = "";
- this.AllowLogs = true;
+ Provider = "MsSql";
+ ConnectionString = "";
+ AllowLogs = true;
}
- #endregion
-
-
-
-
- #region Properties
///
- /// Gets or sets the name of the provider to connect with
+ /// Gets or sets the name of the provider to connect with.
///
public string Provider { get; set; }
-
+
///
- /// Gets or sets the sql connection string to connect with
+ /// Gets or sets the sql connection string to connect with.
///
public string ConnectionString { get; set; }
///
- /// Gets or sets whether logs can be written or not
+ /// Gets or sets whether logs can be written or not.
///
public bool AllowLogs { get; set; }
- #endregion
}
-}
\ No newline at end of file
+}
diff --git a/src/Cake.SqlTools/icon.png b/src/Cake.SqlTools/icon.png
new file mode 100644
index 0000000..84c2a82
Binary files /dev/null and b/src/Cake.SqlTools/icon.png differ
diff --git a/src/SolutionInfo.cs b/src/SolutionInfo.cs
deleted file mode 100644
index 01c75fa..0000000
--- a/src/SolutionInfo.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-//------------------------------------------------------------------------------
-//
-// This code was generated by Cake.
-//
-//------------------------------------------------------------------------------
-using System.Reflection;
-
-[assembly: AssemblyVersion("1.0.1")]
-[assembly: AssemblyFileVersion("1.0.1")]
-[assembly: AssemblyInformationalVersion("1.0.1")]
-[assembly: AssemblyCopyright("Copyright (c) 2015 - 2021 Phillip Sharpe")]
-