ラベル C# の投稿を表示しています。 すべての投稿を表示
ラベル C# の投稿を表示しています。 すべての投稿を表示

TikaOnDotnetでファイル内の文字列を抽出する方法

 以下のSampleのとおり、TextExtractor.Extract()メソッドで、ファイル内の文字列を取得できます。

※Shift-Jisのテキストファイル(.txt)は、UTF-8に変換しないと抽出に失敗するので要注意。

public void TikaExtractorTest() {
    var txtExtractor = new TextExtractor();

    var path = @"C:\Temp\Test.xlsx";
    var content = txtExtractor.Extract(path);

    Debug.WriteLine(content.Text);
}

C#で文字コードを自動判定する方法

 以下のSampleのとおり、ReadJEnc.JP.GetEncoding()メソッドで文字コードを自動判定することができます。

実装例

public void DetectingEncodeTest() {
    var path = @"C:\Temp\Test.txt";

    byte[] bytes = null;
    using (var fs = new FileStream(path, FileMode.Open)) {
        bytes = new byte[fs.Length];
        fs.Read(bytes, 0, bytes.Length);
    }
    string str = null;
    var encode = ReadJEnc.JP.GetEncoding(bytes, bytes.Length, out str);

    Debug.WriteLine(encode.ToString());
}

実行結果

ShiftJIS

FlexLuceneで日付フィルタリングを実現する方法

 ポイントは、以下の2点です。

  • ドキュメントの日付を、同一フィールド名でLongPointとStoredFieldを使って登録する。(17行目付近)
  • 検索時にLongPoint.NewRangeQueryを使って、絞込みを行う点です。(32行目)

実装例

public void LongPointTest() {
    var analyzer = new WhitespaceAnalyzer();
    var iwc = new IndexWriterConfig(analyzer);

    iwc.SetOpenMode(IndexWriterConfigOpenMode.CREATE);

    //テスト用インデックス作成---------------------------------------------
    DateTime baseDate = DateTime.Parse("2020/07/16 08:00:00");
    var ram = new RAMDirectory();
    var writer = new IndexWriter(ram, iwc);
    try {
        for (int i = 0; i < 10; i++) {
            var doc = new Document();
            doc.Add(new TextField("text", "hoge foo", FieldStore.YES));
            DateTime tmp = baseDate.AddDays(i);
            long l = long.Parse(tmp.ToString("yyyyMMddHHmmss"));
            //日付文字列をlong値で保持
            doc.Add(new LongPoint("date", l));
            //long値をストアするには、同じフィールド名でStoredFieldとして指定する必要がある。
            doc.Add(new StoredField("date", l));

            writer.AddDocument(doc);
        }
        
    } finally {
        writer.Close();
    }

    //検索------------------------------------------------------------
    TermQuery tq = new TermQuery(new Term("text", "foo"));
    //日付範囲の条件
    Query rq = LongPoint.NewRangeQuery("date", 20200717000000, 20200719000000);

    BooleanQueryBuilder b = new BooleanQueryBuilder();
    b.Add(tq, BooleanClauseOccur.MUST); //AND条件
    b.Add(rq, BooleanClauseOccur.FILTER); //AND条件(スコアリングに関与しない)
    Query q = b.Build();

    DirectoryReader dr = DirectoryReader.Open(ram);
    IndexSearcher searcher = new IndexSearcher(dr);
    ScoreDoc[] hits = searcher.Search(q, 100).ScoreDocs;
    for (int i = 0; i < hits.Length; i++) {
        var doc = searcher.Doc(hits[i].Doc);
        Debug.WriteLine(DateTime.ParseExact(doc.Get("date"), "yyyyMMddHHmmss", null));
    }
}

検索結果

2020/07/17 8:00:00
2020/07/18 8:00:00

C#でファイルの拡張プロパティを取得/編集する方法

 

  • NuGetでWindowsAPICodePack-Shellをインストール。
  • 以下のコードで取得/編集ができる。
    using Microsoft.WindowsAPICodePack.Shell;
    using Microsoft.WindowsAPICodePack.Shell.PropertySystem;

    public void FilePropertiesTest() {
        var file = ShellFile.FromFilePath(@"C:\Temp\test.jpg");
        //拡張プロパティ取得
        Console.WriteLine(file.Properties.System.Title.Value);
        Console.WriteLine(file.Properties.System.Author.Value);
        Console.WriteLine(file.Properties.System.Comment.Value);

        //拡張プロパティセット
        ShellPropertyWriter propertyWriter =  file.Properties.GetPropertyWriter();
        propertyWriter.WriteProperty(SystemProperties.System.Title, new string[] { "タイトル" });
        propertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "著者" });
        propertyWriter.WriteProperty(SystemProperties.System.Comment, new string[] { "コメント" });
        propertyWriter.Close();
    }

C#でEveryoneフルコントロール権限を付与

 

Everyoneフルコントロール権限を付与

public class ExchangeUtil : PublicWebApiUtil {
    /// Everyoneフルコントロール権限を付与
    /// 処理対象パス
    public static void AddFullControleRule(string filePath) {
        //EveryOneFullControle
        var rule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, 
            InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow);

        //ファイルセキュリティオブジェクトを取得
        FileSecurity security = File.GetAccessControl(filePath);
        //権限付与
        security.AddAccessRule(rule);
        //変更したファイルセキュリティをファイルに設定
        File.SetAccessControl(filePath, security);
    }
}

C#でファイルがロックされているかどうか判定

 

ファイルがロックされているかどうか判定

public class ExchangeUtil : PublicWebApiUtil {
    /// ファイルが開かれてロックされているかどうか
    /// true:ロックされている/false:されていない
    public static bool IsFileLocked(string path) {
        FileStream stream = null;
        if (!File.Exists(path)) {
            return false;
        }
        try {
            stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        } catch {
            return true;
        }
        finally {
            if (stream != null) {
                stream.Close();
            }
        }
     
        return false;
    }
}

C#でISO8601形式の継続時間文字列をTimeSpanに変換

 

ISO8601形式の継続時間文字列をTimeSpanに変換

public class ExchangeUtil : PublicWebApiUtil {
    /// 
    /// ISO8601形式の文字列をTimeSpanに変換します。
    /// 
    /// ISO8601形式の文字列
    /// 
    public static TimeSpan Iso8601ToTimeSpan(string iso8601) {
        if (iso8601 == null || iso8601 == "") {
            //0秒で返す。
            return new TimeSpan(0, 0, 0);
        }
        TimeSpan? ret = null;
        int index = iso8601.IndexOf("D");
        if (index > 0) {
            //日付部("P1D")が存在する場合
            string strDays = iso8601.Substring(0, index);
            TimeSpan days = new TimeSpan(int.Parse(strDays.Replace("P", "")), 0, 0, 0);
            ret = days;

            //時間部が存在する場合
            index = iso8601.IndexOf("DT");
            if (index > 0) {
                TimeSpan other = XmlConvert.ToTimeSpan("PT" + iso8601.Substring(index + 2));
                ret = days.Add(other);
            }
        } else {
            ret =  XmlConvert.ToTimeSpan(iso8601.Replace("P", "PT"));
        }
        return new TimeSpan(ret.Value.Days, ret.Value.Hours, ret.Value.Minutes, 0);
    }
}

C#でランダムに色を生成する方法

 

ランダムに色を生成

public class ExchangeUtil : PublicWebApiUtil {
    /// 
    /// ランダムカラー取得
    /// 
    /// シードとなる疑似乱数ジェネレータ
    /// 
    public Color GetRandomColor(Random r) {
        int red = r.Next(256);
        int green = r.Next(256);
        int blue = r.Next(256);

        return Color.FromArgb(red, green, blue);
    }
}

淡い色だけ生成

public class ExchangeUtil : PublicWebApiUtil {

    /// 淡いランダムカラー取得
    /// 
    /// シードとなる疑似乱数ジェネレータ
    /// 
    public Color GetPaleRandomColor(Random r) {
        int red = r.Next(100, 256);
        int green = r.Next(100, 256);
        int blue = r.Next(100, 256);

        return Color.FromArgb(red, green, blue);
    }
}

C#でメール送信


メール送信サンプル

public class ExchangeUtil : PublicWebApiUtil {
    /// <summary>
    /// メール送信
    /// </summary>
    /// <param name="fromAddress">送信元アドレス</param>
    /// <param name="toAddress">送信先アドレス</param>
    /// <param name="subject">件名</param>
    /// <param name="body">メール本文</param>
    public void SendMail(string fromAddress, string toAddress, string subject, string body) {
        MailMessage msg = new MailMessage();
        SmtpClient sc = new SmtpClient();
        try {
            msg.From = new MailAddress(fromAddress, "表示名");
            msg.To.Add(new MailAddress(toAddress, ""));
            //件名
            msg.Subject = subject;
            //本文
            msg.Body = body;

            //SMTPサーバーなどを設定する
            sc.Host = this.SmtpAddress;
            sc.Port = this.SmtpPort;
            sc.DeliveryMethod = SmtpDeliveryMethod.Network;
            //メッセージを送信する
            sc.Send(msg);
        } finally {
            msg.Dispose();
            sc.Dispose();
        }
    }
}

C#で外為オンラインから為替レートを取得してみた

 為替レートを取得するサンプルです。

「Yahoo Finance」、「Google Finance」が廃止となったので、外為オンラインから取得してみました。


為替レート取得クラス

public class ExchangeUtil : PublicWebApiUtil {
    public enum CurrencyPairCode : int {
        //英ポンド/NZドル
        GBPNZD = 1,
        //カナダドル/NZドル
        CADJPY,
        //英ポンド/AUドル
        GBPAUD,
        //AUドル/円
        AUDJPY,
        //AUドル/NZドル
        AUDNZD,
        //ユーロ/カナダドル
        EURCAD,
        //ユーロ/米ドル
        EURUSD,
        //NZドル/円(jsonString);

        return ds.Tables[0];
    }

    // 指定した貨幣コードの始値を取得
    public Decimal GetOpenPrice(CurrencyPairCode currencyPairCode) {
        Decimal price = -1;

        DataTable exchangeTbl = GetExchangeRateTable();
        DataRow[] rows = (
            from row in exchangeTbl.AsEnumerable()
            let qOpenPrice = row.Field(EnumUtil.GetLabel(RateTableColIdx.Open))
            let qCurrencyPairCode = row.Field(EnumUtil.GetLabel(RateTableColIdx.CurrencyPairCode))
            where qCurrencyPairCode == EnumUtil.GetName(currencyPairCode)
            select row).ToArray();

        price = Decimal.Parse(rows[0][(int)RateTableColIdx.Open].ToString());

        return price;
    }

}

親クラス

public class PublicWebApiUtil {
    public PublicWebApiUtil() {
    }
    /// WebAPI呼び出し
    protected string GetResponseString(string url) {
        HttpWebRequest req = null;
        HttpWebResponse res = null;
        StreamReader sr = null;
        string jsonString = "";
        try {
            //サーバーからデータを受信する
            req = (HttpWebRequest)WebRequest.Create(url);
            res = (HttpWebResponse)req.GetResponse();
            sr = new StreamReader(res.GetResponseStream());
            //すべてのデータを受信する
            jsonString = sr.ReadToEnd();
        } finally {
            sr.Close();
            res.Close();
        }
        return jsonString;
    }
}

使い方

     public void GetPriceRate() {
         ExchangeUtil eu = new ExchangeUtil();
         //始値のレートを取得
         Decimal d = eu.GetOpenPrice(ExchangeUtil.CurrencyPairCode.USDJPY);
     }

C#でMP3, MP4のメタデータを取得/編集する方法

NuGetにtaglibという便利なライブラリがあるので、早速、インストールしてみた。
使い方は、以下のような感じ。
ジャケットイメージも付けれるので、貯まったメディアファイルの整理に役立ちそう。

private void SaveTag() {
    var f = TagLib.File.Create(@"C:\Temp\対象.mp3");

    //タイトル
    f.Tag.Title = "タイトル";
    //アーティスト
    f.Tag.Performers = new string[] { "タイトル名" };
    //ジャンル
    f.Tag.Genres = new string[] { "洋楽" };
    //歌詞
    f.Tag.Lyrics = "歌詞";
    //コメント
    f.Tag.Comment = "コメント";

    //画像
    string imgPath = @"C:\Temp\カバー画像.jpeg";
    var ic = new System.Drawing.ImageConverter();
    var ba = (byte[])ic.ConvertTo(Image.FromFile(imgPath), typeof(byte[]));
    var byteVector = new TagLib.ByteVector(ba);
    var pic = new TagLib.Picture(byteVector);
    pic.Type = TagLib.PictureType.FrontCover;
    pic.Description = "Cover";
    pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
    f.Tag.Pictures = new TagLib.IPicture[] { pic };

    f.Save();
}

将来構想

貯まったMP3,MP4に対する情報を、Webから収集し、メタデータとして自動付与するツールを作成。
後は、全文検索ツールのPokuda Searchを使って、
見たいファイルにすぐにアクセスといったことを考え中。

これで、ファイル整理の手間も省けるかも。。。

C#でGoogle Maps APIを使う(2点間の距離を取得)

Google Maps APIを使って2点間の距離を取得するメソッドを実装してみました。

public static double GetDistance(string origin, string destination, string apiKey) {
    double ret = 0;
    WebResponse response = null;
    try {
        string url = @"https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + 
            origin + "&destinations=" + destination + "&key=" + apiKey;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        response = request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader sReader = new StreamReader(dataStream);
        string jsonString = sReader.ReadToEnd();
        Debug.Write(jsonString);

        var jo = JObject.Parse(jsonString);
        JToken jt = jo.SelectToken("$.rows..elements..distance.value");
        ret = double.Parse(StringUtil.NullBlankToZero(jt.ToString()));

        return ret;
    } finally {
        response.Close();
    }
}

例えば「origin:東京」-「destination:大阪」を指定してリクエストを投げると、以下の形式のJSONが返されるので、
JSONPathを使って、距離の部分を抜き出して戻り値にセットしています。

●例)「東京」-「大阪」間でリクエストを投げた時のJSON取得結果
{
   "destination_addresses" : [ "Osaka, Osaka Prefecture, Japan" ],
   "origin_addresses" : [ "Tokyo, Japan" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "513 km",
                  "value" : 512545
               },
               "duration" : {
                  "text" : "6 hours 16 mins",
                  "value" : 22563
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Simple Injectorを使ってみた


手軽に利用できるDIコンテナ「Simple Injector」を使ってみました。
パッケージ開発のアドオンの受け口などで活用できそうです。

●このデモで利用するクラス一覧
クラス/インタフェース 説明
Program.cs このクラスで以下の処理を行います。
・コンテナ生成
・注入オプジェクト登録
・コンテナの登録内容の検証
・InjectionTargetClassのメソッドを実行
IProxy.cs 注入オブジェクトのインタフェースです。
HogeProxy.cs 注入オブジェクトの具象クラス。
FooProxy.cs 注入オブジェクトの具象クラス。
BarClass.cs 注入オブジェクトの具象クラス。(IProxyは実装していない。)
InjectionTargetClass.cs オブジェクト注入対象のクラスです。
このクラスで注入されたオブジェクトを利用します。
コンストラクタの引数に注目してください。
コンテナに登録されたオブジェクトが渡されます。

●Program.cs
using SimpleInjector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleInjectorInConsoleApp {
    class Program {

        private static Container container;

        static void Main(string[] args) {
            
            container = new Container();

            //デフォルトのLifestyleを確認
            Console.WriteLine("デフォルトのLifestyle : " + container.Options.DefaultLifestyle.ToString());

            container.Register(Lifestyle.Singleton);
            //登録をFooProxyに切替えると、利用側のクラスを変更せずに処理を切り替えれます。
            //container.Register(Lifestyle.Singleton);

            //コンストラクタにRegister()していないTypeの引数を渡す方法
            container.Register(() => new BarClass("bar"), Lifestyle.Singleton);

            container.Verify();

            // Useコンテナに登録していないが、コンストラクタインジェクションを行って必要な
            // オブジェクトを設定してインスタンスを作成してくれる。 (auto-wiring)
            var a = container.GetInstance();
            a.Write();

            //自動でコンソールが閉じるの防ぐ
            Console.ReadLine();
        }
    }
}

●IProxy.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleInjectorInConsoleApp {
    /// 
    /// インタフェース
    /// 
    public interface IProxy {
        void Write();
    }
}

●HogeProxy.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleInjectorInConsoleApp {
    /// 
    /// 注入クラスHoge
    /// 
    class HogeProxy : IProxy {
        public void Write() {
            Console.WriteLine("hoge");
        }
    }
}

●FooProxy.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleInjectorInConsoleApp {
    /// 
    /// 注入クラスFoo
    /// 
    class FooProxy : IProxy {
        public void Write() {
            Console.WriteLine("foo");
        }
    }
}

●BarClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleInjectorInConsoleApp {
    /// 
    /// 注入クラスBar
    /// ※ IProxyを実装していない
    /// 
    public class BarClass {
        private string val = "";
        public BarClass(string str) {
            val = str; 
        }

        public void Write() {
            Console.Write(val);
        }
    }
}

●InjectionTargetClass.cs
using SimpleInjector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleInjectorInConsoleApp {
    /// 
    /// オブジェクト注入対象クラス
    /// 
    public class InjectionTargetClass {
        private readonly IProxy _proxy;
        private readonly Container _container;
        private readonly BarClass _dummy;

        public InjectionTargetClass(IProxy proxy, Container container, BarClass dummy) {
            _proxy = proxy;
            _container = container;
            _dummy = dummy;
        }

        public void Write() {
            _proxy.Write();
            Console.WriteLine("注入コンテナのDefaultLifestyle : " + 
                _container.Options.DefaultLifestyle);
            _dummy.Write();
        }
    }
}

●実行結果

Microsoft Teamsにエラーログを出力するLog4Net Custom Appenderを作ってみた。


Custom AppenderクラスはAppenderSkeletonを継承し、Append()メソッドをオーバライドして作成。
IncomingWebhooksのURLをlog4net.configから取得できるようにプロパティを作成しておく。

●Custom Appenderクラスは以下のとおり。
 MSTeamsUtil()の実装についてはこちらを参考にして下さい。
public class MSTeamsAppender : AppenderSkeleton {

    //Microsoft TeamsのコネクタURL
    public string IncomingWebhookURL { getset; }  

    // Microsoft Teamsにログ追記
    protected override void Append(LoggingEvent loggingEvent) {
        var mstu = new MSTeamsUtil();
        mstu.PostPlainMessage(IncomingWebhookURL, RenderLoggingEvent(loggingEvent));
    }
}
●log4net.configの設定方法は以下のとおり
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <log4net>
    <appender name="MSTeamsAppender" type="FxCommonLib.Log4NetAppender.MSTeamsAppender, FxCommonLib">
      <incomingWebhookURL value="https://outlook.office.com/・・・" />
      <layout type="log4net.Layout.PatternLayout">
        <ConversionPattern value="%username %d [%t] %-5p %c - %m%n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="WARN" />
        <levelMax value="FATAL" />
      </filter>
    </appender>
    <root>
      <level value="INFO" />
      <appender-ref ref="MSTeamsAppender" />
    </root>
  </log4net>
</configuration>
こんな感じでログが投稿されます。

Microsoft TeamsにC#でメッセージ投稿してみた


最近、無償提供されたMicrosoft Teamsにプログラムからメッセージ投稿してみたいと思い、実装してみた。
システム監視、センサなどから情報投稿など、いろいろ利用できそう。

まずは、Microsoft TeamsのIncoming Webhook APIのURLを取得。
取得方法の詳細はこちら

○Microsoft Teamsに平文メッセージを投稿するためのユーティリティメソッド
public class MSTeamsUtil {
    // Microsoft Temasに平文メッセージを投稿
    public void PostPlainMessage(string webhookURL, string message) {
        using (var client = new WebClient()) {
            var param = new Dictionary();
            // Textパラメータは必須
            param["Text"] = message;
            var json = JsonConvert.SerializeObject(param);

            client.Headers.Add(HttpRequestHeader.ContentType, "application/json;charset=UTF-8");
            client.Encoding = Encoding.UTF8;
            client.UploadString(webhookURL, json);
        }
    }
}
○利用側のソース
public class MSTeamsUtilTest {
    //取得したImcoming WebhooksのURLをセット
    private string _webhookURL = "https://outlook.office.com/webhook/・・・";

    public void PostPlainMessageTest() {
        var mst = new MSTeamsUtil();
        mst.PostPlainMessage(_webhookURL, "hoge hoge");
    }
}
最初、HttpClientで実装しようとしたが、PostAsAsync()実行時にエラー(ExceptionもCatchできない状態)となった。
エラーの原因は、よく解らないので、追々調査してみることに。

代わりにWebClientに変更して実装してみるとメッセージ投稿に成功した。

なお、HttpClientを利用する時はリクエストの度にインスタンス生成・破棄してはならにとのこと。
TCPコネクションが都度、張られ、パフォーマンスを低下させるとのこと。

WebClientではリクエストの度にインスタンス生成・破棄してもTCPコネクションが使い回されるため問題ない。

【参考】
C# HTTPクライアントまとめ
不適切なインスタンス化のアンチパターン

厳選 Visual Studioの便利なショートカット

  エラー箇所にジャンプ 「Ctrl + Shift + F12」 ブレークポイント 設定/解除 「F9」 有効化/無効化 「Ctrl + F9」 ViEmu特有 「:ls」:バッファナンバーのリストを表示。 「:b2」:バッファ2のファイルを開く。 「:n」:次のバッファのファ...