2022年08月14日 PostgreSQL-14.4 Windows11Pro npgsql.3.1.10 and Tips [長年日記]
_ pg_env.batの修正
PATHに「"」が含まれていると正しく動作しなかったので、「"」を削除する。
REM @SET PATH="C:\Users\USER\Desktop\PostgreSQL\14\bin";%PATH% @SET PATH=C:\Users\USER\Desktop\PostgreSQL\14\bin;%PATH%
_ エンコーディングの設定
@SET PGCLIENTENCODING=UTF8
_ DB作成(例)
> createdb.exe -E UTF8 testdb
_ テーブル作成(例)(psql.exe)
psql.exe -U postgres testdb testdb=# create table tb_sample1 ( testdb=# id integer primary key, testdb=# name varchar(50), testdb=# job varchar(50) testdb=# };
_ psql.exe利用例
出力先をoutput.csvに設定、文字揃えをオフにし、区切り文字をタブに設定、rowのみ出力、tb_sample1テーブルの全てを出力して、出力先を元に戻す。
testdb=# \o output.csv testdb=# \a testdb=# \f '\t' testdb=# \t on testdb=# select * from tb_sample1; testdb=# \o
-Aで文字揃えをオフに、-Fで区切り文字を「カンマ」に指定。
> psql -d testdb -U postgres -c "select * from tb_sample1;" -A -F ',' > output.csv
-Aで文字揃えをオフに、-Fで区切り文字を「タブ」に指定(Powershell限定)。
> psql -d testdb -U postgres -c "select * from tb_sample1;" -A -F "`t" > output.csv
- タブ区切
- 引用符(QUOTE)で囲む
- NULL文字は空文字化
- カラム名を表示
COPY tb_sample1 TO 'c:\temp\output.csv' WITH CSV DELIMITER E'\t' FORCE QUOTE * NULL AS '' HEADER;
_ npgsql.3.1.10.nupkg
pg_hba.confの認証methodを「trust」または「password」に設定する。
本来は、もっと新しいnpgsqlを使うべきだと思われるが、dllの依存関係をどうしても解決できなかった。 結局、このバージョン(3.1.10)と認証method(trust or password)でしか接続できなかった...
_ C#によるPostgreSQLアクセス例
// // Compile: c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:npgsql.dll npgsqltest.cs // using System; using System.IO; using System.Data; using Npgsql; public class Program{ static void Main(string[] args){ var connString = @"Server=127.0.0.1;Port=5432;UserId=postgres;Password=パスワード;Database=testdb"; var conn = new NpgsqlConnection(connString); conn.Open(); NpgsqlTransaction tran = conn.BeginTransaction(); var cmd = new NpgsqlCommand(@"delete from tb_sample1", conn); cmd.ExecuteNonQuery(); tran.Commit(); tran = conn.BeginTransaction(); cmd = new NpgsqlCommand(@"insert into tb_sample1 (id, name, job) values (:id, :name, :job)", conn); cmd.Parameters.AddWithValue("id", 1); cmd.Parameters.AddWithValue("name", "山田 太郎"); cmd.Parameters.AddWithValue("job", "会社員"); cmd.ExecuteNonQuery(); tran.Commit(); tran = conn.BeginTransaction(); cmd.Parameters.Remove("id"); cmd.Parameters.Remove("name"); cmd.Parameters.Remove("job"); cmd.Parameters.AddWithValue("id", 2); cmd.Parameters.AddWithValue("name", "辻󠄀(一点しんにょうつじ) IVS"); cmd.Parameters.AddWithValue("job", "会社員"); cmd.ExecuteNonQuery(); tran.Commit(); tran = conn.BeginTransaction(); cmd.Parameters.Remove("id"); cmd.Parameters.Remove("name"); cmd.Parameters.Remove("job"); cmd.Parameters.AddWithValue("id", 3); cmd.Parameters.AddWithValue("name", "𠮷(土よし) サロゲート"); cmd.Parameters.AddWithValue("job", "会社員"); cmd.ExecuteNonQuery(); tran.Commit(); tran = conn.BeginTransaction(); cmd.Parameters.Remove("id"); cmd.Parameters.Remove("name"); cmd.Parameters.Remove("job"); cmd.Parameters.AddWithValue("id", 4); cmd.Parameters.AddWithValue("name", "(\uE000) 外字"); cmd.Parameters.AddWithValue("job", "会社員"); cmd.ExecuteNonQuery(); tran.Commit(); // // わざと重複キーでインサートして、どんなエラーメッセージが出るか観察してみる... // tran = conn.BeginTransaction(); cmd.Parameters.Remove("id"); cmd.Parameters.Remove("name"); cmd.Parameters.Remove("job"); cmd.Parameters.AddWithValue("id", 4); cmd.Parameters.AddWithValue("name", "(\uE000) 外字"); cmd.Parameters.AddWithValue("job", "会社員"); try{ cmd.ExecuteNonQuery(); tran.Commit(); }catch (Exception e){ Concole.WriteLine(e.Message); tran.Rollback(); } cmd = new NpgsqlCommand(@"select * from tb_sample1", conn); var dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { Console.WriteLine("{0},{1},{2}", dataReader["id"], dataReader["name"], dataReader["job"]); } dataReader.Close(); tran = conn.BeginTransaction(); cmd = new NpgsqlCommand(@"update tb_sample1 set job = :job where id = :id", conn); cmd.Parameters.AddWithValue("id", 1); cmd.Parameters.AddWithValue("job", "無職"); cmd.ExecuteNonQuery(); cmd.Parameters.Remove("id"); cmd.Parameters.Remove("job"); cmd.Parameters.AddWithValue("id", 2); cmd.Parameters.AddWithValue("job", "無職"); cmd.ExecuteNonQuery(); cmd.Parameters.Remove("id"); cmd.Parameters.Remove("job"); cmd.Parameters.AddWithValue("id", 3); cmd.Parameters.AddWithValue("job", "無職"); cmd.ExecuteNonQuery(); cmd.Parameters.Remove("id"); cmd.Parameters.Remove("job"); cmd.Parameters.AddWithValue("id", 4); cmd.Parameters.AddWithValue("job", "無職"); cmd.ExecuteNonQuery(); cmd = new NpgsqlCommand(@"select * from tb_sample1", conn); dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { Console.WriteLine("{0},{1},{2}", dataReader["id"], dataReader["name"], dataReader["job"]); } dataReader.Close(); tran.Rollback(); cmd = new NpgsqlCommand(@"select * from tb_sample1", conn); dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { Console.WriteLine("{0},{1},{2}", dataReader["id"], dataReader["name"], dataReader["job"]); } dataReader.Close(); conn.Close(); } }
_ エラーメッセージ
- 二重キー
- "0" 個の引数を指定して "ExecuteNonQuery" を呼び出し中に例外が発生しました: "23505: 重複したキー値は一意性制約"tb_sample1_pkey"違反となります"
- デッドロック
- "0" 個の引数を指定して "ExecuteNonQuery" を呼び出し中に例外が発生しました: "40P01: デッドロックを検出しました"
_ PowershellによるPostgreSQLアクセス例
[void][reflection.assembly]::LoadFrom("C:\Users\USER\Desktop\PostgreSQL\Npgsql.dll") $ConnectionString = "Host=127.0.0.1;Username=postgres;Password=パスワード;Database=testdb" $conn = New-Object NpgSql.NpgsqlConnection($ConnectionString) $conn.Open() $tran = $conn.BeginTransaction() $command = New-Object NpgSql.NpgSqlCommand("delete from tb_sample1", $conn) $effected_row_count = $command.ExecuteNonQuery(); $tran.Commit() $tran = $conn.BeginTransaction() $command = New-Object NpgSql.NpgSqlCommand("insert into tb_sample1 (id, name, job) values (:id, :name, :job)", $conn) [void]$command.Parameters.AddWithValue("id", 1) [void]$command.Parameters.AddWithValue("name", "山田 太郎") [void]$command.Parameters.AddWithValue("job", "会社員") $effected_row_count = $command.ExecuteNonQuery(); $tran.Commit() $tran = $conn.BeginTransaction() [void]$command.Parameters.Remove("id") [void]$command.Parameters.Remove("name") [void]$command.Parameters.Remove("job") [void]$command.Parameters.AddWithValue("id", 2) [void]$command.Parameters.AddWithValue("name", "辻󠄀(一点しんにょうつじ) IVS") [void]$command.Parameters.AddWithValue("job", "会社員") $effected_row_count = $command.ExecuteNonQuery(); $tran.Commit() $tran = $conn.BeginTransaction() [void]$command.Parameters.Remove("id") [void]$command.Parameters.Remove("name") [void]$command.Parameters.Remove("job") [void]$command.Parameters.AddWithValue("id", 3) [void]$command.Parameters.AddWithValue("name", "𠮷(土よし) サロゲート") [void]$command.Parameters.AddWithValue("job", "会社員") $effected_row_count = $command.ExecuteNonQuery(); $tran.Commit() $tran = $conn.BeginTransaction() [void]$command.Parameters.Remove("id") [void]$command.Parameters.Remove("name") [void]$command.Parameters.Remove("job") [void]$command.Parameters.AddWithValue("id", 4) [void]$command.Parameters.AddWithValue("name", "(\uE000) 外字") [void]$command.Parameters.AddWithValue("job", "会社員") $effected_row_count = $command.ExecuteNonQuery(); $tran.Commit() # # わざと重複キーでインサートして、どんなエラーメッセージが出るか観察してみる... # $tran = $conn.BeginTransaction() [void]$command.Parameters.Remove("id") [void]$command.Parameters.Remove("name") [void]$command.Parameters.Remove("job") [void]$command.Parameters.AddWithValue("id", 4) [void]$command.Parameters.AddWithValue("name", "(\uE000) 外字") [void]$command.Parameters.AddWithValue("job", "会社員") try{ $effected_row_count = $command.ExecuteNonQuery(); $tran.Commit() }catch{ write-output $_.Exception.Message # "0" 個の引数を指定して "ExecuteNonQuery" を呼び出し中に例外が発生しました: "23505: 重複したキー値は一意性制約"tb_sample1_pkey"違反となります" $tran.Rollback() } $command = New-Object NpgSql.NpgSqlCommand("select * from tb_sample1 order by id", $conn) $datareader = $command.ExecuteReader() while ($datareader.Read()){ write-output($datareader["id"].tostring() + "," + $datareader["name"] + "," + $datareader["job"]) } $datareader.Close() $tran = $conn.BeginTransaction() $command = New-Object NpgSql.NpgSqlCommand("update tb_sample1 set job = :job where id = :id", $conn) [void]$command.Parameters.AddWithValue("id", 1) [void]$command.Parameters.AddWithValue("job", "無職") $effected_row_count = $command.ExecuteNonQuery(); [void]$command.Parameters.Remove("id") [void]$command.Parameters.Remove("job") [void]$command.Parameters.AddWithValue("id", 2) [void]$command.Parameters.AddWithValue("job", "無職") $effected_row_count = $command.ExecuteNonQuery(); [void]$command.Parameters.Remove("id") [void]$command.Parameters.Remove("job") [void]$command.Parameters.AddWithValue("id", 3) [void]$command.Parameters.AddWithValue("job", "無職") $effected_row_count = $command.ExecuteNonQuery(); [void]$command.Parameters.Remove("id") [void]$command.Parameters.Remove("job") [void]$command.Parameters.AddWithValue("id", 4) [void]$command.Parameters.AddWithValue("job", "無職") $effected_row_count = $command.ExecuteNonQuery(); $command = New-Object NpgSql.NpgSqlCommand("select * from tb_sample1 order by id", $conn) $datareader = $command.ExecuteReader() while ($datareader.Read()){ write-output($datareader["id"].tostring() + "," + $datareader["name"] + "," + $datareader["job"]) } $datareader.Close() $tran.Rollback() $command = New-Object NpgSql.NpgSqlCommand("select * from tb_sample1 order by id", $conn) $datareader = $command.ExecuteReader() while ($datareader.Read()){ write-output($datareader["id"].tostring() + "," + $datareader["name"] + "," + $datareader["job"]) } $datareader.Close() $conn.Close()
_ PowershellでUTF8を使う設定
# 標準出力(パイプ)への出力時のエンコーディングをバックアップ $oe = $OutputEncoding # 標準出力(画面)への出力時のエンコーディングをバックアップ $scoe = [System.Console]::OutputEncoding # 標準出力(パイプ)、標準出力(画面)への出力時のエンコーディングをUTF-8BOM無しに設定 $OutputEncoding = [System.Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false # 標準出力(パイプ)、標準出力(画面)への出力時のエンコーディングをUTF-16、LE、BOM有りに設定 #$OutputEncoding = [System.Console]::OutputEncoding = New-Object System.Text.UnicodeEncoding $false,$true # 標準出力(パイプ)、標準出力(画面)への出力時のエンコーディングをShift-JISに設定 #$OutputEncoding = [System.Console]::OutputEncoding = [Text.Encoding]::GetEncoding("Shift-JIS") # ... UTF-8BOMなしデータを処理 ... Hogge.exe | fuga.exe | foo.exe | bar.exe ... # 標準出力(パイプ)への出力時のエンコーディングを元に戻す $OutputEncoding = $oe # 標準出力(画面)への出力時のエンコーディングを元に戻す [System.Console]::OutputEncoding = $scoe
_ dotnet and npgsql.6.0.6
結局、pg_hba.confの認証methodを「md5」または「scram-sha-256」にする為にはdotnet6環境でのビルドが必要だった。
ソースディレクトリの準備
mkdir npgsqltest cd npgsqltest dotnet new console
npgsql.6.0.6のパッケージ追加(インターネット接続可能な場合)
dotnet add package npgsql
npgsql.6.0.6のパッケージ追加(インターネット接続不可能な場合)
mkdir packages copy anywhere\npgsql.6.0.6.nupkg .\packages\ copy anywhere\ystem.runtime.compilerservices.unsafe.nupkg .\packages\ dotnet add package npgsql -s .\packages
ソースの編集
notepad Program.cs
ビルド
dotnet build
テスト実行
dotnet run
公開(デバッグ)
dotnet publish bin\Debug\net6.0\publish\npgsqltest.exe
公開(本番)
dotnet publish -c Release bin\Release\net6.0\publish\npgsqltest.exe
公開(本番、全部入り)
dotnet publish -c Release --self-contained true -r win-x64 bin\Release\net6.0\win-x64\publish\npgsqltest.exe
公開(本番、全部入り、単一exe)
dotnet publish -c Release --self-contained -p:PublicSingleFile=true -p:PublishTrimmed=true -r win-x64 bin\Release\net6.0\win-x64\publish\npgsqltest.exe
2022年06月27日 iText7 C# サンプル [長年日記]
_ C#からiTextを利用して、PDFを作成するサンプル。iTextはAGPL3.0で利用可能。ネット上の各所から収集した情報を再構築して、個人的に必要十分な使用例をサンプルプログラムとして実装してみた。ただし、Windowsでの開発は本職ではないので、かなり自分勝手な解釈で行っている。
_ nupkg(dll)
nupkgの本来の使い方は全く知らないが、拡張子を.zipに変更して.dllを取り出す。
- bouncycastle.1.8.9.nupkg
- https://www.nuget.org/packages/BouncyCastle/
- itext7.7.2.2.nupkg
- https://www.nuget.org/packages/iText7/
- itext7.commons.7.2.2.nupkg
- https://www.nuget.org/packages/itext7.commons/
- microsoft.extensions.logging.5.0.0.nupkg
- https://www.nuget.org/packages/Microsoft.Extensions.Logging/
- microsoft.extensions.logging.abstractions.5.0.0.nupkg
- https://www.nuget.org/packages/Microsoft.Extensions.Logging.Abstractions/
- microsoft.extensions.options.5.0.0.nupkg
- https://www.nuget.org/packages/Microsoft.Extensions.Options/
_ コンパイル
c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:itext.commons.dll;itext.barcodes.dll;itext.forms.dll;itext.io.dll;itext.kernel.dll;itext.layout.dll;itext.pdfa.dll;itext.sign.dll;itext.styledxmlparser.dll;itext.svg.dll;BouncyCastle.Crypto.dll;Microsoft.Extensions.Logging.Abstractions.dll;Microsoft.Extensions.Logging.dll;Microsoft.Extensions.Options.dll Itext7Sample.cs
_ Itext7Sample.cs
// // iText7利用サンプル(iTextSharp7使用につき、無償利用の場合はソース公開義務有り。注意!) // // Author. "Masahiko Ito"<m-ito@myh.no-ip.org> // // 開発環境 // エディタ :メモ帳 // コンパイル:c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:itext.commons.dll;itext.barcodes.dll;itext.forms.dll;itext.io.dll;itext.kernel.dll;itext.layout.dll;itext.pdfa.dll;itext.sign.dll;itext.styledxmlparser.dll;itext.svg.dll;BouncyCastle.Crypto.dll;Microsoft.Extensions.Logging.Abstractions.dll;Microsoft.Extensions.Logging.dll;Microsoft.Extensions.Options.dll Itext7Sample.cs // // 必要なDLL // // bouncycastle.1.8.9.nupkg(https://www.nuget.org/packages/BouncyCastle/) // BouncyCastle.Crypto.dll // // itext7.7.2.2.nupkg(https://www.nuget.org/packages/iText7/) // itext.barcodes.dll // itext.forms.dll // itext.io.dll // itext.kernel.dll // itext.layout.dll // itext.pdfa.dll // itext.sign.dll // itext.styledxmlparser.dll // itext.svg.dll // // itext7.commons.7.2.2.nupkg(https://www.nuget.org/packages/itext7.commons/) // itext.commons.dll // // microsoft.extensions.logging.5.0.0.nupkg(https://www.nuget.org/packages/Microsoft.Extensions.Logging/) // Microsoft.Extensions.Logging.dll // // microsoft.extensions.logging.abstractions.5.0.0.nupkg(https://www.nuget.org/packages/Microsoft.Extensions.Logging.Abstractions/) // Microsoft.Extensions.Logging.Abstractions.dll // // microsoft.extensions.options.5.0.0.nupkg(https://www.nuget.org/packages/Microsoft.Extensions.Options/) // Microsoft.Extensions.Options.dll // using System; using System.IO; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; using iText.Kernel.Pdf.Xobject; using iText.Kernel.Pdf.Extgstate; using iText.Kernel.Geom; using iText.Kernel.Font; using iText.Kernel.Colors; using iText.Layout; using iText.Layout.Element; using iText.Layout.Properties; using iText.IO.Image; using iText.Barcodes; public class Program{ //====================================================================== // iText7 サンプル //====================================================================== static void Main(string[] args){ Sample_ShowTextAligned("sample_showtextaligned.pdf"); Sample_DrawLine("sample_drawline.pdf"); Sample_DrawRectangle("sample_drawrectangle.pdf"); Sample_FillRectangle("sample_fillrectangle.pdf"); Sample_DrawEllipse("sample_drawellipse.pdf"); Sample_FillEllipse("sample_fillellipse.pdf"); Sample_DrawImage("sample_drawimage.pdf"); Sample_DrawQRCode("sample_drawqrcode.pdf"); Sample_SetTemplate("sample_settemplate.pdf"); } //====================================================================== // 文字列描画 //====================================================================== static void Sample_ShowTextAligned(string filename){ // // 出力する PdfDocument 作成 // PdfDocument PdfDocument = new PdfDocument(new PdfWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); // // PdfDocument から Document 作成 // Document Document = new Document(PdfDocument); // // PdfDocument に新しいページを追加し、用紙をA4縦に設定 // // PdfDocument.AddNewPage(new PageSize(new Rectangle(210.0f / 25.4f * 72.0f, 297.0f / 25.4f * 72.0f)); PdfDocument.AddNewPage(PageSize.A4); // PdfDocument.AddNewPage(PageSize.A4.Rotate()); // A4横の場合 // // PdfFont をMS明朝で作成 // PdfFont PdfFont = PdfFontFactory.CreateFont(@"C:\Windows\Fonts\msgothic.ttc,0", "Identity-H"); // // Document にMS明朝を設定 // Document.SetFont(PdfFont); // // Document にフォントのサイズを 24point に設定 // Document.SetFontSize(24); // // Document にフォントの色を黒、不透過度を 1.0f に設定 // Document.SetFontColor(ColorConstants.BLACK, 1.0f); // // 用紙の右端から24.0point、下から48.0pointの位置に文字列を表示 // 指定する位置に文字列の左下が位置付けられる // サロゲートペア文字は表示可能、IVS/IVD文字は表示不可能 // Document.ShowTextAligned("はろーわーるど!", 24.0f, 48.0f, TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0.0f); // // 用紙の右端から24.0point、下から48.0pointの位置に45度傾けて文字列を表示。 // Document.ShowTextAligned("はろーわーるど!", 24.0f, 48.0f, TextAlignment.LEFT, VerticalAlignment.BOTTOM, (float)Math.PI / 180 * 45); // // Document を閉じてPDFを完成させる // Document.Close(); } //====================================================================== // 直線描画 //====================================================================== static void Sample_DrawLine(string filename){ // // 出力する PdfDocument 作成 // PdfDocument PdfDocument = new PdfDocument(new PdfWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); // // PdfDocument から Document 作成 // Document Document = new Document(PdfDocument); // // PdfDocument に新しいページを追加および用紙をA4縦に設定し、PdfPage を作成 // PdfPage PdfPage = PdfDocument.AddNewPage(PageSize.A4); // // PdfPage から PdfCanvas 作成 // PdfCanvas PdfCanvas = new PdfCanvas(PdfPage); // // PdfCanvas に直線描画の色を RED に設定 // PdfCanvas.SetStrokeColor(ColorConstants.RED); // // PdfCanvas に描画の線幅を2.0point に設定 // PdfCanvas.SetLineWidth(2.0f); // // 用紙の左下を原点として、(100.0point, 50.0point)から(200.0point, 100.0point)に直線を描画 // PdfCanvas.MoveTo(100.0f,50.0f).LineTo(200.0f,100.0f).Stroke(); // // Document を閉じてPDFを完成させる // Document.Close(); } //====================================================================== // 矩形描画 //====================================================================== static void Sample_DrawRectangle(string filename){ // // 出力する PdfDocument 作成 // PdfDocument PdfDocument = new PdfDocument(new PdfWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); // // PdfDocument から Document 作成 // Document Document = new Document(PdfDocument); // // PdfDocument に新しいページを追加および用紙をA4縦に設定し、PdfPage を作成 // PdfPage PdfPage = PdfDocument.AddNewPage(PageSize.A4); // // PdfPage から PdfCanvas 作成 // PdfCanvas PdfCanvas = new PdfCanvas(PdfPage); // // PdfCanvas に直線描画の色を RED に設定 // PdfCanvas.SetStrokeColor(ColorConstants.RED); // // PdfCanvas に描画の線幅を2.0point に設定 // PdfCanvas.SetLineWidth(2.0f); // // 用紙の左下を原点として、(10.0point, 20.0point)から右方向に30.0pointの幅, 上方向に40.0pointの高さで矩形を描画 // PdfCanvas.Rectangle(10.0f,20.0f,30.0f,40.0f).Stroke(); // // Document を閉じてPDFを完成させる // Document.Close(); } //====================================================================== // 矩形塗りつぶし //====================================================================== static void Sample_FillRectangle(string filename){ // // 出力する PdfDocument 作成 // PdfDocument PdfDocument = new PdfDocument(new PdfWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); // // PdfDocument から Document 作成 // Document Document = new Document(PdfDocument); // // PdfDocument に新しいページを追加および用紙をA4縦に設定し、PdfPage を作成 // PdfPage PdfPage = PdfDocument.AddNewPage(PageSize.A4); // // PdfPage から PdfCanvas 作成 // PdfCanvas PdfCanvas = new PdfCanvas(PdfPage); // // PdfCanvas に直線描画の色を RED に設定 // PdfCanvas.SetStrokeColor(ColorConstants.RED); // // PdfCanvas に直線描画の不透過度を 1.0f に設定 // PdfCanvas.SetExtGState(new PdfExtGState().SetStrokeOpacity(1.0f)); // // PdfCanvas に塗りつぶしの色を GREEN に設定 // PdfCanvas.SetFillColor(ColorConstants.GREEN); // // PdfCanvas に塗りつぶしの不透過度を 0.5f に設定 // PdfCanvas.SetExtGState(new PdfExtGState().SetFillOpacity(0.5f)); // // PdfCanvas に描画の線幅を2.0point に設定 // PdfCanvas.SetLineWidth(2.0f); // // 用紙の左下を原点として、(10.0point, 20.0point)から右方向に30.0pointの幅, 上方向に40.0pointの高さで矩形を描画し内部を塗りつぶす // PdfCanvas.Rectangle(10.0f,20.0f,30.0f,40.0f).FillStroke(); // // 用紙の左下を原点として、(25.0point, 40.0point)から右方向に30.0pointの幅, 上方向に40.0pointの高さで矩形を描画し内部を塗りつぶす // PdfCanvas.Rectangle(25.0f,40.0f,30.0f,40.0f).FillStroke(); // // Document を閉じてPDFを完成させる // Document.Close(); } //====================================================================== // 楕円描画 //====================================================================== static void Sample_DrawEllipse(string filename){ // // 出力する PdfDocument 作成 // PdfDocument PdfDocument = new PdfDocument(new PdfWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); // // PdfDocument から Document 作成 // Document Document = new Document(PdfDocument); // // PdfDocument に新しいページを追加および用紙をA4縦に設定し、PdfPage を作成 // PdfPage PdfPage = PdfDocument.AddNewPage(PageSize.A4); // // PdfPage から PdfCanvas 作成 // PdfCanvas PdfCanvas = new PdfCanvas(PdfPage); // // PdfCanvas に直線描画の色を RED に設定 // PdfCanvas.SetStrokeColor(ColorConstants.RED); // // PdfCanvas に描画の線幅を2.0point に設定 // PdfCanvas.SetLineWidth(2.0f); // // 用紙の左下を原点として、(10.0point, 20.0point)-(30.0point, 40.0point)を対角とする矩形内に接する楕円を描画 // PdfCanvas.Ellipse(10.0f, 20.0f, 30.0f, 40.0f).Stroke(); // // Document を閉じてPDFを完成させる // Document.Close(); } //====================================================================== // 楕円塗りつぶし //====================================================================== static void Sample_FillEllipse(string filename){ // // 出力する PdfDocument 作成 // PdfDocument PdfDocument = new PdfDocument(new PdfWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); // // PdfDocument から Document 作成 // Document Document = new Document(PdfDocument); // // PdfDocument に新しいページを追加および用紙をA4縦に設定し、PdfPage を作成 // PdfPage PdfPage = PdfDocument.AddNewPage(PageSize.A4); // // PdfPage から PdfCanvas 作成 // PdfCanvas PdfCanvas = new PdfCanvas(PdfPage); // // PdfCanvas に直線描画の色を RED に設定 // PdfCanvas.SetStrokeColor(ColorConstants.RED); // // PdfCanvas に直線描画の不透過度を 1.0f に設定 // PdfCanvas.SetExtGState(new PdfExtGState().SetStrokeOpacity(1.0f)); // // PdfCanvas に塗りつぶしの色を GREEN に設定 // PdfCanvas.SetFillColor(ColorConstants.GREEN); // // PdfCanvas に塗りつぶしの不透過度を 0.5f に設定 // PdfCanvas.SetExtGState(new PdfExtGState().SetFillOpacity(0.5f)); // // PdfCanvas に描画の線幅を2.0point に設定 // PdfCanvas.SetLineWidth(2.0f); // // 用紙の左下を原点として、(10.0point, 20.0point)-(30.0point, 40.0point)を対角とする矩形内に接する楕円を描画し内部を塗りつぶす // PdfCanvas.Ellipse(10.0f,20.0f,30.0f,40.0f).FillStroke(); // // 用紙の左下を原点として、(20.0point, 30.0point)-(40.0point, 50.0point)を対角とする矩形内に接する楕円を描画し内部を塗りつぶす // PdfCanvas.Ellipse(20.0f,30.0f,40.0f,50.0f).FillStroke(); // // Document を閉じてPDFを完成させる // Document.Close(); } //====================================================================== // 画像ファイル描画 //====================================================================== static void Sample_DrawImage(string filename){ // // 出力する PdfDocument 作成 // PdfDocument PdfDocument = new PdfDocument(new PdfWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); // // PdfDocument から Document 作成 // Document Document = new Document(PdfDocument); // // PdfDocument に新しいページを追加および用紙をA4縦に設定し、PdfPage を作成 // PdfPage PdfPage = PdfDocument.AddNewPage(PageSize.A4); // // PdfPage から PdfCanvas 作成 // PdfCanvas PdfCanvas = new PdfCanvas(PdfPage); // // PdfCanvas に塗りつぶしの(描画の)不透過度を 0.5f に設定 // PdfCanvas.SetExtGState(new PdfExtGState().SetFillOpacity(0.5f)); // // image.png を取り込んで、 ImageData を作成 // ImageData ImageData = ImageDataFactory.Create(@"image.png"); // // ImageData から Image を作成 // Image Image = new Image(ImageData); // // イメージの幅を 100point、高さを 50point に設定 // Image.ScaleAbsolute(100.0f, 50.0f); // // 用紙の左下を原点として、(1ページ目の)(20.0point, 30.0point) にイメージを位置づけ // Image.SetFixedPosition(1, 20.0f, 30.0f); // // Document に Image を描画 // Document.Add(Image); // // Document を閉じてPDFを完成させる // Document.Close(); } //====================================================================== // QRCode描画 //====================================================================== static void Sample_DrawQRCode(string filename){ // // 出力する PdfDocument 作成 // PdfDocument PdfDocument = new PdfDocument(new PdfWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); // // PdfDocument から Document 作成 // Document Document = new Document(PdfDocument); // // PdfDocument に新しいページを追加および用紙をA4縦に設定し、PdfPage を作成 // PdfPage PdfPage = PdfDocument.AddNewPage(PageSize.A4); // // PdfPage から PdfCanvas 作成 // PdfCanvas PdfCanvas = new PdfCanvas(PdfPage); // // PdfCanvas に塗りつぶしの(描画の)不透過度を 1.0f に設定 // PdfCanvas.SetExtGState(new PdfExtGState().SetFillOpacity(1.0f)); // // "this is test qrcode" を内容とする BarcodeQRCode を作成 // BarcodeQRCode BarcodeQRCode = new BarcodeQRCode("this is test qrcode"); // // BarcodeQRCode から、描画色を BLACK で PdfFormXObject を作成 // PdfFormXObject PdfFormXObject = BarcodeQRCode.CreateFormXObject(ColorConstants.BLACK, PdfDocument); // // PdfFormXObject から ImageBarcode を作成 // Image ImageBarcode = new Image(PdfFormXObject); // // ImageBarcode にイメージの幅を 100point、高さを 100point に設定 // ImageBarcode.ScaleAbsolute(100.0f, 100.0f); // // ImageBarcode に用紙の左下を原点として、(1ページ目の)(20.0point, 30.0point) にイメージを位置づけ // ImageBarcode.SetFixedPosition(1, 20.0f, 30.0f); // // Document に ImageBarcode を描画 // Document.Add(ImageBarcode); // // Document を閉じてPDFを完成させる // Document.Close(); } //====================================================================== // テンプレート設定 //====================================================================== static void Sample_SetTemplate(string filename){ // // 出力する PdfDocument 作成 // PdfDocument PdfDocument = new PdfDocument(new PdfWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))); // // PdfDocument から Document 作成 // Document Document = new Document(PdfDocument); // // template.pdf から PdfDocumentTemplate 生成 // PdfDocument PdfDocumentTemplate = new PdfDocument(new PdfReader(@"template.pdf")); // // PdfDocumentTemplate の1ページ目を取り込んで PagePdfTemplate 生成 // PdfPage PagePdfTemplate = PdfDocumentTemplate.GetPage(1); // // PagePdfTemplate から PdfXObject 生成 // PdfXObject PdfXObject = PagePdfTemplate.CopyAsFormXObject(PdfDocument); // // 取込が完了して不要になった PdfDocumentTemplate を閉じる // PdfDocumentTemplate.Close(); // // PdfDocument に新しいページ(1ページ目)を追加および用紙をA4縦に設定し、PdfPage を作成 // PdfPage PdfPage = PdfDocument.AddNewPage(PageSize.A4); // // PdfPage から PdfCanvas 作成 // PdfCanvas PdfCanvas = new PdfCanvas(PdfPage); // // 新しいページに PdfXObject(テンプレート) を設定 // PdfCanvas.AddXObjectAt(PdfXObject, 0, 0); // // PdfDocument に新しいページ(2ページ目)を追加および用紙をA4縦に設定し、PdfPage を作成 // PdfPage = PdfDocument.AddNewPage(PageSize.A4); // // PdfPage から PdfCanvas 作成 // PdfCanvas = new PdfCanvas(PdfPage); // // 新しいページに PdfXObject(テンプレート) を設定 // PdfCanvas.AddXObjectAt(PdfXObject, 0, 0); // // Document を閉じてPDFを完成させる // Document.Close(); } }
2022年03月25日 Windows 11 Insider Preview 22581.1 (ni_release) on Vmware workstation player [長年日記]
このPCは現在WindoこのPCは現在Windows11のシステム要件を満たしていませんws11のシステム要件を満たしていません
_ Windows 11 Insider Preview 22581.1 がvmplayerに降ってきたが、「TPMじゃない!」とか「セキュアブートじゃない!」とか文句を言われてアップデートできない状態になった。
_ 対策
C:\$Windows.~BT\Sources\AppraiserRes.dllをWindows10の物に入れ替えるといいらしい
https://samurai-computer.com/how-to-bypass-system-requirement-check-windows11-insider/ より。
2021年10月14日 VMware Workstation Player 16.1.2(vmplayer) on Slackware64-current [長年日記]
_ VMware Workstation Player 16.1.2(vmplayer) on Slackware64-current
Slackware64-currentにvmplayer 16.1.2をインストールした時のメモ。
インストール
以下のスクリプトでインストールを実行するが...
# sh VMware-Player-16.1.2-17966106.x86_64.bundle --ignore-errors
この環境(カーネルバージョン)では必要なモジュールのビルドに失敗する。
$ uname -a Linux slackware64-current.artie.or.jp 5.14.11 #1 SMP Sat Oct 9 18:30:57 CDT 2021 x86_64 Intel(R) Core(TM) i5-3320M CPU @ 2.60GHz GenuineIntel GNU/Linux
これは既知の問題らしく、解決策も提示されている。
$ git clone -b workstation-16.1.2 https://github.com/mkubecek/vmware-host-modules.git $ cd vmware-host-modules/ $ make # make install # /etc/init.d/vmware restart
以上でインストールは無事完了。
ランスクリプトの設定
# cd /etc/rc.d/rc4.d # ln -s /etc/rc.d/init.d/vmware K08vmware # ln -s /etc/rc.d/init.d/vmware-USBArbitrator K08vmware-USBArbitrator # ln -s /etc/rc.d/init.d/vmware S19vmware # ln -s /etc/rc.d/init.d/vmware-USBArbitrator S50vmware-USBArbitrator
root以外でのライセンス認証
初回の起動時にライセンス認証が必要だが、バックグラウンドでpolkit-gnome-authentication-agent-1を起動しておかないと成功しない。おそらくデスクトップ環境がgnomeだと問題ないのだろうと想像するが、私はfvwm-1.24rユーザなので :P
$ /usr/libexec/polkit-gnome-authentication-agent-1 & $ vmplayer
ネットワーク設定
# /usr/lib/vmware/bin/vmware-netcfg
- vmnet1 for Hostonly network
- vmnet8 for Nat network
2021年09月05日 Building ClamAV-0.104.0 on Slackware-14.2 [長年日記]
_ Slackware-14.2でClamAV-0.104.0をビルドする
Slackware-14.2でClamAV-0.103.3からClamAV-0.104.0にバージョンアップしたのだけれど、新しめなcmakeやら新たなライブラリやらが必要になっていた。
cmake-3.19.6を/optにインストール
オリジナルのcmake-3.5.2では古すぎて、ClamAV-0.104.0はビルド出来ない。
- tar xvf cmake-202x.tar.gz
- mv cmake-3.19.6.tar.gz cmake-202x/
- cd cmake-202x
- sudo sh cmake-202x.SlackBuild
- sudo installpkg /tmp/cmake-202x-3.19.6-i586-1_SBo.tgz
これで、/opt/cmake-202x/以下にインストールされる。
check-0.15.2のインストール
ClamAV-0.104.0のビルドには、libcheckとやらが必要とのこと...
- tar xvf check.tar.gz
- mv check-0.15.2.tar.gz check/
- cd check
- sudo sh check.SlackBuild
- sudo installpkg /tmp/check-0.15.2-i586-1_SBo.tgz
python-3.7.2のインストール
Python3も必要...
- tar xvf python3.tar.gz
- mv Python-3.7.2.tar.xz python3/
- cd python3
- sudo sh python3.SlackBuild
- sudo installpkg /tmp/python3-3.7.2-i586-1_SBo.tgz
ようやくClamAV-0.104.0のビルド
- tar xvf clamav-0.104.0.tar.gz
- cd clamav-0.104.0
- mkdir build
- cd build
- PATH=/opt/cmake-202x/bin:${PATH} cmake ..
- make
- sudo make install
定義ファイル格納ディレクトリ(/usr/local/share/clamav/)の準備
- sudo mkdir /usr/local/share/clamav
- sudo chown clamav.clamav /usr/local/share/clamav
スキャンデーモンの設定ファイル(/usr/local/etc/clamd.conf)
*** clamd.conf.sample 2021-08-28 07:41:31.000000000 +0900 --- clamd.conf 2021-09-05 15:22:48.245019780 +0900 *************** *** 5,17 **** # Comment or remove the line below. ! Example # Uncomment this option to enable logging. # LogFile must be writable for the user running daemon. # A full path is required. # Default: disabled ! #LogFile /tmp/clamd.log # By default the log file is locked for writing - the lock protects against # running clamd multiple times (if want to run another clamd, please --- 5,17 ---- # Comment or remove the line below. ! #Example # Uncomment this option to enable logging. # LogFile must be writable for the user running daemon. # A full path is required. # Default: disabled ! LogFile /var/log/clamav/clamd.log # By default the log file is locked for writing - the lock protects against # running clamd multiple times (if want to run another clamd, please *************** *** 41,52 **** # Use system logger (can work together with LogFile). # Default: no ! #LogSyslog yes # Specify the type of syslog messages - please refer to 'man syslog' # for facility names. # Default: LOG_LOCAL6 ! #LogFacility LOG_MAIL # Enable verbose logging. # Default: no --- 41,52 ---- # Use system logger (can work together with LogFile). # Default: no ! LogSyslog yes # Specify the type of syslog messages - please refer to 'man syslog' # for facility names. # Default: LOG_LOCAL6 ! LogFacility LOG_MAIL # Enable verbose logging. # Default: no *************** *** 74,80 **** # It is recommended that the directory where this file is stored is # also owned by root to keep other users from tampering with it. # Default: disabled ! #PidFile /var/run/clamd.pid # Optional path to the global temporary directory. # Default: system specific (usually /tmp or /var/tmp). --- 74,80 ---- # It is recommended that the directory where this file is stored is # also owned by root to keep other users from tampering with it. # Default: disabled ! PidFile /var/run/clamav/clamd.pid # Optional path to the global temporary directory. # Default: system specific (usually /tmp or /var/tmp). *************** *** 93,111 **** # Path to a local socket file the daemon will listen on. # Default: disabled (must be specified by a user) ! #LocalSocket /tmp/clamd.socket # Sets the group ownership on the unix socket. # Default: disabled (the primary group of the user running clamd) ! #LocalSocketGroup virusgroup # Sets the permissions on the unix socket to the specified mode. # Default: disabled (socket is world accessible) ! #LocalSocketMode 660 # Remove stale socket after unclean shutdown. # Default: yes ! #FixStaleSocket yes # TCP port address. # Default: no --- 93,111 ---- # Path to a local socket file the daemon will listen on. # Default: disabled (must be specified by a user) ! LocalSocket /var/run/clamav/clamd.socket # Sets the group ownership on the unix socket. # Default: disabled (the primary group of the user running clamd) ! LocalSocketGroup clamav # Sets the permissions on the unix socket to the specified mode. # Default: disabled (socket is world accessible) ! #DEL_LocalSocketMode 660 # Remove stale socket after unclean shutdown. # Default: yes ! FixStaleSocket yes # TCP port address. # Default: no *************** *** 117,123 **** # from the outside world. This option can be specified multiple # times if you want to listen on multiple IPs. IPv6 is now supported. # Default: no ! #TCPAddr localhost # Maximum length the queue of pending connections may grow to. # Default: 200 --- 117,123 ---- # from the outside world. This option can be specified multiple # times if you want to listen on multiple IPs. IPv6 is now supported. # Default: no ! #TCPAddr 127.0.0.1 # Maximum length the queue of pending connections may grow to. # Default: 200 *************** *** 210,227 **** #ConcurrentDatabaseReload no # Execute a command when virus is found. In the command string %v will ! # be replaced with the virus name and %f will be replaced with the file name. ! # Additionally, two environment variables will be defined: $CLAM_VIRUSEVENT_FILENAME ! # and $CLAM_VIRUSEVENT_VIRUSNAME. # Default: no ! #VirusEvent /usr/local/bin/send_sms 123456789 "VIRUS ALERT: %v in %f" # Run as another user (clamd must be started by root for this option to work) # Default: don't drop privileges ! #User clamav # Stop daemon when libclamav reports out of memory condition. ! #ExitOnOOM yes # Don't fork into background. # Default: no --- 210,225 ---- #ConcurrentDatabaseReload no # Execute a command when virus is found. In the command string %v will ! # be replaced with the virus name. # Default: no ! #VirusEvent /usr/local/bin/send_sms 123456789 "VIRUS ALERT: %v" # Run as another user (clamd must be started by root for this option to work) # Default: don't drop privileges ! #DEL_User clamav # Stop daemon when libclamav reports out of memory condition. ! ExitOnOOM yes # Don't fork into background. # Default: no
定義ファイル更新デーモンの定義ファイル(/usr/local/etc/freshclam.conf)
*** freshclam.conf.sample 2021-08-28 07:41:31.000000000 +0900 --- freshclam.conf 2021-09-05 15:25:26.379098762 +0900 *************** *** 5,11 **** # Comment or remove the line below. ! Example # Path to the database directory. # WARNING: It must match clamd.conf's directive! --- 5,11 ---- # Comment or remove the line below. ! #Example # Path to the database directory. # WARNING: It must match clamd.conf's directive! *************** *** 14,20 **** # Path to the log file (make sure it has proper permissions) # Default: disabled ! #UpdateLogFile /var/log/freshclam.log # Maximum size of the log file. # Value of 0 disables the limit. --- 14,20 ---- # Path to the log file (make sure it has proper permissions) # Default: disabled ! UpdateLogFile /var/log/clamav/freshclam.log # Maximum size of the log file. # Value of 0 disables the limit. *************** *** 35,46 **** # Use system logger (can work together with UpdateLogFile). # Default: no ! #LogSyslog yes # Specify the type of syslog messages - please refer to 'man syslog' # for facility names. # Default: LOG_LOCAL6 ! #LogFacility LOG_MAIL # Enable log rotation. Always enabled when LogFileMaxSize is enabled. # Default: no --- 35,46 ---- # Use system logger (can work together with UpdateLogFile). # Default: no ! LogSyslog yes # Specify the type of syslog messages - please refer to 'man syslog' # for facility names. # Default: LOG_LOCAL6 ! LogFacility LOG_MAIL # Enable log rotation. Always enabled when LogFileMaxSize is enabled. # Default: no *************** *** 51,62 **** # It is recommended that the directory where this file is stored is # also owned by root to keep other users from tampering with it. # Default: disabled ! #PidFile /var/run/freshclam.pid # By default when started freshclam drops privileges and switches to the # "clamav" user. This directive allows you to change the database owner. # Default: clamav (may depend on installation options) ! #DatabaseOwner clamav # Use DNS to verify virus database version. FreshClam uses DNS TXT records # to verify database and software versions. With this directive you can change --- 51,62 ---- # It is recommended that the directory where this file is stored is # also owned by root to keep other users from tampering with it. # Default: disabled ! PidFile /var/run/clamav/freshclam.pid # By default when started freshclam drops privileges and switches to the # "clamav" user. This directive allows you to change the database owner. # Default: clamav (may depend on installation options) ! DatabaseOwner clamav # Use DNS to verify virus database version. FreshClam uses DNS TXT records # to verify database and software versions. With this directive you can change *************** *** 147,153 **** # Send the RELOAD command to clamd. # Default: no ! #NotifyClamd /path/to/clamd.conf # Run command after successful database update. # Use EXIT_1 to return 1 after successful database update. --- 147,153 ---- # Send the RELOAD command to clamd. # Default: no ! NotifyClamd /usr/local/etc/clamd.conf # Run command after successful database update. # Use EXIT_1 to return 1 after successful database update.
スキャンデーモン(/usr/local/sbin/clamd)の起動
- sudo mkdir -p /var/run/clamav/
- sudo chown clamav:clamav /var/run/clamav/
- sudo chmod 771 /var/run/clamav/
- sudo /usr/local/sbin/clamd
定義ファイル更新デーモン(/usr/local/bin/freshclam)の起動
- sudo /usr/local/bin/freshclam -d -l /var/log/clamav/freshclam.log
2021年08月29日 How to get best quality movie by youtube-dl [長年日記]
_ yourtbe-dlで最高画質で動画を取得する方法
youtube-dl --no-playlist -f bestvideo+bestaudio --merge-output-format mp4 'https://www.youtube.com/hogehoge'
2021年08月03日 jupyter notebookでデフォルトの作業フォルダを設定する方法 [長年日記]
_ jupyter notebookでデフォルトの作業フォルダを設定する方法
作業フォルダそのものはシェルからコマンドで作成する。
$ mkdir ~/src $ mkdir ~/src/jupyter
設定ファイルを作成し、設定する。
$ jupyter notebook --generate-config $ vim ~/.jupyter/jupyter_notebook_config.py
~/.jupyter/jupyter_notebook_config.py
c.NotebookApp.notebook_dir = '/home/m-ito/src/jupyter/'
jupyter notebookで実行(Run)出来ない場合の対処
jupyter notebookで実行(Run)しても、新しいセルが挿入されるだけで、何も実行されない場合がある。
そんな場合は、カーネルとやらとの接続がうまくできていない可能性があるので、「カーネル」→「再接続」を行ってみると回復するかも...
2021年08月02日 jupyter notebookで起動するブラウザをオプション込で設定する方法 [長年日記]
_ jupyter notebookで起動するブラウザをオプション込で設定する方法
$ jupyter notebook --generate-config $ vim ~/.jupyter/jupyter_notebook_config.py
~/.jupyter/jupyter_notebook_config.py
c.NotebookApp.browser = '/usr/local/firefox/firefox %s -P prof1'
2020年09月22日 C# memo [長年日記]
_ C# memo
HelloWorld.cs
using System; public class AnyClassYouLike{ static void Main(string[] args){ Console.WriteLine("HelloWorld"); return; } }
変数
sbyte //8ビット整数(符号付き) byte //8ビット整数(符号無し) short //16ビット整数(符号付き) ushort //16ビット整数(符号無し) int //32ビット整数(符号付き) uint //32ビット整数(符号無し) long //64ビット整数(符号付き) ulong //64ビット整数(符号無し) float //32ビット浮動小数(例 123.456f) double //64ビット浮動小数(例 123.456d) char //文字(UNICODE)(例 'あ') bool //論理値 (true or false) decimal //高精度 10進数浮動小数(例 123.456m) string //文字列(UNICODE)(例 "あいうえお") object //全ての型の基底となる型
配列
int[] a = new int[3] {1,2,3}; int[,] a = new int[2,3] {{1,2,3},{4,5,6}};
ハッシュ
using System.Collections; Hashtable ht = new Hashtable(); ht["key1"] = "data1"; // ht.ContainsKey("key1") // True or False // foreach (string key in ht.Keys){ ... }
標準入出力
using System; Console.Write("あいうえお"); // 改行無し Console.WriteLine("あいうえお"); // 改行有り Console.WriteLine("私は{0}{1}です","伊藤","太郎"); string input = Console.ReadLine();
文字列フォーマット
string str = string.Format("{(インデックス)[,(表示幅)][:(書式)(精度)]}", 値) // (インデックス) 0オリジン // ,(表示幅) 整数値、マイナス指定は左寄せ // :(書式)(精度) d 整数値の10進表記、(精度)は桁数を表す(先頭ゼロ埋め) // e 指数表記、(精度)は仮数部の小数点桁数を表す // f 固定小数点表記、(精度)は小数点桁数を表す // n 3桁区切り文字入りの数値表記、(精度)は小数点桁数を表す // x 整数値の16進表記、(精度)は桁数を表す(先頭ゼロ埋め)
string str = string.Format("{(インデックス):###,###,###}", 値) // 可変長、先頭ゼロ埋め無し、桁区切り付き、マイナス符号付き
string str = string.Format("{(インデックス):000,000,000}", 値) // 固定長、先頭ゼロ埋め有り、桁区切り付き、マイナス符号付き
条件分岐
if (a == 1){ }else if (a == 2){ }else{ }
繰返し
using System; using System.Collections; while (a < 10){ } for (int i = 0; i < 10; i++){ } int[] array = new int[10] {1,2,3,4,5,6,7,8,9,10}; foreach (int i in array){ } Hashtable hash = new Hashtable() { {"key1","value1"}, {"key2","value2"}, {"key3","value3"} }; ArrayList list = new ArrayList (hash.Keys); list.Sort(); foreach (string key in list){ }
ファイル入出力(テキスト)
using System.IO; using System.Text; StreamReader sr = new StreamReader("input.csv", Encoding.GetEncoding("UTF-8")); bool append_sw = false; StreamWriter sw = new StreamWriter("output.csv", append_sw, Encoding.GetEncoding("UTF-8")); string str = null; while ((str = sr.ReadLine()) != null){ sw.WriteLine(str); } sr.Close(); sw.Close();
ファイル入出力(バイナリ)
using System.IO; byte[] buf = new byte[1024]; FileStream sr = new FileStream("input.dat", FileMode.Open, FileAccess.Read); FileStream sw = new FileStream("output.dat", FileMode.Create, FileAccess.Write); int readsize = 0; while ((readsize = sr.Read(buf, 0, 1024)) > 0){ sw.Write(buf, 0, readsize); } sr.Close(); sw.Close();
ファイル入出力(バイナリ2)
using System.IO; byte[] buf = new byte[1024]; byte b; FileStream srw = new FileStream("output.dat", FileMode.Open, FileAccess.ReadWrite); int readsize = 0; srw.Seek(10, SeekOrigin.Begin); readsize = srw.Read(buf, 0, 5); b = buf[0];buf[0] = buf[4]; buf[4] = b; b = buf[1];buf[1] = buf[3]; buf[3] = b; srw.Seek(10, SeekOrigin.Begin); srw.Write(buf, 0, 5); srw.Close();
引数
using System; public class AnyClassYouLike{ static void Main(string[] args){ for (int i = 0; i < args.Length; i++){ Console.WriteLine(args[i]); } return; } }
文字列連結
string str = "あいう" + "えお";
文字列分割
using System.Text.RegularExpressions; string input = "aa,bb,,cc,,,dd"; string sep = ",+"; string[] array = Regex.Split(input, sep);
部分文字列
string str = "abcあいうdef"; string hiragana = str.Substring(3, 3);
文字列比較(正規表現)
using System.Text.RegularExpressions; if (Regex.IsMatch("abcdefg", "b.*e")){ ... }
文字列置換(正規表現)
using System.Text.RegularExpressions; string str = Regex.Replace("abcdefg", "b.*f", "b to f"); string str = Regex.Replace("abcdefg", "^(.)(.*)(.)$", "$3$2$1");
文字列⇒数値変換
int i = int.Parse("123"); float f = float.Parse("123.456");
型変換
int i = (int)123.45;
日時取得
DateTime dt; dt = new DateTime(2020,9,20,12,59,59); Console.WriteLine(dt.ToString()); Console.WriteLine(dt.ToString("yyyy/MM/dd HH:mm:ss")); Console.WriteLine(dt.Year); Console.WriteLine(dt.Month); Console.WriteLine(dt.Day); Console.WriteLine(dt.Hour); Console.WriteLine(dt.Minute); Console.WriteLine(dt.Second); dt = DateTime.Parse("2020/09/20 12:59:59"); dt = DateTime.Now; DateTime dt2 = dt.AddYears(10); // AddMonths(), AddDays(), AddHours(), AddMinutes(), AddSeconds() Console.WriteLine(dt.CompareTo(dt2)); // -1 (-1, 0, 1)
外部コマンド実行
using System; using System.Diagnostics; ProcessStartInfo pInfo = new ProcessStartInfo(); pInfo.FileName = "ipconfig.exe"; pInfo.CreateNoWindow = true; // do not open console window pInfo.UseShellExecute = false; // false for console command, true for windows app pInfo.RedirectStandardOutput = true; pInfo.RedirectStandardError = true; pInfo.Arguments = "/all"; Process p = Process.Start(pInfo); p.WaitForExit(); String stdOut = p.StandardOutput.ReadToEnd(); String stdErr = p.StandardError.ReadToEnd(); int exitCode = p.ExitCode; p.Close(); Console.WriteLine(stdOut); Console.WriteLine(stdErr);
終了
Environment.Exit(0);
例外処理
try{ throw new Exception("エラーだよ"); }catch(Exception e){ Console.WriteLine(e); Console.WriteLine(e.Message); }finally{ Console.WriteLine("finally"); }
クラス
using System; public class AnyClassYouLike{ static void Main(string[] args){ MyClass mc = new MyClass("あいう", "えお"); mc.show(); MyClass2 mc2 = new MyClass2("あいう", "えお", "かきくけこ"); mc2.show(); return; } } public class MyClass{ string p1; string p2; public MyClass(){ this.p1 = ""; this.p2 = ""; } public MyClass(string p1, string p2){ this.p1 = p1; this.p2 = p2; } public virtual void show(){ Console.WriteLine(this.p1 + "," + this.p2); } } public class MyClass2 : MyClass{ string p3; public MyClass2(){ } public MyClass2(string p1, string p2, string p3) : base(p1, p2){ this.p3 = p3; } public override void show(){ base.show(); Console.WriteLine(this.p3); } }
インターフェース
using System; public class AnyClassYouLike{ static void Main(string[] args){ Ianimal a; a = new Dog(); a.talk(); a = new Cat(); a.talk(); return; } } interface Ianimal{ void talk(); } class Dog : Ianimal{ public void talk(){ Console.WriteLine("わんわん"); } } class Cat : Ianimal{ public void talk(){ Console.WriteLine("にゃー"); } }
Oracle
using System; using System.Data; using System.Data.OracleClient; public class AnyClassYouLike{ static void Main(string[] args){ string ip = "127.0.0.1"; string user = "mito"; string password = "oracle"; string connectionString = "Data Source=" + ip + ";User ID=" + user + ";Password=" + password + ";Integrated Security=false;"; OracleConnection connection; OracleCommand ocmd; OracleParameter bind_id; OracleParameter bind_name; OracleDataReader ord; int row; // connection = new OracleConnection(connectionString); connection.Open(); ocmd = new OracleCommand(); ocmd.Connection = connection; ocmd.Transaction = connection.BeginTransaction(); // ocmd.CommandText = "insert into t_sample (id,name) values(:id,:name)"; bind_id = new OracleParameter("id", "00000001"); ocmd.Parameters.Add(bind_id); bind_name = new OracleParameter("name", "伊藤 太郎"); ocmd.Parameters.Add(bind_name); row = ocmd.ExecuteNonQuery(); ocmd.Parameters.Remove(bind_id); ocmd.Parameters.Remove(bind_name); ocmd.Transaction.Commit(); // or .Rollback(); ocmd.Transaction = connection.BeginTransaction(); // ocmd.CommandText = "select id,name from t_sample where id >= :id"; bind_id = new OracleParameter("id", "00000000"); ocmd.Parameters.Add(bind_id); ord = ocmd.ExecuteReader(); while (ord.Read()){ Console.WriteLine(ord["id"] + "," + ord["name"]); } ord.Close(); ocmd.Parameters.Remove(bind_id); // ocmd.CommandText = "update t_sample set name=:name where id = :id"; bind_id = new OracleParameter("id", "00000001"); ocmd.Parameters.Add(bind_id); bind_name = new OracleParameter("name", "伊藤 花子"); ocmd.Parameters.Add(bind_name); row = ocmd.ExecuteNonQuery(); ocmd.Parameters.Remove(bind_id); ocmd.Parameters.Remove(bind_name); ocmd.Transaction.Commit(); // or .Rollback(); ocmd.Transaction = connection.BeginTransaction(); // ocmd.CommandText = "select id,name from t_sample where id >= :id"; bind_id = new OracleParameter("id", "00000000"); ocmd.Parameters.Add(bind_id); ord = ocmd.ExecuteReader(); while (ord.Read()){ Console.WriteLine(ord["id"] + "," + ord["name"]); } ord.Close(); ocmd.Parameters.Remove(bind_id); // ocmd.CommandText = "delete from t_sample where id >= :id"; bind_id = new OracleParameter("id", "00000000"); ocmd.Parameters.Add(bind_id); row = ocmd.ExecuteNonQuery(); ocmd.Parameters.Remove(bind_id); ocmd.Transaction.Commit(); // or .Rollback(); // ord.Dispose(); ocmd.Dispose(); connection.Close(); connection.Dispose(); return; } }
MSSQLServer
using System; using System.Data; using System.Data.SqlClient; public class AnyClassYouLike{ static void Main(string[] args){ SqlConnectionStringBuilder builder; SqlConnection con; SqlCommand com; SqlParameter parm_id; SqlParameter parm_name; SqlDataReader reader; SqlTransaction transaction; string sqlstr; builder = new SqlConnectionStringBuilder(); builder.DataSource = "127.0.0.1"; builder.UserID = "mito"; builder.Password = "sqlserver"; builder.InitialCatalog = "testdb"; builder.ConnectTimeout = 15000; // ms con = new SqlConnection(builder.ConnectionString); con.Open(); // sqlstr = "insert into t_sample (id,name) values(@id,@name)"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000001"); com.Parameters.Add(parm_id); parm_name = new SqlParameter("@name", "伊藤 太郎"); com.Parameters.Add(parm_name); com.ExecuteNonQuery(); com.Parameters.Remove(parm_id); com.Parameters.Remove(parm_name); com.Dispose(); transaction.Commit(); // or .Rollback(); // sqlstr = "select id,name from t_sample where id >= @id"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000000"); com.Parameters.Add(parm_id); reader = com.ExecuteReader(); while (reader.Read()){ Console.WriteLine(reader["id"] + "," + reader["name"]); } reader.Close(); com.Parameters.Remove(parm_id); com.Dispose(); transaction.Commit(); // or .Rollback(); // sqlstr = "update t_sample set name=@name where id = @id"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000001"); com.Parameters.Add(parm_id); parm_name = new SqlParameter("@name", "伊藤 花子"); com.Parameters.Add(parm_name); com.ExecuteNonQuery(); com.Parameters.Remove(parm_id); com.Parameters.Remove(parm_name); com.Dispose(); transaction.Commit(); // or .Rollback(); // sqlstr = "select id,name from t_sample where id >= @id"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000000"); com.Parameters.Add(parm_id); reader = com.ExecuteReader(); while (reader.Read()){ Console.WriteLine(reader["id"] + "," + reader["name"]); } reader.Close(); com.Parameters.Remove(parm_id); com.Dispose(); transaction.Commit(); // or .Rollback(); // sqlstr = "delete from t_sample where id >= @id"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000000"); com.Parameters.Add(parm_id); com.ExecuteNonQuery(); com.Parameters.Remove(parm_id); com.Dispose(); transaction.Commit(); // or .Rollback(); // con.Close(); return; } }
Socket通信(echo server (single thread))
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Text.RegularExpressions; public class AnyClassYouLike{ static void Main(String[] args){ string line; IPAddress ipAdd = IPAddress.Parse("0.0.0.0"); int port = 1234; TcpListener listener = new TcpListener(ipAdd, port); listener.Start(); while (true){ TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((IPEndPoint)client.Client.RemoteEndPoint).Port); NetworkStream ns = client.GetStream(); StreamReader sr = new StreamReader(ns, Encoding.UTF8); StreamWriter sw = new StreamWriter(ns, Encoding.UTF8); while ((line = sr.ReadLine()) != null){ Console.WriteLine(line); sw.WriteLine(line); sw.Flush(); if (Regex.IsMatch(line, "^shutdown")){ break; } } sr.Close(); sw.Close(); ns.Close(); client.Close(); if (line != null){ break; } } listener.Stop(); } }
Socket通信(echo client)
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; public class AnyClassYouLike{ static void Main(String[] args){ string line; string ipAdd = args[0]; int port = int.Parse(args[1]); string str = args[2]; TcpClient client = new TcpClient(ipAdd, port); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((IPEndPoint)client.Client.RemoteEndPoint).Port); NetworkStream ns = client.GetStream(); StreamReader sr = new StreamReader(ns, Encoding.UTF8); StreamWriter sw = new StreamWriter(ns, Encoding.UTF8); sw.WriteLine(str); sw.Flush(); line = sr.ReadLine(); Console.WriteLine(line); sr.Close(); sw.Close(); ns.Close(); client.Close(); } }
Socket通信(echo server (multi thread))
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; public class AnyClassYouLike{ static void Main(String[] args){ IPAddress ipAdd = IPAddress.Parse("0.0.0.0"); int port = 1234; TcpListener listener = new TcpListener(ipAdd, port); listener.Start(); while (true){ TcpClient client = listener.AcceptTcpClient(); Task.Run(() => communicateClient(client)); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((IPEndPoint)client.Client.RemoteEndPoint).Port); } listener.Stop(); } private static void communicateClient(TcpClient client){ string line; NetworkStream ns = client.GetStream(); StreamReader sr = new StreamReader(ns, Encoding.UTF8); StreamWriter sw = new StreamWriter(ns, Encoding.UTF8); while ((line = sr.ReadLine()) != null){ Console.WriteLine(line); sw.WriteLine(line); sw.Flush(); } sr.Close(); sw.Close(); ns.Close(); client.Close(); } }
2020年08月09日 Setting ACPI for suspending machine automatically when battery charge loss [長年日記]
_ ノートPCのバッテリー残量が少なくなったら自動的にサスペンドするためのACPI設定方法
/etc/acpi/acpi_handler.sh
バッテリーに関するイベントを検知したらスクリプト(/etc/acpi/lowbattery.sh)を起動する。
*** acpi_handler.sh.ORG 2020-08-08 23:40:56.530432033 +0900 --- acpi_handler.sh 2020-08-09 01:16:38.793951977 +0900 *************** *** 13,18 **** --- 13,21 ---- ;; esac ;; + battery) + /etc/acpi/lowbattery.sh & + ;; *) logger "ACPI group $1 / action $2 is not defined" ;;
/etc/acpi/lowbattery.sh
バッテリー駆動の間は60秒間隔でバッテリー残量をチェックし、残量が10%を切った場合サスペンドする。ACアダプタ駆動になったら終了する。
#! /bin/sh trap 'rm -fr /tmp/lowbattery.lock' INT TERM mkdir /tmp/lowbattery.lock || exit 1 wait=60 threshold_percent=10 while [ X = X ] do if [ X`cat /proc/acpi/ac_adapter/ACAD/state | egrep off-line` = "X" ] then off_line=no else off_line=yes fi if [ ${off_line} = yes ] then last_full_capacity=`cat /proc/acpi/battery/BAT1/info |\ egrep 'last full capacity' |\ sed -e 's/: */:/;s/ mAh//' |\ cut -d: -f2` remaining_capacity=`cat /proc/acpi/battery/BAT1/state |\ egrep 'remaining capacity' |\ sed -e 's/: */:/;s/ mAh//' |\ cut -d: -f2` battery_percent=`expr ${remaining_capacity} \* 100 / ${last_full_capacity}` if [ ${battery_percent} -le ${threshold_percent} ] then logger "ACPI /etc/acpi/lowbattery.sh suspend(${battery_percent}%/${threshold_percent}%)" sync;sync;sync echo -n mem > /sys/power/state fi else break fi sleep ${wait} done rm -fr /tmp/lowbattery.lock