技術メモ

【C#】DbUpdateConcurrencyExceptionが発生する(同じレコードに複数のフォームから同時に書き込んでいた)

SQLite+EntityFrameworkの環境にて発生。

エラー内容

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions. ---> System.Data.Entity.Core.OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.
   場所 System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source)
   場所 System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   場所 System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   場所 System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
   場所 System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
   場所 System.Data.Entity.Internal.InternalContext.SaveChanges()

原因

あるフォームのイベント発生時にレコード更新する処理を入れていたが、先に閉じたフォームのイベントが残っていて、同時に複数のフォームから同じレコードを更新していたことが原因だった。
今回は、閉じたフォームのイベントが確実に消えるようにしたところ解消された。

【C#】長いパスから短いパスに変換する(GetShortPathNameを使う)

WindowsのAPIであるGetShortPathName関数を利用する。

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern int GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);

以下のように呼び出す。

// ※ポイント!
// 長いパスの先頭に「\\?\」をつけないと、短いパスを取得できない
var longPath = @"\\?\C:\Users\a\Desktop\あいうえお\テキストファイル\111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111.txt";

var shortPath = new StringBuilder(256);
if (GetShortPathName(longPath, shortPath, shortPath.Capacity) == 0)
{
    // 取得失敗
}
else
{
    // 取得成功。取得例 \\?\C:\Users\a\Desktop\あいう~1\テキス~1\111111~1.TXT
    Console.WriteLine(shortPath);
}

【Windows Bat】ps1ファイルを呼び出す&日本語が化けないようにする

以下の2ファイルは同じフォルダに保存されている前提。
start.batをダブルクリックするだけで、ps1が実行されるようになる。

start.bat (※文字コードはShift-JIS)

@echo off
rem ps1ファイルをそのまま呼び出せるようにするため、「-ExecutionPolicy Bypass」を指定する
powershell -ExecutionPolicy Bypass -File "%~dp0main.ps1"
pause

 

main.ps1 (※文字コードはUTF-8 BOM付き)

# 現在日時を表示
Write-Host "PowerShellを実行しました! $(Get-Date -Format 'yyyy/MM/dd HH:mm:ss')"

EasyReplayWindows

You can easily automate routine computer tasks.

Start EasyReplayWindows and click the “Start Recording” button.
Then operate your computer as you normally would.
After recording is complete, in “AutoPlay Settings”, specify the time and day you want it to run.
The recorded content will now be executed automatically every time.

It’s very easy to use, so please give it a try!
You can use it for free for one month.

Click here to download

Once you have confirmed that it works without any problems, please purchase it from the link below.

*Refunds are not available after purchase. Please check the operation beforehand.
*Automatic payment is made every month. If you wish to cancel the renewal, please contact us by email (it takes several days to process the cancellation, so please contact us earlier than the next renewal date.)

EasyReplayWindows

English page here.

いつものパソコンの定型作業を簡単に自動化できます。

EasyReplayWindowsを起動し、「記録開始」ボタンをクリックします。
あとは普通にパソコンの操作を行います。
記録完了後、「自動再生設定」にて、実行したい時間と曜日を指定します。
これで、記録した内容が毎回自動で実行されるようになります。

操作はとても簡単ですので、一度お試しください!
1か月間は無料にてご利用できます。

ダウンロードはこちらをクリックしてください

問題なく動作することが確認できましたら、以下からご購入をお願いいたします。

※ご購入後の返金はできません。事前に動作確認をお願いいたします。
※1か月ごとの自動支払いになります。更新をキャンセルする場合は、メールにてご連絡ください(キャンセル処理までに数日かかりますので、次回更新日よりも早めにご連絡ください。)

【WordPress】【ロリポップ】WordPressをインストールした直後に「このサイトは安全に接続できません」と表示されてしまう(サブドメインの独自SSLが未設定が原因)

ロリポップから、サブドメインにWordPressをインストールした。
インストール完了時には管理画面が表示されていたのだが、数分すると「このサイトは安全に接続できません」「(サブドメイン名)から無効な応答が送信されました」と表示されるようになってしまった。

原因は、サブドメインがSSLの設定がされていないためであった。
以下のロリポップの管理画面(セキュリティ→独自SSL証明書導入)から、「SSL保護されていないドメイン」をクリックし、「独自SSL(無料)を設定する」をクリックする。

数分待つと、表示されるようになった!

【C#】【log4net】Releaseビルドのときだけログ出力されない(XmlConfigurator.Configure()の呼び出し不足)

Debugビルドのときにはログ出力されるが、Releaseビルドに変えるとログ出力されない問題に遭遇(正確には、Relaseビルドで「最適化コード」にチェックが付いた状態)。
log4netのバージョンは、v2.0.17

Program.csのMainメソッドの一番先頭で、以下のコードを書けばログ出力されるようになった!

XmlConfigurator.Configure();

 

逆に、なぜDebugビルドのときに出力できていたのかが謎だが、とりあえず先に進む・・・

【C#】BitmapのSave()を呼び出すとSystem.ArgumentException: 使用されたパラメーターが有効ではありません。エラーが発生する

エラーになるコード(一部のみ抜粋)

        using (MemoryStream ms = new MemoryStream())
        {
            bitmap.Save(ms, ImageFormat.Png);

エラー内容

System.ArgumentException: ‘使用されたパラメーターが有効ではありません。’

原因

このエラーになるコードの前に、bitmapをusingを使って作成していたためだった。。

bitmapはnullにはなっていないが、Saveを呼び出すと上記エラーとなった。
usingを止めたところ、エラーが解消された。