From f502116801dbf17c20e1068d8ba46702ae0b192c Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Wed, 7 Feb 2024 14:26:23 +0200 Subject: [PATCH 01/11] Initial implementation --- ...cuteQueryToFile_build_and_test_on_main.yml | 19 ++ ...cuteQueryToFile_build_and_test_on_push.yml | 19 ++ .../workflows/ExecuteQueryToFile_release.yml | 13 + .../Apache-2.0 | 93 +++++++ .../CHANGELOG.md | 5 + ...crosoftSQL.ExecuteQueryToFile.Tests.csproj | 41 +++ .../GlobalSuppressions.cs | 7 + .../TestData/Test_image.png | Bin 0 -> 1944 bytes .../TestData/Test_text.txt | 103 ++++++++ .../UnitTests.cs | 243 ++++++++++++++++++ .../docker-compose.yml | 13 + ...Frends.MicrosoftSQL.ExecuteQueryToFile.sln | 40 +++ .../Definitions/CsvFileWriter.cs | 187 ++++++++++++++ .../Definitions/CsvOptions.cs | 147 +++++++++++ .../Definitions/Input.cs | 39 +++ .../Definitions/Options.cs | 31 +++ .../Definitions/Result.cs | 36 +++ .../Definitions/SqlParameter.cs | 31 +++ .../Enums/CsvFieldDelimiter.cs | 16 ++ .../Enums/CsvLineBreak.cs | 15 ++ .../Enums/FileEncoding.cs | 17 ++ .../Enums/ReturnFormat.cs | 13 + .../Enums/SqlDataTypes.cs | 42 +++ .../Frends.MicrosoftSQL.ExecuteQueryToFile.cs | 62 +++++ ...nds.MicrosoftSQL.ExecuteQueryToFile.csproj | 47 ++++ .../FrendsTaskMetadata.json | 7 + .../GlobalSuppressions.cs | 12 + .../README.md | 34 +++ 28 files changed, 1332 insertions(+) create mode 100644 .github/workflows/ExecuteQueryToFile_build_and_test_on_main.yml create mode 100644 .github/workflows/ExecuteQueryToFile_build_and_test_on_push.yml create mode 100644 .github/workflows/ExecuteQueryToFile_release.yml create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Apache-2.0 create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/CHANGELOG.md create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests.csproj create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/GlobalSuppressions.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/TestData/Test_image.png create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/TestData/Test_text.txt create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/docker-compose.yml create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.sln create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvFileWriter.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvOptions.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Input.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Options.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Result.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/SqlParameter.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/CsvFieldDelimiter.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/CsvLineBreak.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/FileEncoding.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/ReturnFormat.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/SqlDataTypes.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/FrendsTaskMetadata.json create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/GlobalSuppressions.cs create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/README.md diff --git a/.github/workflows/ExecuteQueryToFile_build_and_test_on_main.yml b/.github/workflows/ExecuteQueryToFile_build_and_test_on_main.yml new file mode 100644 index 0000000..8a69b12 --- /dev/null +++ b/.github/workflows/ExecuteQueryToFile_build_and_test_on_main.yml @@ -0,0 +1,19 @@ +name: ExecuteQueryToFile_build_main + +on: + push: + branches: + - main + paths: + - 'Frends.MicrosoftSQL.ExecuteQueryToFile/**' + workflow_dispatch: + +jobs: + build: + uses: FrendsPlatform/FrendsTasks/.github/workflows/linux_build_main.yml@main + with: + workdir: Frends.MicrosoftSQL.ExecuteQueryToFile + prebuild_command: docker-compose -f ./Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/docker-compose.yml up -d + secrets: + badge_service_api_key: ${{ secrets.BADGE_SERVICE_API_KEY }} + \ No newline at end of file diff --git a/.github/workflows/ExecuteQueryToFile_build_and_test_on_push.yml b/.github/workflows/ExecuteQueryToFile_build_and_test_on_push.yml new file mode 100644 index 0000000..78ca2eb --- /dev/null +++ b/.github/workflows/ExecuteQueryToFile_build_and_test_on_push.yml @@ -0,0 +1,19 @@ +name: ExecuteQueryToFile_build_test + +on: + push: + branches-ignore: + - main + paths: + - 'Frends.MicrosoftSQL.ExecuteQueryToFile/**' + workflow_dispatch: + +jobs: + build: + uses: FrendsPlatform/FrendsTasks/.github/workflows/linux_build_test.yml@main + with: + workdir: Frends.MicrosoftSQL.ExecuteQueryToFile + prebuild_command: docker-compose -f ./Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/docker-compose.yml up -d + secrets: + badge_service_api_key: ${{ secrets.BADGE_SERVICE_API_KEY }} + test_feed_api_key: ${{ secrets.TASKS_TEST_FEED_API_KEY }} diff --git a/.github/workflows/ExecuteQueryToFile_release.yml b/.github/workflows/ExecuteQueryToFile_release.yml new file mode 100644 index 0000000..78a8cf9 --- /dev/null +++ b/.github/workflows/ExecuteQueryToFile_release.yml @@ -0,0 +1,13 @@ +name: ExecuteQueryToFile_release + +on: + workflow_dispatch: + +jobs: + build: + uses: FrendsPlatform/FrendsTasks/.github/workflows/release.yml@main + with: + workdir: Frends.MicrosoftSQL.ExecuteQueryToFile + secrets: + feed_api_key: ${{ secrets.TASKS_FEED_API_KEY }} + \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Apache-2.0 b/Frends.MicrosoftSQL.ExecuteQueryToFile/Apache-2.0 new file mode 100644 index 0000000..a20cf5a --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Apache-2.0 @@ -0,0 +1,93 @@ +Apache License 2.0 +SPDX identifier +Apache-2.0 +License text + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + + "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +Standard License Header + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +Notes + +This license was released January 2004 +SPDX web page + + https://spdx.org/licenses/Apache-2.0.html + +Notice + +This license content is provided by the SPDX project. For more information about licenses.nuget.org, see our documentation. + +Data pulled from spdx/license-list-data on February 9, 2023. diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/CHANGELOG.md b/Frends.MicrosoftSQL.ExecuteQueryToFile/CHANGELOG.md new file mode 100644 index 0000000..ee043aa --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog + +## [1.0.0] - 2024-02-05 +### Changed +- Initial implementation diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests.csproj b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests.csproj new file mode 100644 index 0000000..923c177 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests.csproj @@ -0,0 +1,41 @@ + + + + net6.0 + + false + + + + 1701;1702;SA0001 + + + + 1701;1702;SA0001 + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + all + runtime; build; native; contentfiles; analyzers + + + + + + + + + + + \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/GlobalSuppressions.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/GlobalSuppressions.cs new file mode 100644 index 0000000..931d7d2 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/GlobalSuppressions.cs @@ -0,0 +1,7 @@ +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Tests")] +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:File should have header", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Tests")] +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:File should have header", Justification = "Following Frends documentation guidelines")] +[assembly: SuppressMessage("StyleCop.CSharp.NamingRules", "SA1309:Field names should not begin with underscore", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Tests")] +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1629:Documentation text should end with a period", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Tests")] diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/TestData/Test_image.png b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/TestData/Test_image.png new file mode 100644 index 0000000000000000000000000000000000000000..7055e4111428ff4423d32995865c2453dd115587 GIT binary patch literal 1944 zcma)-c{~#e0LO=s^c+#hQM6)_`^cShb~H5ieP44`LwM{7=^#tXrj$y{ea_LN94Yq^ zWA@yZVdhF=&2v2OpZE9sTF(C2@})fH770010Qfmxb4 z#Cff~a1TFiCD~PE;*bw6(U8RFTO^JQ`Hg-FDSodAx>&5HR8e43EcalJhxi0~?G&$A z6#abX>yQk;k9_LC3d}WjNp`BN3_EQlVJEm>N>cS;R1;?R<=Se#@lxGNkNP2_Z+!aM z%a_j%ugvZR$4(Zue%&`L}%}+|WZ(4fqf8tWowyx1$kpX5=SjWJi^m$$$ zb#nQvEmMqxjQUq)56?gTxRdMv>@A47efGn|cDTiY7Nb=j68rM*!r+9iAI zSoSm?NbW86Cka_u!%t`2 z8G@L5V$fdIZ}Mj$JlpLq_%R;KB9*e4Sf_f<_fPjeP^AqU^5#b@ir~VEKgGXiNa!L!odi5s)*yBuC^pN$sVf%d)f^~|ist<35tav!6{cSoH6p0aFs6cNhg9SAuEVq@4zwNrsKA?a~B=eOKq#4Aw)UbF?0CqO_!Uzf}j^O9@-?F zL}Ci*kR*0x9LGy{U3a6_bj$g?!L@7}x!vtSsrrvuI30A&Zd$F|<=(tp9kb_zww zsY{NzLLT5#(^ax(Iua^zgPoI{a)lgrrSm{@dmRycq39|4v2@Ah{@Rqzx#qtXE7WY= za<#66ZNA1HZmWq=lm}YtQv?YKkH><{8=d;nr{Z!8o3C9ApE1?UlHEwvW+*)+1Jra3 zuh)FXlpY)X8xK>FO$jrCZlyOo> z^3b)A+c<3_N!!9tv)KJ+x0dh@Qha=(VNHX24sTjqGTu?k&2&m*1n}=NzSZeaugXg* z$M~wr{)IP3pltSMCxCGUQ?U zGy4U1srJmhogQ9uRqpl_vQToRE0pj1G!EVc74t8pxXL+tHapgx998vz&%0!$kxo(#{yOJP= z4`Af{-bTg+%m(V{vICPS<-U+o-W3~U8YTmo68*)&>(%S?9)ID3dVEiZir&{_AVuRK z^q>$>^_nFo*lOU9*qaA?@j3>(IQ_`T7MFosjn6U&k@WCl*yMFMH-=^=OJK-!{y0|u zLg66;b5hEc9acL=Gy<=s@*Epoh8A!B=B|cN;Dm!0`$QyqNE>uzk +/// docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Salakala123!" -p 1433:1433 --name sql1 --hostname sql1 -d mcr.microsoft.com/mssql/server:2019-CU18-ubuntu-20.04 +/// with Git bash add winpty to the start of +/// winpty docker exec -it sql1 "bash" +/// /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Salakala123!" +/// Check rows before CleanUp: +/// SELECT* FROM TestTable +/// GO +/// Optional queries: +/// SELECT Name FROM sys.Databases; +/// GO +/// SELECT* FROM INFORMATION_SCHEMA.TABLES; +/// GO +/// +[TestFixture] +public class UnitTests +{ + private static readonly string _connString = "Server=127.0.0.1,1433;Database=Master;User Id=SA;Password=Salakala123!"; + private static readonly string _tableName = "TestTable"; + private static readonly string _destination = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../TestData/test.csv"); + + [SetUp] + public void Init() + { + using (var connection = new SqlConnection(_connString)) + { + connection.Open(); + var createTable = connection.CreateCommand(); + createTable.CommandText = $@"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN CREATE TABLE {_tableName} ( Id int, LastName varchar(255), FirstName varchar(255), Salary decimal(6,2), Image Image, TestText VarBinary(MAX)); END"; + createTable.ExecuteNonQuery(); + connection.Close(); + } + + var parameters = new System.Data.SqlClient.SqlParameter[] + { + new System.Data.SqlClient.SqlParameter("@Hash", SqlDbType.VarBinary) + { + Value = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png")), + }, + new System.Data.SqlClient.SqlParameter("@TestText", SqlDbType.VarBinary) + { + Value = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_text.txt")), + }, + }; + + InsertTestData($"Insert into {_tableName} (Id, LastName, FirstName, Salary, Image, TestText) values (1,'Meikalainen','Matti',1523.25, {parameters[0].ParameterName}, {parameters[1].ParameterName});", parameters); + } + + [TearDown] + public void CleanUp() + { + using (var connection = new SqlConnection(_connString)) + { + connection.Open(); + var createTable = connection.CreateCommand(); + createTable.CommandText = $@"IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN DROP TABLE IF EXISTS {_tableName}; END"; + createTable.ExecuteNonQuery(); + connection.Close(); + } + + // Clean and remove destination directory + File.Delete(_destination); + } + + [Test] + public async Task ExecuteQueryToFile_StringWithApostrophe() + { + var query = new Input + { + Query = $"Select Id, LastName, FirstName, REPLACE(Salary, '.', ',') AS 'Salary' from {_tableName}", + QueryParameters = Array.Empty(), + ConnectionString = _connString, + OutputFilePath = _destination, + }; + + var options = new Options + { + TimeoutSeconds = 30, + CsvOptions = new CsvOptions + { + FieldDelimiter = CsvFieldDelimiter.Semicolon, + LineBreak = CsvLineBreak.CRLF, + FileEncoding = FileEncoding.UTF8, + EnableBom = false, + IncludeHeadersInOutput = true, + SanitizeColumnHeaders = false, + AddQuotesToDates = false, + AddQuotesToStrings = true, + DateFormat = "yyyy-MM-dd", + DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", + }, + }; + + await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + var output = File.ReadAllText(_destination); + + Assert.AreEqual("Id;LastName;FirstName;Salary\r\n1;\"Meikalainen\";\"Matti\";\"1523,25\"\r\n", output); + } + + [Test] + public async Task ExecuteQueryToFile_StringWithoutApostrophe() + { + var query = new Input + { + Query = $"Select Id, LastName, FirstName, REPLACE(Salary, '.', ',') AS 'Salary' from {_tableName}", + QueryParameters = Array.Empty(), + ConnectionString = _connString, + OutputFilePath = _destination, + }; + + var options = new Options + { + TimeoutSeconds = 30, + CsvOptions = new CsvOptions + { + FieldDelimiter = CsvFieldDelimiter.Semicolon, + LineBreak = CsvLineBreak.CRLF, + FileEncoding = FileEncoding.UTF8, + EnableBom = false, + IncludeHeadersInOutput = true, + SanitizeColumnHeaders = false, + AddQuotesToDates = false, + AddQuotesToStrings = false, + DateFormat = "yyyy-MM-dd", + DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", + }, + }; + + await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + + var output = File.ReadAllText(_destination); + + Assert.AreEqual("Id;LastName;FirstName;Salary\r\n1;Meikalainen;Matti;1523,25\r\n", output); + } + + [Test] + public async Task ExecuteQueryToFile_WithImageDBType() + { + var query = new Input + { + Query = $"SELECT Image from {_tableName}", + QueryParameters = Array.Empty(), + ConnectionString = _connString, + OutputFilePath = _destination, + }; + + var options = new Options + { + TimeoutSeconds = 30, + CsvOptions = new CsvOptions + { + FieldDelimiter = CsvFieldDelimiter.Semicolon, + LineBreak = CsvLineBreak.CRLF, + FileEncoding = FileEncoding.UTF8, + EnableBom = false, + IncludeHeadersInOutput = false, + SanitizeColumnHeaders = false, + AddQuotesToDates = false, + AddQuotesToStrings = false, + DateFormat = "yyyy-MM-dd", + DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", + }, + }; + + await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + + var output = File.ReadAllText(_destination); + + Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png"))), output.TrimEnd(Environment.NewLine.ToCharArray())); + } + + [Test] + public async Task ExecuteQueryToFile_WithBinaryDBType() + { + var query = new Input + { + Query = $"SELECT TestText from {_tableName}", + QueryParameters = Array.Empty(), + ConnectionString = _connString, + OutputFilePath = _destination, + }; + + var options = new Options + { + TimeoutSeconds = 30, + CsvOptions = new CsvOptions + { + FieldDelimiter = CsvFieldDelimiter.Semicolon, + LineBreak = CsvLineBreak.CRLF, + FileEncoding = FileEncoding.UTF8, + EnableBom = false, + IncludeHeadersInOutput = false, + SanitizeColumnHeaders = false, + AddQuotesToDates = false, + AddQuotesToStrings = false, + DateFormat = "yyyy-MM-dd", + DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", + }, + }; + + await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + + var output = File.ReadAllText(_destination); + + Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_Text.txt"))), output.TrimEnd(Environment.NewLine.ToCharArray())); + } + + private static void InsertTestData(string commandText, System.Data.SqlClient.SqlParameter[] parameters = null) + { + using var sqlConnection = new SqlConnection(_connString); + sqlConnection.Open(); + + using (var command = new SqlCommand()) + { + command.CommandText = commandText; + command.CommandType = CommandType.Text; + command.CommandTimeout = 30; + command.Connection = sqlConnection; + if (parameters != null) + { + foreach (var param in parameters) + { + command.Parameters.Add(param); + } + } + + command.ExecuteNonQuery(); + } + + sqlConnection.Close(); + } +} \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/docker-compose.yml b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/docker-compose.yml new file mode 100644 index 0000000..6a241cc --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/docker-compose.yml @@ -0,0 +1,13 @@ +version: '3' + +services: + sql1: + container_name: sql1 + image: mcr.microsoft.com/mssql/server:2019-CU18-ubuntu-20.04 + hostname: + sql1 + environment: + MSSQL_SA_PASSWORD: "Salakala123!" + ACCEPT_EULA: "Y" + ports: + - "1433:1433" \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.sln b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.sln new file mode 100644 index 0000000..9c5b962 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.sln @@ -0,0 +1,40 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.32112.339 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Frends.MicrosoftSQL.ExecuteQueryToFile", "Frends.MicrosoftSQL.ExecuteQueryToFile\Frends.MicrosoftSQL.ExecuteQueryToFile.csproj", "{35C305C0-8108-4A98-BB1D-AFE5C926239E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Frends.MicrosoftSQL.ExecuteQueryToFile.Tests", "Frends.MicrosoftSQL.ExecuteQueryToFile.Tests\Frends.MicrosoftSQL.ExecuteQueryToFile.Tests.csproj", "{8CA92187-8E4F-4414-803B-EC899479022E}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{78F7F22E-6E20-4BCE-8362-0C558568B729}" + ProjectSection(SolutionItems) = preProject + CHANGELOG.md = CHANGELOG.md + ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_main.yml = ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_main.yml + ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_push.yml = ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_push.yml + ..\.github\workflows\ExecuteQueryToFile_release.yml = ..\.github\workflows\ExecuteQueryToFile_release.yml + README.md = README.md + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Release|Any CPU.Build.0 = Release|Any CPU + {8CA92187-8E4F-4414-803B-EC899479022E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8CA92187-8E4F-4414-803B-EC899479022E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8CA92187-8E4F-4414-803B-EC899479022E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8CA92187-8E4F-4414-803B-EC899479022E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {55BC6629-85C9-48D8-8CA2-B0046AF1AF4B} + EndGlobalSection +EndGlobal diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvFileWriter.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvFileWriter.cs new file mode 100644 index 0000000..89647a7 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvFileWriter.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Data.SqlClient; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using CsvHelper; +using CsvHelper.Configuration; +using Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; + +internal class CsvFileWriter +{ + internal CsvFileWriter(SqlCommand sqlCommand, Input input, CsvOptions options) + { + SqlCommand = sqlCommand; + Input = input; + Options = options; + } + + private SqlCommand SqlCommand { get; set; } + + private Input Input { get; set; } + + private CsvOptions Options { get; set; } + + public async Task SaveQueryToCSV(CancellationToken cancellationToken) + { + var output = 0; + var encoding = GetEncoding(Options.FileEncoding, Options.EnableBom, Options.EncodingInString); + + using (var writer = new StreamWriter(Input.OutputFilePath, false, encoding)) + using (var csvFile = CreateCsvWriter(Options.GetFieldDelimiterAsString(), writer)) + { + writer.NewLine = Options.GetLineBreakAsString(); + + var reader = await SqlCommand.ExecuteReaderAsync(cancellationToken); + output = DataReaderToCsv(reader, csvFile, Options, cancellationToken); + + csvFile.Flush(); + } + + return new Result(output, Input.OutputFilePath, Path.GetFileName(Input.OutputFilePath)); + } + + private static CsvWriter CreateCsvWriter(string delimiter, TextWriter writer) + { + var csvOptions = new CsvConfiguration(CultureInfo.InvariantCulture) + { + Delimiter = delimiter, + }; + + return new CsvWriter(writer, csvOptions); + } + + private static string FormatDbHeader(string header, bool forceSpecialFormatting) + { + if (!forceSpecialFormatting) return header; + + // First part of regex removes all non-alphanumeric ('_' also allowed) chars from the whole string. + // Second part removed any leading numbers or underscoress. + var rgx = new Regex("[^a-zA-Z0-9_-]|^[0-9_]+"); + header = rgx.Replace(header, string.Empty); + return header.ToLower(); + } + + private static string FormatDbValue(object value, string dbTypeName, Type dotnetType, CsvOptions options) + { + if (value == null || value == DBNull.Value) + { + if (dotnetType == typeof(string)) return "\"\""; + if (dotnetType == typeof(DateTime) && options.AddQuotesToDates) return "\"\""; + return string.Empty; + } + + if (dotnetType == typeof(string)) + { + var str = (string)value; + options.GetFieldDelimiterAsString(); + str = str.Replace("\"", "\\\""); + str = str.Replace("\r\n", " "); + str = str.Replace("\r", " "); + str = str.Replace("\n", " "); + if (options.AddQuotesToStrings) + return $"\"{str}\""; + return str; + } + + if (dotnetType == typeof(DateTime)) + { + var dateTime = (DateTime)value; + var dbType = dbTypeName?.ToLower(); + string output = dbType switch + { + "date" => dateTime.ToString(options.DateFormat, CultureInfo.InvariantCulture), + _ => dateTime.ToString(options.DateTimeFormat, CultureInfo.InvariantCulture), + }; + if (options.AddQuotesToDates) return $"\"{output}\""; + return output; + } + + if (dotnetType == typeof(float)) + return ((float)value).ToString("0.###########", CultureInfo.InvariantCulture); + + if (dotnetType == typeof(double)) + return ((double)value).ToString("0.###########", CultureInfo.InvariantCulture); + + if (dotnetType == typeof(decimal)) + return ((decimal)value).ToString("0.###########", CultureInfo.InvariantCulture); + + if (dotnetType == typeof(byte[])) + return BitConverter.ToString((byte[])value); + + return value.ToString(); + } + + private static int DataReaderToCsv( + DbDataReader reader, + CsvWriter csvWriter, + CsvOptions options, + CancellationToken cancellationToken) + { + // Write header and remember column indexes to include. + var columnIndexesToInclude = new List(); + for (var i = 0; i < reader.FieldCount; i++) + { + var columnName = reader.GetName(i); + var includeColumn = + options.ColumnsToInclude == null || + options.ColumnsToInclude.Length == 0 || + options.ColumnsToInclude.Contains(columnName); + + if (includeColumn) + { + if (options.IncludeHeadersInOutput) + { + var formattedHeader = FormatDbHeader(columnName, options.SanitizeColumnHeaders); + csvWriter.WriteField(formattedHeader); + } + + columnIndexesToInclude.Add(i); + } + + cancellationToken.ThrowIfCancellationRequested(); + } + + if (options.IncludeHeadersInOutput) csvWriter.NextRecord(); + + int count = 0; + while (reader.Read()) + { + foreach (var columnIndex in columnIndexesToInclude) + { + var value = reader.GetValue(columnIndex); + var dbTypeName = reader.GetDataTypeName(columnIndex); + var dotnetType = reader.GetFieldType(columnIndex); + var formattedValue = FormatDbValue(value, dbTypeName, dotnetType, options); + csvWriter.WriteField(formattedValue, false); + cancellationToken.ThrowIfCancellationRequested(); + } + + csvWriter.NextRecord(); + count++; + } + + return count; + } + + private static Encoding GetEncoding(FileEncoding optionsFileEncoding, bool optionsEnableBom, string optionsEncodingInString) + { + return optionsFileEncoding switch + { + FileEncoding.Other => Encoding.GetEncoding(optionsEncodingInString), + FileEncoding.ASCII => Encoding.ASCII, + FileEncoding.ANSI => Encoding.Default, + FileEncoding.UTF8 => optionsEnableBom ? new UTF8Encoding(true) : new UTF8Encoding(false), + FileEncoding.Unicode => Encoding.Unicode, + _ => Encoding.ASCII, + }; + } +} diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvOptions.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvOptions.cs new file mode 100644 index 0000000..57babfc --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvOptions.cs @@ -0,0 +1,147 @@ +using System; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; + +/// +/// Options for CSV outout. +/// +public class CsvOptions +{ + /// + /// Columns to include in the CSV output. Leave empty to include all columns in output. + /// + /// [ column1, column2 ] + public string[] ColumnsToInclude { get; set; } + + /// + /// What to use as field separators. + /// + /// CsvDelimiter.SemiColon + [DefaultValue(CsvFieldDelimiter.Semicolon)] + public CsvFieldDelimiter FieldDelimiter { get; set; } = CsvFieldDelimiter.Semicolon; + + /// + /// Custom field delimiter as a string. + /// + /// ; + [UIHint(nameof(FieldDelimiter), "", CsvFieldDelimiter.Custom)] + public string CustomFieldDelimiter { get; set; } + + /// + /// What to use as line breaks. + /// + /// CsvLineBreak.CRLF + [DefaultValue(CsvLineBreak.CRLF)] + public CsvLineBreak LineBreak { get; set; } = CsvLineBreak.CRLF; + + /// + /// Output file encoding. + /// + /// FileEncoding.UTF8 + [DefaultValue(FileEncoding.UTF8)] + public FileEncoding FileEncoding { get; set; } + + /// + /// Enable Bom. + /// + /// true + [UIHint(nameof(FileEncoding), "", FileEncoding.UTF8)] + public bool EnableBom { get; set; } + + /// + /// File encoding to be used. A partial list of possible encodings: https://en.wikipedia.org/wiki/Windows_code_page#List + /// + /// utf-8 + [UIHint(nameof(FileEncoding), "", FileEncoding.Other)] + public string EncodingInString { get; set; } + + /// + /// Whether to include headers in output. + /// + /// false + [DefaultValue(true)] + public bool IncludeHeadersInOutput { get; set; } = true; + + /// + /// Whether to sanitize headers in output: + /// - Strip any chars that are not 0-9, a-z or _ + /// - Make sure that column does not start with a number or underscore. + /// - Force lower case. + /// + /// false + [DefaultValue(true)] + public bool SanitizeColumnHeaders { get; set; } = true; + + /// + /// Whether to add quotes around DATE and DATETIME fields. + /// + /// false + [DefaultValue(true)] + public bool AddQuotesToDates { get; set; } = true; + + /// + /// Whether to add quotes around string typed fields. + /// + /// false + [DefaultValue(true)] + public bool AddQuotesToStrings { get; set; } = true; + + /// + /// Date format to use for formatting DATE columns, use .NET formatting tokens. + /// Note that formatting is done using invariant culture. + /// + /// yyyy-MM-dd + [DefaultValue("\"yyyy-MM-dd\"")] + public string DateFormat { get; set; } = "yyyy-MM-dd"; + + /// + /// Date format to use for formatting DATETIME columns, use .NET formatting tokens. + /// Note that formatting is done using invariant culture. + /// + /// yyyy-MM-dd HH:mm:ss + [DefaultValue("\"yyyy-MM-dd HH:mm:ss\"")] + public string DateTimeFormat { get; set; } = "yyyy-MM-dd HH:mm:ss"; + + /// + /// Helper method to return the field delimiter as string. + /// + /// string + internal string GetFieldDelimiterAsString() + { + switch (FieldDelimiter) + { + case CsvFieldDelimiter.Comma: + return ","; + case CsvFieldDelimiter.Pipe: + return "|"; + case CsvFieldDelimiter.Semicolon: + return ";"; + case CsvFieldDelimiter.Custom: + return CustomFieldDelimiter; + default: + throw new Exception($"Unknown field delimeter: {FieldDelimiter}"); + } + } + + /// + /// Helper method to return the line break as string. + /// + /// string + internal string GetLineBreakAsString() + { + switch (LineBreak) + { + case CsvLineBreak.CRLF: + return "\r\n"; + case CsvLineBreak.CR: + return "\r"; + case CsvLineBreak.LF: + return "\n"; + default: + throw new Exception($"Unknown field delimeter: {FieldDelimiter}"); + } + } +} \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Input.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Input.cs new file mode 100644 index 0000000..2308780 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Input.cs @@ -0,0 +1,39 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; + +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +/// +/// Input class usually contains parameters that are required. +/// +public class Input +{ + /// + /// Query to execute. + /// + /// SELECT * FROM table + [DisplayFormat(DataFormatString = "Sql")] + public string Query { get; set; } + + /// + /// Query parameters. + /// + /// [ { Name = test, Value = test_value, SqlDataType = SqlDataTypes.Auto } ] + public SqlParameter[] QueryParameters { get; set; } + + /// + /// Database connection string. + /// + /// Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword; + [DefaultValue("\"Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;\"")] + [PasswordPropertyText] + [DisplayFormat(DataFormatString = "Text")] + public string ConnectionString { get; set; } + + /// + /// Output file path. + /// + /// C:\path\tp\file.csv + [DefaultValue("")] + public string OutputFilePath { get; set; } +} \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Options.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Options.cs new file mode 100644 index 0000000..6fe7487 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Options.cs @@ -0,0 +1,31 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; + +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +/// +/// Options class usually contains parameters that are required. +/// +public class Options +{ + /// + /// Operation timeout (seconds). + /// + /// 30 + [DefaultValue(30)] + public int TimeoutSeconds { get; set; } + + /// + /// Determines in what format the query is written. + /// + /// ReturnFormat.JSON + [DefaultValue(ReturnFormat.CSV)] + public ReturnFormat ReturnFormat { get; set; } + + /// + /// Csv options. + /// + [UIHint(nameof(ReturnFormat), "", ReturnFormat.CSV)] + public CsvOptions CsvOptions { get; set; } +} \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Result.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Result.cs new file mode 100644 index 0000000..80cf3c7 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Result.cs @@ -0,0 +1,36 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; + +/// +/// Result class usually contains properties of the return object. +/// +public class Result +{ + internal Result(int entriesWritten, string path, string name) + { + EntriesWritten = entriesWritten; + Path = path; + FileName = name; + } + + internal Result() + { + } + + /// + /// Amount of entries written. + /// + /// 2 + public int EntriesWritten { get; private set; } + + /// + /// Path to the file. + /// + /// C:\test.csv + public string Path { get; set; } + + /// + /// Name of the file. + /// + /// test.csv + public string FileName { get; set; } +} diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/SqlParameter.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/SqlParameter.cs new file mode 100644 index 0000000..bea3d7f --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/SqlParameter.cs @@ -0,0 +1,31 @@ +using System.ComponentModel; +using Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; + +/// +/// Sql query parameter class. +/// +public class SqlParameter +{ + /// + /// The name of the parameter. + /// + /// first_name + public string Name { get; set; } + + /// + /// The value of the parameter. + /// + /// FirstName + public object Value { get; set; } + + /// + /// SQL Server-specific data type. + /// Note! Use SqlDataType.Auto if not sure of the type. + /// See https://learn.microsoft.com/en-us/dotnet/api/system.data.sqldbtype?view=net-7.0 for more information. + /// + /// SqlDbTypes.Empty + [DefaultValue(SqlDataTypes.Auto)] + public SqlDataTypes SqlDataType { get; set; } +} \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/CsvFieldDelimiter.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/CsvFieldDelimiter.cs new file mode 100644 index 0000000..1c1cf33 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/CsvFieldDelimiter.cs @@ -0,0 +1,16 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +#pragma warning disable CS1591 // Self-explanatory + +/// +/// CSV field delimeter options. +/// +public enum CsvFieldDelimiter +{ + Comma, + Semicolon, + Pipe, + Custom, +} + +#pragma warning restore CS1591 // Self-explanatory diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/CsvLineBreak.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/CsvLineBreak.cs new file mode 100644 index 0000000..a75f597 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/CsvLineBreak.cs @@ -0,0 +1,15 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +#pragma warning disable CS1591 // Self-explanatory + +/// +/// CSV line break options. +/// +public enum CsvLineBreak +{ + CRLF, + LF, + CR, +} + +#pragma warning restore CS1591 // Self-explanatory diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/FileEncoding.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/FileEncoding.cs new file mode 100644 index 0000000..cdc2840 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/FileEncoding.cs @@ -0,0 +1,17 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +#pragma warning disable CS1591 // Self-explanatory + +/// +/// File encoding used to encode the file. +/// +public enum FileEncoding +{ + UTF8, + ANSI, + ASCII, + Unicode, + Other, +} + +#pragma warning restore CS1591 // Self-explanatory \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/ReturnFormat.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/ReturnFormat.cs new file mode 100644 index 0000000..f37af8c --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/ReturnFormat.cs @@ -0,0 +1,13 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +#pragma warning disable CS1591 // Self-explanatory + +/// +/// Enumeration for output format. +/// +public enum ReturnFormat +{ + CSV, +} + +#pragma warning restore CS1591 // Self-explanatory \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/SqlDataTypes.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/SqlDataTypes.cs new file mode 100644 index 0000000..3020359 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/SqlDataTypes.cs @@ -0,0 +1,42 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +/// +/// SQL Server-specific data type. +/// +public enum SqlDataTypes +{ +#pragma warning disable CS1591 // self explanatory + Auto = -1, + BigInt = 0, + Binary = 1, + Bit = 2, + Char = 3, + DateTime = 4, + Decimal = 5, + Float = 6, + Image = 7, + Int = 8, + Money = 9, + NChar = 10, + NText = 11, + NVarChar = 12, + Real = 13, + UniqueIdentifier = 14, + SmallDateTime = 15, + SmallInt = 16, + SmallMoney = 17, + Text = 18, + Timestamp = 19, + TinyInt = 20, + VarBinary = 21, + VarChar = 22, + Variant = 23, + Xml = 25, + Udt = 29, + Structured = 30, + Date = 31, + Time = 32, + DateTime2 = 33, + DateTimeOffset = 34 +#pragma warning restore CS1591 // self explanatory +} \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs new file mode 100644 index 0000000..7e872ce --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs @@ -0,0 +1,62 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile; + +using System; +using System.ComponentModel; +using System.Data; +using System.Data.SqlClient; +using System.Data.Common; +using System.Threading; +using System.Threading.Tasks; +using Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; +using Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; + +/// +/// Main class of the Task. +/// +public static class MicrosoftSQL +{ + /// + /// Frends Task for executing Microsoft SQL queries into a file. + /// [Documentation](https://tasks.frends.com/tasks/frends-tasks/Frends.MicrosoftSQL.ExecuteQueryToFile). + /// + /// Input parameters. + /// Options parameters. + /// Cancellation token given by Frends. + /// Object { int EntriesWritten, string Path, string FileName } + public static async Task ExecuteQueryToFile([PropertyTab] Input input, [PropertyTab] Options options, CancellationToken cancellationToken) + { + Result result = new (); + using (var sqlConnection = new SqlConnection(input.ConnectionString)) + { + await sqlConnection.OpenAsync(cancellationToken); + + using var command = BuildSQLCommand(input.Query, input.QueryParameters); + command.CommandTimeout = options.TimeoutSeconds; + command.Connection = sqlConnection; + + switch (options.ReturnFormat) + { + case ReturnFormat.CSV: + var csvWriter = new CsvFileWriter(command, input, options.CsvOptions); + result = await csvWriter.SaveQueryToCSV(cancellationToken); + break; + } + } + + return result; + } + + private static SqlCommand BuildSQLCommand(string query, Definitions.SqlParameter[] parmeters) + { + using var command = new SqlCommand(); + command.CommandText = query; + command.CommandType = CommandType.Text; + + foreach (var parameter in parmeters) + { + command.Parameters.AddWithValue(parameter.Name, parameter.Value); + } + + return command; + } +} diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj new file mode 100644 index 0000000..0573035 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj @@ -0,0 +1,47 @@ + + + + net6.0 + Latest + 0.0.1 + Frends + Frends + Frends + Frends + Frends + MIT + true + Frends Task for executing Microsoft SQL queries into a file. + https://frends.com/ + https://github.com/FrendsPlatform/Frends.MicrosoftSQL/tree/main/Frends.MicrosoftSQL.ExecuteQueryToFile + + + + + PreserveNewest + + + + + + <_Parameter1>$(MSBuildProjectName).Tests + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/FrendsTaskMetadata.json b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/FrendsTaskMetadata.json new file mode 100644 index 0000000..9195abd --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/FrendsTaskMetadata.json @@ -0,0 +1,7 @@ +{ + "Tasks": [ + { + "TaskMethod": "Frends.MicrosoftSQL.ExecuteQueryToFile.MicrosoftSQL.ExecuteQueryToFile" + } + ] +} \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/GlobalSuppressions.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/GlobalSuppressions.cs new file mode 100644 index 0000000..bbd0b8e --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/GlobalSuppressions.cs @@ -0,0 +1,12 @@ +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions")] +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1623:Property summary documentation should match accessors", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions")] +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:File should have header", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile")] +[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1101:Prefix local calls with this", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile")] +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1629:Documentation text should end with a period", Justification = "Following Frends Tasks guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile")] +[assembly: SuppressMessage("Minor Code Smell", "S101:Types should be named in PascalCase", Justification = "Following Frends guidelines", Scope = "type", Target = "~T:Frends.MicrosoftSQL.ExecuteQueryToFile.MicrosoftSQL")] +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:File should have header", Justification = "Following Frends guidelines")] +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1602:Enumeration items should be documented", Justification = "Following Frends guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Enums")] +[assembly: SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1200:Using directives should be placed correctly", Justification = "Following Frends guidelines")] +[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1503:Braces should not be omitted", Justification = "Following Frends guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions")] diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/README.md b/Frends.MicrosoftSQL.ExecuteQueryToFile/README.md new file mode 100644 index 0000000..5a9a438 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/README.md @@ -0,0 +1,34 @@ +# Frends.MicrosoftSQL.ExecuteQueryToFile +Frends Task for executing Microsoft SQL queries into a file. + +[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT) +[![Build](https://github.com/FrendsPlatform/Frends.MicrosoftSQL/actions/workflows/ExecuteQueryToFile_build_and_test_on_main.yml/badge.svg)](https://github.com/FrendsPlatform/Frends.MicrosoftSQL/actions) +![Coverage](https://app-github-custom-badges.azurewebsites.net/Badge?key=FrendsPlatform/Frends.MicrosoftSQL/Frends.MicrosoftSQL.ExecuteQueryToFile|main) + +## Installing + +You can install the Task via frends UI Task View. + +## Building + +### Clone a copy of the repository + +`git clone https://github.com/FrendsPlatform/Frends.MicrosoftSQL.git` + +### Build the project + +`dotnet build` + +### Run tests + +Run the tests + +`dotnet test` + +### Create a NuGet package + +`dotnet pack --configuration Release` + +### Third party licenses + +StyleCop.Analyzer version (unmodified version 1.1.118) used to analyze code uses Apache-2.0 license, full text and source code can be found in https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/README.md From d8680a2e841bd50f1dfb662f7794adc51dc7292a Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Wed, 7 Feb 2024 14:28:02 +0200 Subject: [PATCH 02/11] updated version number --- Frends.MicrosoftSQL.ExecuteQueryToFile/CHANGELOG.md | 2 +- .../Frends.MicrosoftSQL.ExecuteQueryToFile.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/CHANGELOG.md b/Frends.MicrosoftSQL.ExecuteQueryToFile/CHANGELOG.md index ee043aa..78d07f6 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/CHANGELOG.md +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/CHANGELOG.md @@ -1,5 +1,5 @@ # Changelog -## [1.0.0] - 2024-02-05 +## [1.0.0] - 2024-02-07 ### Changed - Initial implementation diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj index 0573035..4333150 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj @@ -3,7 +3,7 @@ net6.0 Latest - 0.0.1 + 1.0.0 Frends Frends Frends From 1f29ea3d10a9c7cd71cb81c6659f62ba48749f49 Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Wed, 7 Feb 2024 14:49:40 +0200 Subject: [PATCH 03/11] CodeQL fixes --- .../UnitTests.cs | 348 ++++++++---------- .../lib/Helper.cs | 48 +++ 2 files changed, 206 insertions(+), 190 deletions(-) create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs index df65f0c..c8a288f 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs @@ -1,93 +1,86 @@ -namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Tests; - -using System; -using System.Data; -using System.Data.SqlClient; -using System.IO; -using System.Threading.Tasks; -using Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; -using Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; -using NUnit.Framework; - +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Tests; + +using System; +using System.Data; +using System.Data.SqlClient; +using System.IO; +using System.Threading.Tasks; +using Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; +using Frends.MicrosoftSQL.ExecuteQueryToFile.Enums; +using NUnit.Framework; + /// -/// docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Salakala123!" -p 1433:1433 --name sql1 --hostname sql1 -d mcr.microsoft.com/mssql/server:2019-CU18-ubuntu-20.04 -/// with Git bash add winpty to the start of -/// winpty docker exec -it sql1 "bash" -/// /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Salakala123!" -/// Check rows before CleanUp: +/// docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Salakala123!" -p 1433:1433 --name sql1 --hostname sql1 -d mcr.microsoft.com/mssql/server:2019-CU18-ubuntu-20.04 +/// with Git bash add winpty to the start of +/// winpty docker exec -it sql1 "bash" +/// /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Salakala123!" +/// Check rows before CleanUp: /// SELECT* FROM TestTable -/// GO -/// Optional queries: -/// SELECT Name FROM sys.Databases; -/// GO -/// SELECT* FROM INFORMATION_SCHEMA.TABLES; +/// GO +/// Optional queries: +/// SELECT Name FROM sys.Databases; +/// GO +/// SELECT* FROM INFORMATION_SCHEMA.TABLES; /// GO /// -[TestFixture] -public class UnitTests -{ - private static readonly string _connString = "Server=127.0.0.1,1433;Database=Master;User Id=SA;Password=Salakala123!"; - private static readonly string _tableName = "TestTable"; - private static readonly string _destination = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../TestData/test.csv"); - - [SetUp] - public void Init() - { - using (var connection = new SqlConnection(_connString)) - { - connection.Open(); - var createTable = connection.CreateCommand(); - createTable.CommandText = $@"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN CREATE TABLE {_tableName} ( Id int, LastName varchar(255), FirstName varchar(255), Salary decimal(6,2), Image Image, TestText VarBinary(MAX)); END"; - createTable.ExecuteNonQuery(); - connection.Close(); - } - - var parameters = new System.Data.SqlClient.SqlParameter[] - { - new System.Data.SqlClient.SqlParameter("@Hash", SqlDbType.VarBinary) - { - Value = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png")), - }, - new System.Data.SqlClient.SqlParameter("@TestText", SqlDbType.VarBinary) - { - Value = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_text.txt")), - }, - }; - - InsertTestData($"Insert into {_tableName} (Id, LastName, FirstName, Salary, Image, TestText) values (1,'Meikalainen','Matti',1523.25, {parameters[0].ParameterName}, {parameters[1].ParameterName});", parameters); - } - - [TearDown] - public void CleanUp() - { - using (var connection = new SqlConnection(_connString)) - { - connection.Open(); - var createTable = connection.CreateCommand(); - createTable.CommandText = $@"IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN DROP TABLE IF EXISTS {_tableName}; END"; - createTable.ExecuteNonQuery(); - connection.Close(); - } - - // Clean and remove destination directory - File.Delete(_destination); - } - - [Test] - public async Task ExecuteQueryToFile_StringWithApostrophe() - { - var query = new Input - { - Query = $"Select Id, LastName, FirstName, REPLACE(Salary, '.', ',') AS 'Salary' from {_tableName}", - QueryParameters = Array.Empty(), - ConnectionString = _connString, - OutputFilePath = _destination, - }; - - var options = new Options - { - TimeoutSeconds = 30, - CsvOptions = new CsvOptions +[TestFixture] +public class UnitTests +{ + private static readonly string _connString = Helper.GetConnectionString(); + private static readonly string _tableName = "TestTable"; + private static readonly string _destination = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../TestData/test.csv"); + + [SetUp] + public void Init() + { + Helper.CreateTestTable(_connString, _tableName); + + var parameters = new System.Data.SqlClient.SqlParameter[] + { + new System.Data.SqlClient.SqlParameter("@Hash", SqlDbType.VarBinary) + { + Value = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png")), + }, + new System.Data.SqlClient.SqlParameter("@TestText", SqlDbType.VarBinary) + { + Value = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_text.txt")), + }, + }; + + Helper.InsertTestData(_connString, $"Insert into {_tableName} (Id, LastName, FirstName, Salary, Image, TestText) values (1,'Meikalainen','Matti',1523.25, {parameters[0].ParameterName}, {parameters[1].ParameterName});", parameters); + } + + [TearDown] + public void CleanUp() + { + using (var connection = new SqlConnection(_connString)) + { + connection.Open(); + var createTable = connection.CreateCommand(); + createTable.CommandText = $@"IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{_tableName}') BEGIN DROP TABLE IF EXISTS {_tableName}; END"; + createTable.ExecuteNonQuery(); + connection.Close(); + } + + // Clean and remove destination directory + File.Delete(_destination); + } + + [Test] + public async Task ExecuteQueryToFile_StringWithApostrophe() + { + var query = new Input + { + Query = $"Select Id, LastName, FirstName, REPLACE(Salary, '.', ',') AS 'Salary' from {_tableName}", + QueryParameters = Array.Empty(), + ConnectionString = _connString, + OutputFilePath = _destination, + }; + + var options = new Options + { + TimeoutSeconds = 30, + CsvOptions = new CsvOptions { FieldDelimiter = CsvFieldDelimiter.Semicolon, LineBreak = CsvLineBreak.CRLF, @@ -99,29 +92,29 @@ public async Task ExecuteQueryToFile_StringWithApostrophe() AddQuotesToStrings = true, DateFormat = "yyyy-MM-dd", DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", - }, - }; - - await MicrosoftSQL.ExecuteQueryToFile(query, options, default); - var output = File.ReadAllText(_destination); - - Assert.AreEqual("Id;LastName;FirstName;Salary\r\n1;\"Meikalainen\";\"Matti\";\"1523,25\"\r\n", output); - } - - [Test] - public async Task ExecuteQueryToFile_StringWithoutApostrophe() - { - var query = new Input - { - Query = $"Select Id, LastName, FirstName, REPLACE(Salary, '.', ',') AS 'Salary' from {_tableName}", - QueryParameters = Array.Empty(), - ConnectionString = _connString, - OutputFilePath = _destination, - }; - - var options = new Options - { - TimeoutSeconds = 30, + }, + }; + + await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + var output = File.ReadAllText(_destination); + + Assert.AreEqual("Id;LastName;FirstName;Salary\r\n1;\"Meikalainen\";\"Matti\";\"1523,25\"\r\n", output); + } + + [Test] + public async Task ExecuteQueryToFile_StringWithoutApostrophe() + { + var query = new Input + { + Query = $"Select Id, LastName, FirstName, REPLACE(Salary, '.', ',') AS 'Salary' from {_tableName}", + QueryParameters = Array.Empty(), + ConnectionString = _connString, + OutputFilePath = _destination, + }; + + var options = new Options + { + TimeoutSeconds = 30, CsvOptions = new CsvOptions { FieldDelimiter = CsvFieldDelimiter.Semicolon, @@ -134,30 +127,30 @@ public async Task ExecuteQueryToFile_StringWithoutApostrophe() AddQuotesToStrings = false, DateFormat = "yyyy-MM-dd", DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", - }, - }; - - await MicrosoftSQL.ExecuteQueryToFile(query, options, default); - - var output = File.ReadAllText(_destination); - - Assert.AreEqual("Id;LastName;FirstName;Salary\r\n1;Meikalainen;Matti;1523,25\r\n", output); - } - - [Test] - public async Task ExecuteQueryToFile_WithImageDBType() - { - var query = new Input - { - Query = $"SELECT Image from {_tableName}", - QueryParameters = Array.Empty(), - ConnectionString = _connString, - OutputFilePath = _destination, - }; - - var options = new Options - { - TimeoutSeconds = 30, + }, + }; + + await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + + var output = File.ReadAllText(_destination); + + Assert.AreEqual("Id;LastName;FirstName;Salary\r\n1;Meikalainen;Matti;1523,25\r\n", output); + } + + [Test] + public async Task ExecuteQueryToFile_WithImageDBType() + { + var query = new Input + { + Query = $"SELECT Image from {_tableName}", + QueryParameters = Array.Empty(), + ConnectionString = _connString, + OutputFilePath = _destination, + }; + + var options = new Options + { + TimeoutSeconds = 30, CsvOptions = new CsvOptions { FieldDelimiter = CsvFieldDelimiter.Semicolon, @@ -170,31 +163,31 @@ public async Task ExecuteQueryToFile_WithImageDBType() AddQuotesToStrings = false, DateFormat = "yyyy-MM-dd", DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", - }, - }; - - await MicrosoftSQL.ExecuteQueryToFile(query, options, default); - - var output = File.ReadAllText(_destination); - - Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png"))), output.TrimEnd(Environment.NewLine.ToCharArray())); - } - - [Test] - public async Task ExecuteQueryToFile_WithBinaryDBType() - { - var query = new Input - { - Query = $"SELECT TestText from {_tableName}", - QueryParameters = Array.Empty(), - ConnectionString = _connString, - OutputFilePath = _destination, - }; - - var options = new Options - { - TimeoutSeconds = 30, - CsvOptions = new CsvOptions + }, + }; + + await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + + var output = File.ReadAllText(_destination); + + Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png"))), output.TrimEnd(Environment.NewLine.ToCharArray())); + } + + [Test] + public async Task ExecuteQueryToFile_WithBinaryDBType() + { + var query = new Input + { + Query = $"SELECT TestText from {_tableName}", + QueryParameters = Array.Empty(), + ConnectionString = _connString, + OutputFilePath = _destination, + }; + + var options = new Options + { + TimeoutSeconds = 30, + CsvOptions = new CsvOptions { FieldDelimiter = CsvFieldDelimiter.Semicolon, LineBreak = CsvLineBreak.CRLF, @@ -206,38 +199,13 @@ public async Task ExecuteQueryToFile_WithBinaryDBType() AddQuotesToStrings = false, DateFormat = "yyyy-MM-dd", DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", - }, - }; - - await MicrosoftSQL.ExecuteQueryToFile(query, options, default); - - var output = File.ReadAllText(_destination); - - Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_Text.txt"))), output.TrimEnd(Environment.NewLine.ToCharArray())); - } - - private static void InsertTestData(string commandText, System.Data.SqlClient.SqlParameter[] parameters = null) - { - using var sqlConnection = new SqlConnection(_connString); - sqlConnection.Open(); - - using (var command = new SqlCommand()) - { - command.CommandText = commandText; - command.CommandType = CommandType.Text; - command.CommandTimeout = 30; - command.Connection = sqlConnection; - if (parameters != null) - { - foreach (var param in parameters) - { - command.Parameters.Add(param); - } - } + }, + }; - command.ExecuteNonQuery(); - } + await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + + var output = File.ReadAllText(_destination); - sqlConnection.Close(); - } + Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_Text.txt"))), output.TrimEnd(Environment.NewLine.ToCharArray())); + } } \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs new file mode 100644 index 0000000..1567b0b --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs @@ -0,0 +1,48 @@ +namespace Frends.MicrosoftSQL.ExecuteQueryToFile.Tests; + +using System.Data; +using System.Data.SqlClient; + +internal static class Helper +{ + + internal static string GetConnectionString() + { + return "Server=127.0.0.1,1433;Database=Master;User Id=SA;Password=Salakala123!"; + } + + internal static void CreateTestTable(string connString, string tableName) + { + using var connection = new SqlConnection(connString); + connection.Open(); + var createTable = connection.CreateCommand(); + createTable.CommandText = $@"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{tableName}') BEGIN CREATE TABLE {tableName} ( Id int, LastName varchar(255), FirstName varchar(255), Salary decimal(6,2), Image Image, TestText VarBinary(MAX)); END"; + createTable.ExecuteNonQuery(); + connection.Close(); + } + + internal static void InsertTestData(string connString, string commandText, System.Data.SqlClient.SqlParameter[] parameters = null) + { + using var sqlConnection = new SqlConnection(connString); + sqlConnection.Open(); + + using (var command = new SqlCommand()) + { + command.CommandText = commandText; + command.CommandType = CommandType.Text; + command.CommandTimeout = 30; + command.Connection = sqlConnection; + if (parameters != null) + { + foreach (var param in parameters) + { + command.Parameters.Add(param); + } + } + + command.ExecuteNonQuery(); + } + + sqlConnection.Close(); + } +} From aa37746a65d1b53ad4c4b4841610ce01792c7135 Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Wed, 7 Feb 2024 14:54:48 +0200 Subject: [PATCH 04/11] CodeQL fixes --- .../lib/Helper.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs index 1567b0b..89fe28e 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs @@ -8,7 +8,9 @@ internal static class Helper internal static string GetConnectionString() { - return "Server=127.0.0.1,1433;Database=Master;User Id=SA;Password=Salakala123!"; + var user = "SA"; + var pwd = "Salakala123!"; + return $"Server=127.0.0.1,1433;Database=Master;User Id={user};Password={pwd}"; } internal static void CreateTestTable(string connString, string tableName) From 590b78fd2e06115b4d70a93e9dd1f7c33a3ef073 Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Wed, 7 Feb 2024 15:34:08 +0200 Subject: [PATCH 05/11] CodeQL and Lint fixes --- .../.editorconfig | 4 + .../UnitTests.cs | 4 +- ...Frends.MicrosoftSQL.ExecuteQueryToFile.sln | 81 ++++++++++--------- .../Frends.MicrosoftSQL.ExecuteQueryToFile.cs | 4 +- 4 files changed, 48 insertions(+), 45 deletions(-) create mode 100644 Frends.MicrosoftSQL.ExecuteQueryToFile/.editorconfig diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/.editorconfig b/Frends.MicrosoftSQL.ExecuteQueryToFile/.editorconfig new file mode 100644 index 0000000..1023159 --- /dev/null +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# SA1000: Keywords should be spaced correctly +dotnet_diagnostic.SA1000.severity = none diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs index c8a288f..8857c9e 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs @@ -170,7 +170,7 @@ public async Task ExecuteQueryToFile_WithImageDBType() var output = File.ReadAllText(_destination); - Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png"))), output.TrimEnd(Environment.NewLine.ToCharArray())); + Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png"))), output.TrimEnd(new char[] { '\r', '\n' })); } [Test] @@ -206,6 +206,6 @@ public async Task ExecuteQueryToFile_WithBinaryDBType() var output = File.ReadAllText(_destination); - Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_Text.txt"))), output.TrimEnd(Environment.NewLine.ToCharArray())); + Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_text.txt"))), output.TrimEnd(Environment.NewLine.ToCharArray())); } } \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.sln b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.sln index 9c5b962..df720a7 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.sln +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.sln @@ -1,40 +1,41 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32112.339 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Frends.MicrosoftSQL.ExecuteQueryToFile", "Frends.MicrosoftSQL.ExecuteQueryToFile\Frends.MicrosoftSQL.ExecuteQueryToFile.csproj", "{35C305C0-8108-4A98-BB1D-AFE5C926239E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Frends.MicrosoftSQL.ExecuteQueryToFile.Tests", "Frends.MicrosoftSQL.ExecuteQueryToFile.Tests\Frends.MicrosoftSQL.ExecuteQueryToFile.Tests.csproj", "{8CA92187-8E4F-4414-803B-EC899479022E}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{78F7F22E-6E20-4BCE-8362-0C558568B729}" - ProjectSection(SolutionItems) = preProject - CHANGELOG.md = CHANGELOG.md - ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_main.yml = ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_main.yml - ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_push.yml = ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_push.yml - ..\.github\workflows\ExecuteQueryToFile_release.yml = ..\.github\workflows\ExecuteQueryToFile_release.yml - README.md = README.md - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Release|Any CPU.Build.0 = Release|Any CPU - {8CA92187-8E4F-4414-803B-EC899479022E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8CA92187-8E4F-4414-803B-EC899479022E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8CA92187-8E4F-4414-803B-EC899479022E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8CA92187-8E4F-4414-803B-EC899479022E}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {55BC6629-85C9-48D8-8CA2-B0046AF1AF4B} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.32112.339 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Frends.MicrosoftSQL.ExecuteQueryToFile", "Frends.MicrosoftSQL.ExecuteQueryToFile\Frends.MicrosoftSQL.ExecuteQueryToFile.csproj", "{35C305C0-8108-4A98-BB1D-AFE5C926239E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Frends.MicrosoftSQL.ExecuteQueryToFile.Tests", "Frends.MicrosoftSQL.ExecuteQueryToFile.Tests\Frends.MicrosoftSQL.ExecuteQueryToFile.Tests.csproj", "{8CA92187-8E4F-4414-803B-EC899479022E}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{78F7F22E-6E20-4BCE-8362-0C558568B729}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + CHANGELOG.md = CHANGELOG.md + ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_main.yml = ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_main.yml + ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_push.yml = ..\.github\workflows\ExecuteQueryToFile_build_and_test_on_push.yml + ..\.github\workflows\ExecuteQueryToFile_release.yml = ..\.github\workflows\ExecuteQueryToFile_release.yml + README.md = README.md + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {35C305C0-8108-4A98-BB1D-AFE5C926239E}.Release|Any CPU.Build.0 = Release|Any CPU + {8CA92187-8E4F-4414-803B-EC899479022E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8CA92187-8E4F-4414-803B-EC899479022E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8CA92187-8E4F-4414-803B-EC899479022E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8CA92187-8E4F-4414-803B-EC899479022E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {55BC6629-85C9-48D8-8CA2-B0046AF1AF4B} + EndGlobalSection +EndGlobal diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs index 7e872ce..c35b9b3 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs @@ -1,10 +1,8 @@ namespace Frends.MicrosoftSQL.ExecuteQueryToFile; -using System; using System.ComponentModel; using System.Data; using System.Data.SqlClient; -using System.Data.Common; using System.Threading; using System.Threading.Tasks; using Frends.MicrosoftSQL.ExecuteQueryToFile.Definitions; @@ -25,7 +23,7 @@ public static class MicrosoftSQL /// Object { int EntriesWritten, string Path, string FileName } public static async Task ExecuteQueryToFile([PropertyTab] Input input, [PropertyTab] Options options, CancellationToken cancellationToken) { - Result result = new (); + Result result = new(); using (var sqlConnection = new SqlConnection(input.ConnectionString)) { await sqlConnection.OpenAsync(cancellationToken); From b79717c0f4d38889672646f4715906d9849dc6ba Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Wed, 7 Feb 2024 15:40:16 +0200 Subject: [PATCH 06/11] CodeQL and Lint fixes --- .../Frends.MicrosoftSQL.ExecuteQueryToFile.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs index c35b9b3..d224742 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs @@ -27,7 +27,6 @@ public static async Task ExecuteQueryToFile([PropertyTab] Input input, [ using (var sqlConnection = new SqlConnection(input.ConnectionString)) { await sqlConnection.OpenAsync(cancellationToken); - using var command = BuildSQLCommand(input.Query, input.QueryParameters); command.CommandTimeout = options.TimeoutSeconds; command.Connection = sqlConnection; From de40d2e50ccbaa88da0c90652cc7877f657c4a21 Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Wed, 7 Feb 2024 15:43:26 +0200 Subject: [PATCH 07/11] CodeQL and Lint fixes --- .../Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs index 8857c9e..1d8d0b3 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs @@ -206,6 +206,6 @@ public async Task ExecuteQueryToFile_WithBinaryDBType() var output = File.ReadAllText(_destination); - Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_text.txt"))), output.TrimEnd(Environment.NewLine.ToCharArray())); + Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_text.txt"))), output.TrimEnd(new char[] { '\r', '\n' })); } } \ No newline at end of file From 0c631d1c0fae48087d478df2560795402c67afe3 Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Wed, 7 Feb 2024 15:48:32 +0200 Subject: [PATCH 08/11] changes --- .../Frends.MicrosoftSQL.ExecuteQueryToFile.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj index 4333150..0c69aec 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.csproj @@ -17,6 +17,7 @@ + PreserveNewest From 148936729be089155c1301338d5ecc6f0abd2c7f Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Thu, 8 Feb 2024 09:07:34 +0200 Subject: [PATCH 09/11] PR review changes --- .../lib/Helper.cs | 1 - .../Enums/SqlDataTypes.cs | 2 +- .../Frends.MicrosoftSQL.ExecuteQueryToFile.cs | 38 +++++++++++-------- README.md | 1 + 4 files changed, 24 insertions(+), 18 deletions(-) diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs index 89fe28e..bd26167 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/lib/Helper.cs @@ -5,7 +5,6 @@ internal static class Helper { - internal static string GetConnectionString() { var user = "SA"; diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/SqlDataTypes.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/SqlDataTypes.cs index 3020359..6e78472 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/SqlDataTypes.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Enums/SqlDataTypes.cs @@ -37,6 +37,6 @@ public enum SqlDataTypes Date = 31, Time = 32, DateTime2 = 33, - DateTimeOffset = 34 + DateTimeOffset = 34, #pragma warning restore CS1591 // self explanatory } \ No newline at end of file diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs index d224742..3e47eab 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.cs @@ -1,5 +1,6 @@ namespace Frends.MicrosoftSQL.ExecuteQueryToFile; +using System; using System.ComponentModel; using System.Data; using System.Data.SqlClient; @@ -27,9 +28,28 @@ public static async Task ExecuteQueryToFile([PropertyTab] Input input, [ using (var sqlConnection = new SqlConnection(input.ConnectionString)) { await sqlConnection.OpenAsync(cancellationToken); - using var command = BuildSQLCommand(input.Query, input.QueryParameters); + + using var command = sqlConnection.CreateCommand(); command.CommandTimeout = options.TimeoutSeconds; - command.Connection = sqlConnection; + command.CommandText = input.Query; + command.CommandType = CommandType.Text; + + if (input.QueryParameters != null) + { + foreach (var parameter in input.QueryParameters) + { + if (parameter.SqlDataType is SqlDataTypes.Auto) + { + command.Parameters.AddWithValue(parameterName: parameter.Name, value: parameter.Value); + } + else + { + var sqlDbType = (SqlDbType)Enum.Parse(typeof(SqlDbType), parameter.SqlDataType.ToString()); + var commandParameter = command.Parameters.Add(parameter.Name, sqlDbType); + commandParameter.Value = parameter.Value; + } + } + } switch (options.ReturnFormat) { @@ -42,18 +62,4 @@ public static async Task ExecuteQueryToFile([PropertyTab] Input input, [ return result; } - - private static SqlCommand BuildSQLCommand(string query, Definitions.SqlParameter[] parmeters) - { - using var command = new SqlCommand(); - command.CommandText = query; - command.CommandType = CommandType.Text; - - foreach (var parameter in parmeters) - { - command.Parameters.AddWithValue(parameter.Name, parameter.Value); - } - - return command; - } } diff --git a/README.md b/README.md index 6859424..1085b67 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Frends Task for MicrosoftSQL operations. - [Frends.MicrosoftSQL.ExecuteQuery](Frends.MicrosoftSQL.ExecuteQuery/README.md) - [Frends.MicrosoftSQL.ExecuteProcedure](Frends.MicrosoftSQL.ExecuteProcedure/README.md) - [Frends.MicrosoftSQL.BatchOperation](Frends.MicrosoftSQL.BatchOperation/README.md) +- [Frends.MicrosoftSQL.ExecuteQueryToFile](Frends.MicrosoftSQL.ExecuteQueryToFile/README.md) # Contributing When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change. From 0a38248e3beae30bbe219edeeb1707f08c646dcc Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Thu, 8 Feb 2024 09:08:38 +0200 Subject: [PATCH 10/11] PR review changes --- .../Definitions/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Options.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Options.cs index 6fe7487..91ba4f7 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Options.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/Options.cs @@ -19,7 +19,7 @@ public class Options /// /// Determines in what format the query is written. /// - /// ReturnFormat.JSON + /// ReturnFormat.CSV [DefaultValue(ReturnFormat.CSV)] public ReturnFormat ReturnFormat { get; set; } From ecd70a9397cb53feff16601430cf6d0ebf1073b1 Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Thu, 8 Feb 2024 09:33:30 +0200 Subject: [PATCH 11/11] Added more tests --- .../GlobalSuppressions.cs | 1 + .../UnitTests.cs | 161 +++++++++++------- .../Definitions/CsvOptions.cs | 35 ++-- 3 files changed, 111 insertions(+), 86 deletions(-) diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/GlobalSuppressions.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/GlobalSuppressions.cs index 931d7d2..d4a5ab6 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/GlobalSuppressions.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/GlobalSuppressions.cs @@ -5,3 +5,4 @@ [assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:File should have header", Justification = "Following Frends documentation guidelines")] [assembly: SuppressMessage("StyleCop.CSharp.NamingRules", "SA1309:Field names should not begin with underscore", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Tests")] [assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1629:Documentation text should end with a period", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Tests")] +[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1101:Prefix local calls with this", Justification = "Following Frends documentation guidelines", Scope = "namespaceanddescendants", Target = "~N:Frends.MicrosoftSQL.ExecuteQueryToFile.Tests")] diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs index 1d8d0b3..2887458 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile.Tests/UnitTests.cs @@ -30,9 +30,29 @@ public class UnitTests private static readonly string _tableName = "TestTable"; private static readonly string _destination = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../TestData/test.csv"); + private Options _options; + [SetUp] public void Init() { + _options = new Options() + { + TimeoutSeconds = 30, + CsvOptions = new CsvOptions + { + FieldDelimiter = CsvFieldDelimiter.Semicolon, + LineBreak = CsvLineBreak.CRLF, + FileEncoding = FileEncoding.UTF8, + EnableBom = false, + IncludeHeadersInOutput = false, + SanitizeColumnHeaders = false, + AddQuotesToDates = false, + AddQuotesToStrings = false, + DateFormat = "yyyy-MM-dd", + DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", + }, + }; + Helper.CreateTestTable(_connString, _tableName); var parameters = new System.Data.SqlClient.SqlParameter[] @@ -66,6 +86,34 @@ public void CleanUp() File.Delete(_destination); } + [Test] + public async Task ExecuteQueryToFile_SqlParameters() + { + var query = new Input + { + Query = $"Select Id, LastName, FirstName, REPLACE(Salary, '.', ',') AS 'Salary' from {_tableName} WHERE Id = @param", + QueryParameters = new Definitions.SqlParameter[] + { + new Definitions.SqlParameter + { + Name = "@param", + Value = 1, + SqlDataType = SqlDataTypes.Int, + }, + }, + ConnectionString = _connString, + OutputFilePath = _destination, + }; + + _options.CsvOptions.AddQuotesToStrings = true; + _options.CsvOptions.IncludeHeadersInOutput = true; + + await MicrosoftSQL.ExecuteQueryToFile(query, _options, default); + var output = File.ReadAllText(_destination); + + Assert.AreEqual("Id;LastName;FirstName;Salary\r\n1;\"Meikalainen\";\"Matti\";\"1523,25\"\r\n", output); + } + [Test] public async Task ExecuteQueryToFile_StringWithApostrophe() { @@ -77,25 +125,10 @@ public async Task ExecuteQueryToFile_StringWithApostrophe() OutputFilePath = _destination, }; - var options = new Options - { - TimeoutSeconds = 30, - CsvOptions = new CsvOptions - { - FieldDelimiter = CsvFieldDelimiter.Semicolon, - LineBreak = CsvLineBreak.CRLF, - FileEncoding = FileEncoding.UTF8, - EnableBom = false, - IncludeHeadersInOutput = true, - SanitizeColumnHeaders = false, - AddQuotesToDates = false, - AddQuotesToStrings = true, - DateFormat = "yyyy-MM-dd", - DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", - }, - }; + _options.CsvOptions.AddQuotesToStrings = true; + _options.CsvOptions.IncludeHeadersInOutput = true; - await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + await MicrosoftSQL.ExecuteQueryToFile(query, _options, default); var output = File.ReadAllText(_destination); Assert.AreEqual("Id;LastName;FirstName;Salary\r\n1;\"Meikalainen\";\"Matti\";\"1523,25\"\r\n", output); @@ -112,25 +145,9 @@ public async Task ExecuteQueryToFile_StringWithoutApostrophe() OutputFilePath = _destination, }; - var options = new Options - { - TimeoutSeconds = 30, - CsvOptions = new CsvOptions - { - FieldDelimiter = CsvFieldDelimiter.Semicolon, - LineBreak = CsvLineBreak.CRLF, - FileEncoding = FileEncoding.UTF8, - EnableBom = false, - IncludeHeadersInOutput = true, - SanitizeColumnHeaders = false, - AddQuotesToDates = false, - AddQuotesToStrings = false, - DateFormat = "yyyy-MM-dd", - DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", - }, - }; + _options.CsvOptions.IncludeHeadersInOutput = true; - await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + await MicrosoftSQL.ExecuteQueryToFile(query, _options, default); var output = File.ReadAllText(_destination); @@ -148,25 +165,33 @@ public async Task ExecuteQueryToFile_WithImageDBType() OutputFilePath = _destination, }; - var options = new Options + await MicrosoftSQL.ExecuteQueryToFile(query, _options, default); + + var output = File.ReadAllText(_destination); + + Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png"))), output.TrimEnd(new char[] { '\r', '\n' })); + } + + [Test] + public async Task ExecuteQueryToFile_WithImageDBTypeWithWhereClause() + { + var query = new Input { - TimeoutSeconds = 30, - CsvOptions = new CsvOptions + Query = $"SELECT Image from {_tableName} WHERE CONVERT(varbinary(max), Image) = @param", + QueryParameters = new Definitions.SqlParameter[] { - FieldDelimiter = CsvFieldDelimiter.Semicolon, - LineBreak = CsvLineBreak.CRLF, - FileEncoding = FileEncoding.UTF8, - EnableBom = false, - IncludeHeadersInOutput = false, - SanitizeColumnHeaders = false, - AddQuotesToDates = false, - AddQuotesToStrings = false, - DateFormat = "yyyy-MM-dd", - DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", + new Definitions.SqlParameter + { + Name = "@param", + Value = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_image.png")), + SqlDataType = SqlDataTypes.VarBinary, + }, }, + ConnectionString = _connString, + OutputFilePath = _destination, }; - await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + await MicrosoftSQL.ExecuteQueryToFile(query, _options, default); var output = File.ReadAllText(_destination); @@ -184,25 +209,33 @@ public async Task ExecuteQueryToFile_WithBinaryDBType() OutputFilePath = _destination, }; - var options = new Options + await MicrosoftSQL.ExecuteQueryToFile(query, _options, default); + + var output = File.ReadAllText(_destination); + + Assert.AreEqual(BitConverter.ToString(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_text.txt"))), output.TrimEnd(new char[] { '\r', '\n' })); + } + + [Test] + public async Task ExecuteQueryToFile_WithBinaryDBTypeWithWhereClause() + { + var query = new Input { - TimeoutSeconds = 30, - CsvOptions = new CsvOptions + Query = $"SELECT TestText FROM {_tableName} WHERE TestText = @param", + QueryParameters = new Definitions.SqlParameter[] { - FieldDelimiter = CsvFieldDelimiter.Semicolon, - LineBreak = CsvLineBreak.CRLF, - FileEncoding = FileEncoding.UTF8, - EnableBom = false, - IncludeHeadersInOutput = false, - SanitizeColumnHeaders = false, - AddQuotesToDates = false, - AddQuotesToStrings = false, - DateFormat = "yyyy-MM-dd", - DateTimeFormat = "yyyy-MM-ddTHH:mm:ss", + new Definitions.SqlParameter + { + Name = "@param", + Value = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(_destination), "Test_text.txt")), + SqlDataType = SqlDataTypes.VarBinary, + }, }, + ConnectionString = _connString, + OutputFilePath = _destination, }; - await MicrosoftSQL.ExecuteQueryToFile(query, options, default); + await MicrosoftSQL.ExecuteQueryToFile(query, _options, default); var output = File.ReadAllText(_destination); diff --git a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvOptions.cs b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvOptions.cs index 57babfc..dc11562 100644 --- a/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvOptions.cs +++ b/Frends.MicrosoftSQL.ExecuteQueryToFile/Frends.MicrosoftSQL.ExecuteQueryToFile/Definitions/CsvOptions.cs @@ -111,19 +111,14 @@ public class CsvOptions /// string internal string GetFieldDelimiterAsString() { - switch (FieldDelimiter) + return FieldDelimiter switch { - case CsvFieldDelimiter.Comma: - return ","; - case CsvFieldDelimiter.Pipe: - return "|"; - case CsvFieldDelimiter.Semicolon: - return ";"; - case CsvFieldDelimiter.Custom: - return CustomFieldDelimiter; - default: - throw new Exception($"Unknown field delimeter: {FieldDelimiter}"); - } + CsvFieldDelimiter.Comma => ",", + CsvFieldDelimiter.Pipe => "|", + CsvFieldDelimiter.Semicolon => ";", + CsvFieldDelimiter.Custom => CustomFieldDelimiter, + _ => throw new Exception($"Unknown field delimeter: {FieldDelimiter}"), + }; } /// @@ -132,16 +127,12 @@ internal string GetFieldDelimiterAsString() /// string internal string GetLineBreakAsString() { - switch (LineBreak) + return LineBreak switch { - case CsvLineBreak.CRLF: - return "\r\n"; - case CsvLineBreak.CR: - return "\r"; - case CsvLineBreak.LF: - return "\n"; - default: - throw new Exception($"Unknown field delimeter: {FieldDelimiter}"); - } + CsvLineBreak.CRLF => "\r\n", + CsvLineBreak.CR => "\r", + CsvLineBreak.LF => "\n", + _ => throw new Exception($"Unknown field delimeter: {FieldDelimiter}"), + }; } } \ No newline at end of file