IRONPDFの使用

IronPDFを使用したC#でのFluent Validationの方法

リーガン・パン
リーガン・パン
2023年6月27日
更新済み 2024年3月17日
共有:

フルーエントバリデーションとは何ですか?

FluentValidation (フルーエントバリデーション)は、厳密に型指定された検証ルールの構築を支援する.NET検証ライブラリです。 これは流暢なインターフェースとラムダ式を提供することで実現され、コードをより読みやすく、保守しやすくします。 モデルクラスでデータ注釈や手動検証を使用する代わりに、Fluent Validation を使用して検証ロジック用の別のクラスを作成できます。

Fluent Validationは、バリデーションの分野により柔軟性をもたらします。 組み込みのバリデーターで一般的なシナリオに対応し、カスタムバリデーションを構築する能力、そしてバリデーションルールをチェーンする簡単な方法を備えたFluent Validationは、.NET Coreツールキットの強力なツールです。

流暢なバリデーションの理解

Fluent Validationは、モデルクラスのバリデーションルールを簡単に構築できるオープンソースの.NETライブラリです。

  1. バリデーター: バリデーターは、検証ロジックをカプセル化するクラスです。 AbstractValidator から継承することによって通常作成されます。基本クラス。

  2. ルール: ルールとは、プロパティが満たさなければならない検証条件のことです。 ルールは、バリデータクラス内のRuleForメソッドを使用して定義されます。

  3. 検証エラー: ルールが失敗すると、Fluent Validationはエラーの詳細(プロパティ名とエラーメッセージを含む)を含むValidationFailureオブジェクトを作成します。

IronPDFとは何ですか?

IronPDF - C#でHTMLをPDFに変換は、HTMLコンテンツからPDF文書を生成できる強力な.NETライブラリです。 請求書、レポート、その他どのような種類のドキュメントを作成する必要がある場合でも、IronPDFは使いやすいソリューションを提供します。 それは、ASP.NET Core アプリケーションとシームレスに統合され、わずか数行のコードで高品質なPDFファイルを生成できます。

IronPDFでFluent Validationを使用する

では、Fluent ValidationとIronPDFがどのようなものか理解したところで、それらを一緒に使用する方法を見てみましょう。 このチュートリアルでは、請求書生成ツールを構築する際に、FluentValidationを使用してASP.NET Coreで請求書の内容が検証され、IronPDFを使用してPDFを生成する方法を紹介します。

それでは、始めましょう!

プロジェクトの設定

まずは、Visual Studio またはお好みの開発環境で新しいコンソールアプリケーションを作成しましょう。

  1. Visual Studio を開き、ファイル > 新規作成 > プロジェクトに進みます。

  2. "Console App" を選択(ASP.NET Core)「プロジェクトテンプレートを選択し、プロジェクトに名前を付けてください。」

    C#でIronPDFを使用したフルーエントバリデーションの使用方法 図1: 新しいコンソールアプリケーションの作成

    新しいコンソールアプリケーションを作成

  3. Next ボタンをクリックして、プロジェクトに名前を付け、リポジトリの場所を選択して設定してください。

    IronPDFとC#で流れるようなバリデーションを使用する方法, 図2 - 新しいアプリケーションを設定

    アプリケーションの新しい構成

  4. 次へボタンをクリックして、.NET Frameworkを選択してください。 最新の .NET Framework(7)推奨されます。

    IronPDFを使用したFluent Validationの使い方 (C#)、図3: .NET Frameworkの選択

    .NETフレームワークの選択

  5. Create ボタンをクリックしてプロジェクトを作成します。

必要なパッケージをインストール

プロジェクトが作成されたら、Fluent ValidationおよびIronPDFの必要なNuGetパッケージを追加する必要があります。

  1. ソリューションエクスプローラーでプロジェクトを右クリックし、「NuGet パッケージの管理」を選択します。

  2. 「FluentValidation」を検索し、「インストール」をクリックしてパッケージをプロジェクトに追加します。

    IronPDFでFluent ValidationをC#で使用する方法、図4:NuGetパッケージマネージャーUIでFluentValidationパッケージをインストール

    NuGet パッケージ マネージャー UI で FluentValidation パッケージをインストールする

  3. 同様に、"IronPDF - 強力な.NET PDFライブラリ" をクリックし、IronPDFパッケージをインストールしてください。

    しかし、次のコマンドを使用してNuGet パッケージ マネージャー コンソールを使ってIronPDFをインストールすることもできます:

Install-Package IronPdf

C#でIronPDFと共にFluent Validationを使用する方法、図5: パッケージ マネージャー コンソールでIronPdfパッケージをインストール

パッケージマネージャーコンソールでIronPDFパッケージをインストール

プロジェクトのセットアップと必要なパッケージのインストールが完了したら、PDFコンテンツクラスの定義に進みましょう。

PDFコンテンツの定義

この例では、InvoiceContentInvoiceItemという新しい2つのクラスのHTMLコードから簡単な請求書PDFが作成されます。

public abstract class PdfContent
{
    public abstract string RenderHtml();
}

public class InvoiceContent : PdfContent
{
    public string CustomerName { get; set; }
    public string Address { get; set; }
    public List<InvoiceItem> InvoiceItems { get; set; }

    public override string RenderHtml()
    {
        string invoiceItemsHtml = string.Join("", InvoiceItems.Select(item => $"<li>{item.Description}: {item.Price}</li>"));
        return $"<h1>Invoice for {CustomerName}</h1><p>{Address}</p><ul>{invoiceItemsHtml}</ul>";
    }
}

public class InvoiceItem
{
    public string Description { get; set; }
    public decimal Price { get; set; }
}
public abstract class PdfContent
{
    public abstract string RenderHtml();
}

public class InvoiceContent : PdfContent
{
    public string CustomerName { get; set; }
    public string Address { get; set; }
    public List<InvoiceItem> InvoiceItems { get; set; }

    public override string RenderHtml()
    {
        string invoiceItemsHtml = string.Join("", InvoiceItems.Select(item => $"<li>{item.Description}: {item.Price}</li>"));
        return $"<h1>Invoice for {CustomerName}</h1><p>{Address}</p><ul>{invoiceItemsHtml}</ul>";
    }
}

public class InvoiceItem
{
    public string Description { get; set; }
    public decimal Price { get; set; }
}

上記のコードでは、RenderHtmlと呼ばれる抽象メソッドを持つ抽象クラス PdfContent が定義されています。 InvoiceContentクラスはPdfContentを拡張し、請求書PDFのコンテンツを表します。 顧客名、住所、および請求書項目のリストに関するプロパティがあります。 InvoiceItem クラスには、'Description' と 'Price' の2つのプロパティがあります。 RenderHtml メソッドは、コンテンツに基づいて請求書のHTMLマークアップを生成します。

PDFコンテンツが定義されたので、Fluent Validationを使って検証ルールの作成に進みましょう。

検証ルールの作成

InvoiceContent クラスのためにバリデーションルールを作成するには、InvoiceContentValidator と呼ばれるバリデータークラスを作成します。 このクラスは AbstractValidator から継承されます。Fluent Validation が提供するもの。

using FluentValidation;

public class InvoiceContentValidator : AbstractValidator<InvoiceContent>
{
    public InvoiceContentValidator()
    {
        RuleFor(content => content.CustomerName).NotEmpty().WithMessage("Customer name is required.");
        RuleFor(content => content.Address).NotEmpty().WithMessage("Address is required.");
        RuleFor(content => content.InvoiceItems).NotEmpty().WithMessage("At least one invoice item is required.");
        RuleForEach(content => content.InvoiceItems).SetValidator(new InvoiceItemValidator());
    }
}

public class InvoiceItemValidator : AbstractValidator<InvoiceItem>
{
    public InvoiceItemValidator()
    {
        RuleFor(item => item.Description).NotEmpty().WithMessage("Description is required.");
        RuleFor(item => item.Price).GreaterThanOrEqualTo(0).WithMessage("Price must be greater than or equal to 0.");
    }
}
using FluentValidation;

public class InvoiceContentValidator : AbstractValidator<InvoiceContent>
{
    public InvoiceContentValidator()
    {
        RuleFor(content => content.CustomerName).NotEmpty().WithMessage("Customer name is required.");
        RuleFor(content => content.Address).NotEmpty().WithMessage("Address is required.");
        RuleFor(content => content.InvoiceItems).NotEmpty().WithMessage("At least one invoice item is required.");
        RuleForEach(content => content.InvoiceItems).SetValidator(new InvoiceItemValidator());
    }
}

public class InvoiceItemValidator : AbstractValidator<InvoiceItem>
{
    public InvoiceItemValidator()
    {
        RuleFor(item => item.Description).NotEmpty().WithMessage("Description is required.");
        RuleFor(item => item.Price).GreaterThanOrEqualTo(0).WithMessage("Price must be greater than or equal to 0.");
    }
}

上記のソースコードでは、InvoiceContentValidatorクラスが定義されており、これはAbstractValidatorから継承されています。. バリデータクラスのコンストラクタ内部で、RuleForメソッドはInvoiceContent` クラス各プロパティに対する検証ルールを定義します。

例: RuleFor(内容 => 内容.CustomerName)顧客名が空であってはならないという新しいルールを定義できます。 Fluent ValidationNotEmpty メソッドを連鎖してこのバリデーションルールを指定することができます。 同様に、住所や請求書項目のプロパティに対してもバリデーションルールを定義します。

請求書の項目を検証するために、RuleForEachメソッドを使用して、InvoiceItemsリスト内の各項目を反復処理し、InvoiceItemValidatorというバリデーターを適用します。 InvoiceItemValidatorクラスは別に定義されており、InvoiceItemクラスのバリデーションルールを含んでいます。

これらの検証ルールを設定したら、IronPDFを使用してPDFの生成に進みましょう。

IronPDFを使用してPDFを生成する

IronPDF - PDFドキュメントの生成と編集は PDF ドキュメントの作成および操作のための人気のある .NET ライブラリです。 IronPDFは、検証済みの請求書コンテンツに基づいてPDFを生成するために使用されます。

using IronPdf;
using FluentValidation;

public class PdfService
{
    public PdfDocument GeneratePdf<T>(T content) where T : PdfContent
    {
        var validator = GetValidatorForContent(content);
        FluentValidation.Results.ValidationResult validationResult = validator.Validate(content);

        if (!validationResult.IsValid)
        {
            throw new FluentValidation.ValidationException(validationResult.Errors);
        }

        var renderer = new ChromePdfRenderer();
        return renderer.RenderHtmlAsPdf(content.RenderHtml());
    }

    private IValidator<T> GetValidatorForContent<T>(T content) where T : PdfContent
    {
        if (content is InvoiceContent)
        {
            return (IValidator<T>)new InvoiceContentValidator();
        }
        else
        {
            throw new NotSupportedException("Unsupported content type.");
        }
    }
}
using IronPdf;
using FluentValidation;

public class PdfService
{
    public PdfDocument GeneratePdf<T>(T content) where T : PdfContent
    {
        var validator = GetValidatorForContent(content);
        FluentValidation.Results.ValidationResult validationResult = validator.Validate(content);

        if (!validationResult.IsValid)
        {
            throw new FluentValidation.ValidationException(validationResult.Errors);
        }

        var renderer = new ChromePdfRenderer();
        return renderer.RenderHtmlAsPdf(content.RenderHtml());
    }

    private IValidator<T> GetValidatorForContent<T>(T content) where T : PdfContent
    {
        if (content is InvoiceContent)
        {
            return (IValidator<T>)new InvoiceContentValidator();
        }
        else
        {
            throw new NotSupportedException("Unsupported content type.");
        }
    }
}

上記のソースコードでは、PdfServiceクラスが定義されており、その中でGeneratePdfメソッドが提供されています。 このメソッドは、 PdfContent オブジェクトを入力として受け取り、検証されたコンテンツに基づいてPDFドキュメントを生成します。

まず、GetValidatorForContentメソッドを呼び出して、コンテンツに対する適切なバリデーターを取得します。 このメソッドはコンテンツのタイプをチェックし、対応するバリデーターを返します。 私たちの場合、InvoiceContentのみをサポートし、InvoiceContentValidatorを使用します。

次に、バリデータのvalidateメソッドを呼び出してコンテンツを検証します。 検証結果は ValidationResult オブジェクトに保存されます。

検証に失敗した場合(もちろん、英語のテキストを教えていただけますでしょうか?!validationResult.IsValid), 検証エラーを含む FluentValidation.ValidationException をスローします。 それ以外の場合は、IronPDFを使用してPDFを生成します。

次のようにインスタンスを作成します:ChromePdfRenderer(クロームPDFレンダラー)HTMLコンテンツをPDFとしてレンダーする。 私たちはそれを呼びますRenderHtmlAsPdf(HTMLをPDFとしてレンダリング)htmlToPdfオブジェクトのメソッドを使用し、content.RenderHtmlメソッドによって生成されたHTMLを引数として渡します。 これによりPDFドキュメントが生成されます。

PDF生成ロジックを定義したので、発生する可能性のある検証エラーを処理しましょう。

検証エラーの処理

バリデーションエラーが発生したとき、エラーメッセージを表示し、優雅に処理したいです。 Program クラスの Main メソッドを修正して、エラーを処理し、ユーザーに意味のあるメッセージを表示しましょう。

public class Program
{
    static void Main(string [] args)
    {
        var pdfService = new PdfService();

        // Test 1: Empty Customer Name
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                    new InvoiceItem { Description = "Item 1", Price = 19.99M },
                    new InvoiceItem { Description = "Item 2", Price = 29.99M }
                }
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        // Test 2: Empty InvoiceItems
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem>()  // Empty list
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        //Successful
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                new InvoiceItem { Description = "Item 1", Price = 19.99M },
                new InvoiceItem { Description = "Item 2", Price = 29.99M }
            }
            };
            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }
    }
}
public class Program
{
    static void Main(string [] args)
    {
        var pdfService = new PdfService();

        // Test 1: Empty Customer Name
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                    new InvoiceItem { Description = "Item 1", Price = 19.99M },
                    new InvoiceItem { Description = "Item 2", Price = 29.99M }
                }
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        // Test 2: Empty InvoiceItems
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem>()  // Empty list
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        //Successful
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                new InvoiceItem { Description = "Item 1", Price = 19.99M },
                new InvoiceItem { Description = "Item 2", Price = 29.99M }
            }
            };
            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }
    }
}

上記のコードでは、try-catch ブロックが発生する可能性のある例外をキャッチするのに役立ちます。 例外がキャッチされた場合、Console.WriteLineを使用してユーザーにエラーメッセージが表示されます。

では、このアプリケーションを異なるシナリオでテストして、PDF生成とバリデーションルールを検証しましょう。

アプリケーションのテスト

このコード例では、テストするシナリオが三つあります:

  1. 顧客名が空です: 検証エラーを引き起こすために顧客名を空のままにします。

  2. 空の請求書項目:検証エラーを発生させるために、空の請求書項目のリストが提供されています。

  3. 生成の成功: PDFを正常に生成するために有効なコンテンツを提供してください。

    アプリケーションを実行して、コンソールに出力を表示します。

Error generating PDF: Validation failed:
    -- CustomerName: Customer name is required. Severity: Error
Error generating PDF: Validation failed:
    -- InvoiceItems: At least one invoice item is required. Severity: Error
PDF generated successfully!

IronPDFをC#で使用した流暢なバリデーションの方法, 図6: コンソールにおける出力エラー

コンソールの出力エラー

C#でIronPDFを使用した流暢なバリデーションの方法, 図7: 出力されたPDFファイル

出力PDFファイル

予想通り、最初の二つのシナリオでは検証エラーが表示され、三つ目のシナリオでは成功メッセージが表示されます。

結論

このチュートリアルでは、Fluent Validationを調査し、IronPDFを使用してPDF文書を生成する方法を学びました。 コンソールアプリケーションを設定し、PDFコンテンツクラスを定義することから始めます。 次に、Fluent Validationを使用して検証ルールを作成し、さまざまなシナリオでPDF生成をテストしました。

Fluent Validationは、.NETアプリケーションにおけるオブジェクトのバリデーションに対して柔軟で使いやすいアプローチを提供します。 強く型付けされた方法で検証ルールを定義し、エラーメッセージをカスタマイズし、検証エラーを優雅に処理することができます。

IronPDF 無料トライアルとライセンス情報は無料トライアルを提供しており、ライセンスは開発者1人あたり499ドルからとなっています。

リーガン・パン
ソフトウェアエンジニア
レーガンはリーディング大学で電子工学の学士号を取得しました。Iron Softwareに入社する前の仕事では、一つのタスクに集中して取り組んでいました。Iron Softwareでは、営業、技術サポート、製品開発、マーケティングのいずれにおいても広範な業務に携わることが最も楽しいと感じています。彼は、Iron Softwareライブラリを開発者がどのように使用しているかを理解し、その知識を使ってドキュメントを継続的に改善し、製品を開発することを楽しんでいます。
< 以前
PDF vs PDFA(開発者のための仕組み)
次へ >
C#開発者向けIronPDFでChatGPTを利用する方法