跳至頁尾內容
.NET幫助

Flunt C#(對於開發者的運行原理)

在當前的軟體開發環境中,生產高品質的文件並保證資料完整性是基本任務。 在這篇文章中,我們將探討如何結合強大的C#程式庫,Flunt C#和IronPDF,以改善資料驗證和文件建立的工作流程。 開發者可以利用IronPDF的高級PDF生產特性和Flunt的強大驗證功能,為各種軟體應用程式構建有效而可靠的解決方案。

How to use Flunt in C

  1. 建立一個新的C#主控台專案。
  2. 從NuGet安裝Flunt套件。
  3. 匯入命名空間並繼承類。
  4. 將驗證加入到資料模型中。
  5. 執行驗證檢查並顯示結果。

Understanding of Flunt C

多功能且輕量的.NET框架Flunt旨在促進在C#應用程式中流利的驗證和通知模式的開發。 當開發者使用Flunt以流暢和表達式的方式構建驗證規則和業務邏輯時,程式碼變得更加易讀和易於維護。 借助Flunt廣泛的內建驗證技術和擴展,開發者可以輕鬆驗證像物件和集合這樣的複雜資料結構。

此外,Flunt是一個有用的工具,可以提升.NET程式庫應用程式的可靠性和穩健性,因為它能輕鬆地與現有的程式碼基和框架整合。 總的來說,Flunt鼓勵采用宣告式的驗證和錯誤處理方法,使開發者能夠編寫更清晰、更穩健的程式碼。

Features of Flunt C

流暢的介面: Flunt提供了一個易讀和扼要的介面,用於構建驗證規則,簡化了複雜驗證邏輯的表達。

可鏈式驗證: 通過自然地連接驗證規則,可以使用少量程式碼建立可鏈式的驗證場景。

內建驗證器: Flunt附帶了多個內建驗證器,用於常用資料型別,包括日期、整數、字串和集合。 流暢的語法允許輕鬆將這些驗證器應用到屬性。

自定義驗證規則: 通過擴展Flunt框架,開發者可以新增自定義驗證規則,允許適應特定領域需求的驗證邏輯。

通知系統: Flunt提供了一個通知系統,用以報告驗證問題並收集錯誤訊息。 這使得開發者可以輕鬆地通知使用者或應用程式的其他組件驗證失敗情況。

與框架整合: Flunt可以輕鬆地與知名框架和庫(如Entity Framework和ASP.NET Core)連接,使在現有專案中新增驗證邏輯變得簡單。

可測試性: Flunt通過提供應用程式程式碼與驗證邏輯之間的明確分工,促進測試驅動開發(TDD),使得驗證規則的單元測試變得簡單。

開源和繁榮的社群: Flunt由一群開發者積極維護,是開源的。 這保證了框架的持續維護、改進和支援。

Getting Started with Flunt C

在C#專案中設定Flunt

Notifications和Validation命名空間是Flunt基本類庫的一部分,應該在您的C#專案中預設可用。 Flunt通過提供一個靈活的介面來定義和應用驗證規則,加速C#程式的驗證。 其對更清晰程式碼、增強可讀性和徹底錯誤處理的支持,使驗證使用者輸入、域物件和API請求變得更簡單。

在Windows主控台和Forms中實現Flunt

Flunt由許多C#應用程式型別實現,包括Windows主控台、Web應用程式和Windows Forms (WinForms)。 儘管每個框架有不同的實現,但一般概念始終相同。

Flunt C#(它是如何為開發人員工作的):圖1 - 使用Visual Studio套件管理器搜尋Flunt並安裝它

Flunt C#範例

一旦安裝完畢,您可以使用以下程式碼Flunt。 這是一個簡單的範例,向您展示如何使用Flunt來構建驗證規則:

using System;
using Flunt.Validations;

public class Program
{
    static void Main(string[] args)
    {
        var person = new Person { Name = "Jack", Age = -25 };
        var contract = new PersonContract(person);

        // Perform validation checks
        if (contract.IsValid)
        {
            Console.WriteLine("Person is valid!");
        }
        else
        {
            Console.WriteLine("Validation failed:");
            foreach (var notification in contract.Notifications)
            {
                Console.WriteLine($"- {notification.Key}: {notification.Message}");
            }
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class PersonContract : Contract<Person>
{
    public PersonContract(Person person)
    {
        // Ensure the correct format of the object
        Requires()
            .IsNotNull(person, nameof(person))
            .IsNotEmpty(person.Name, nameof(person.Name), "Name is required")
            .IsGreaterThan(person.Age, 0, nameof(person.Age), "Age must be a positive number");
    }
}
using System;
using Flunt.Validations;

public class Program
{
    static void Main(string[] args)
    {
        var person = new Person { Name = "Jack", Age = -25 };
        var contract = new PersonContract(person);

        // Perform validation checks
        if (contract.IsValid)
        {
            Console.WriteLine("Person is valid!");
        }
        else
        {
            Console.WriteLine("Validation failed:");
            foreach (var notification in contract.Notifications)
            {
                Console.WriteLine($"- {notification.Key}: {notification.Message}");
            }
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class PersonContract : Contract<Person>
{
    public PersonContract(Person person)
    {
        // Ensure the correct format of the object
        Requires()
            .IsNotNull(person, nameof(person))
            .IsNotEmpty(person.Name, nameof(person.Name), "Name is required")
            .IsGreaterThan(person.Age, 0, nameof(person.Age), "Age must be a positive number");
    }
}
Imports System
Imports Flunt.Validations

Public Class Program
	Shared Sub Main(ByVal args() As String)
		Dim person As New Person With {
			.Name = "Jack",
			.Age = -25
		}
		Dim contract = New PersonContract(person)

		' Perform validation checks
		If contract.IsValid Then
			Console.WriteLine("Person is valid!")
		Else
			Console.WriteLine("Validation failed:")
			For Each notification In contract.Notifications
				Console.WriteLine($"- {notification.Key}: {notification.Message}")
			Next notification
		End If
	End Sub
End Class

Public Class Person
	Public Property Name() As String
	Public Property Age() As Integer
End Class

Public Class PersonContract
	Inherits Contract(Of Person)

	Public Sub New(ByVal person As Person)
		' Ensure the correct format of the object
		Requires().IsNotNull(person, NameOf(person)).IsNotEmpty(person.Name, NameOf(person.Name), "Name is required").IsGreaterThan(person.Age, 0, NameOf(person.Age), "Age must be a positive number")
	End Sub
End Class
$vbLabelText   $csharpLabel

Person 類: 表示具有Age屬性的實體。

PersonContract 此類派生自Flunt的基本概念Contract<t>。 使用Person物件並提供驗證規則。 Requires提供了一種可鏈式方法來定義多個驗證。 驗證通過像IsGreaterThan這樣的方法來執行。 每個驗證規則都有一個關聯的自定義錯誤訊息。

驗證: 類似一個Person物件的實例。 驗證結果由契約的IsValid屬性顯示。 根據驗證結果,成功或失敗的通知以及具體的錯誤訊息會顯示。

Flunt操作

對於C#應用程式中的驗證和通知處理,Flunt提供了許多操作,例如:

建立驗證規則: 使用流暢介面為如必填字段、資料型別、值範圍、最大長度和最小長度等屬性建立驗證規則。

執行驗證: 為了保證資料完整性並遵循業務邏輯,將物件與預定義規則進行驗證。

管理驗證錯誤: 記錄並記錄驗證錯誤作為警報,並通過向使用者提供錯誤訊息或記錄錯誤以進行故障排除來有禮貌地回應它們。

自定義驗證邏輯: 使用獨特的驗證規則來擴展Flunt,以應對複雜的驗證情況或特定的領域需求。

與框架整合: 為了改善現有應用程式中的驗證功能,Flunt可以無縫整合到許多知名的.NET框架和程式庫中,包括Entity Framework,ASP.NET Core等。

Flunt與IronPDF的整合

通過整合Flunt和IronPDF,開發者可以利用這兩項技術的優勢,更快地在C#應用程式中驗證業務邏輯和生成文件。 開發者可以使用IronPDF在驗證輸入資料後建立PDF文件,使應用程式更加可靠和使用者友好。

安裝IronPDF

  • 啟動Visual Studio專案。
  • 選擇"工具">"NuGet攜帶管理員">"攜帶管理員控制台"。
  • 在套件管理器控制台中輸入此命令:
Install-Package IronPdf
  • 作為替代,您可以使用解決方案的NuGet套件管理器來安裝IronPDF和其他必要的NuGet套件。
  • 遍歷並從搜尋結果中選擇IronPDF套件後,點擊"安裝"按鈕。 由Visual Studio負責安裝和下載。

Flunt C# (How It Works For Developers): Figure 2 - Install IronPDF using the Manage NuGet Package for Solution by searching IronPDF in the search bar of NuGet Package Manager, then select the project and click on the Install button.

  • NuGet將負責安裝IronPDF套件及您專案所需的任何依賴項。
  • 安裝完成後,IronPDF在您的專案中可用。

通過NuGet網站安裝

要了解IronPDF的功能、相容性及其他下載選擇,請查看其在NuGet網站上的NuGet包詳細資訊頁面

使用DLL安裝

作為替代,您可以使用IronPDF的DLL檔案直接將其包含到您的專案中。 要獲取包含DLL的ZIP檔案,請存取以下IronPDF ZIP下載頁面。 在解壓縮DLL後,將其包括到您的專案中。

實施邏輯

讓我們建立一個使用IronPDF進行PDF建立及使用Flunt進行資料驗證的基本C#應用程式。 在這個範例中,我們將使用Flunt驗證註冊表單的使用者輸入,並使用IronPDF建立一個包含經核實使用者資料摘要的PDF文件。

  1. 人員類: 定義了一個Person類,具有名稱和年齡的屬性。 我們在構造函式中使用Flunt的流暢介面,以將Person資料與預定義的驗證規則相驗證。
  2. 生成Pdf: 定義了一個名為RenderHtmlAsPdf的方法,接受一個User物件作為輸入。 此功能通過使用IronPDF的HtmlToPdf類將表示使用者註冊摘要的HTML文字呈現為PDF文件。
  3. 主要方法: 使用樣本的Person資料,我們在Main方法中構建一個User類的實例。 接下來,我們使用Flunt的IsValid屬性來確定Person資料是否合法。 如果資料正確,我們調用IronPDF方法以建立PDF文件。 如果不是,驗證問題會顯示在主控台上。

通過結合IronPDF進行PDF生成和Flunt進行資料驗證,我們在C#應用程式中開發了一個快速的使用者輸入評估和PDF文件生成流程。 此方法確保資料完整性,生成專業質量的文件,並促進寫出清晰、易讀和易於維護的程式碼。 如需閱讀更多IronPDF的功能,請參閱文件頁面。 下面是範例程式碼片段。

using IronPdf;
using System;
using System.Linq;
using System.Text;
using Flunt.Validations;

namespace ConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // StringBuilder for HTML content
            StringBuilder sb = new StringBuilder();
            var person = new Person { Name = "Jack", Age = -25 };
            var contract = new PersonContract(person);

            if (contract.IsValid)
            {
                Console.WriteLine("Person is valid!");
                sb.Append("<p>Person is valid!</p>");
            }
            else
            {
                sb.Append("<p>Validation failed: </p>");
                foreach (var notification in contract.Notifications)
                {
                    sb.Append($"- {notification.Key}: {notification.Message}<br>");
                }
            }

            var renderer = new HtmlToPdf();
            // Set HTML content for the page
            var pdfDocument = renderer.RenderHtmlAsPdf(sb.ToString());
            // Save the document
            pdfDocument.SaveAs("output.pdf");
            // Dispose the renderer object
            renderer.Dispose();
            // Display a message
            Console.WriteLine("Report generated successfully!");
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class PersonContract : Contract<Person>
    {
        public PersonContract(Person person)
        {
            Requires()
                .IsNotNull(person, nameof(person))
                .IsNotEmpty(person.Name, nameof(person.Name), "Name is required")
                .IsGreaterThan(person.Age, 0, nameof(person.Age), "Age must be a positive number");
        }
    }
}
using IronPdf;
using System;
using System.Linq;
using System.Text;
using Flunt.Validations;

namespace ConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // StringBuilder for HTML content
            StringBuilder sb = new StringBuilder();
            var person = new Person { Name = "Jack", Age = -25 };
            var contract = new PersonContract(person);

            if (contract.IsValid)
            {
                Console.WriteLine("Person is valid!");
                sb.Append("<p>Person is valid!</p>");
            }
            else
            {
                sb.Append("<p>Validation failed: </p>");
                foreach (var notification in contract.Notifications)
                {
                    sb.Append($"- {notification.Key}: {notification.Message}<br>");
                }
            }

            var renderer = new HtmlToPdf();
            // Set HTML content for the page
            var pdfDocument = renderer.RenderHtmlAsPdf(sb.ToString());
            // Save the document
            pdfDocument.SaveAs("output.pdf");
            // Dispose the renderer object
            renderer.Dispose();
            // Display a message
            Console.WriteLine("Report generated successfully!");
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class PersonContract : Contract<Person>
    {
        public PersonContract(Person person)
        {
            Requires()
                .IsNotNull(person, nameof(person))
                .IsNotEmpty(person.Name, nameof(person.Name), "Name is required")
                .IsGreaterThan(person.Age, 0, nameof(person.Age), "Age must be a positive number");
        }
    }
}
Imports IronPdf
Imports System
Imports System.Linq
Imports System.Text
Imports Flunt.Validations

Namespace ConsoleApp
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' StringBuilder for HTML content
			Dim sb As New StringBuilder()
			Dim person As New Person With {
				.Name = "Jack",
				.Age = -25
			}
			Dim contract = New PersonContract(person)

			If contract.IsValid Then
				Console.WriteLine("Person is valid!")
				sb.Append("<p>Person is valid!</p>")
			Else
				sb.Append("<p>Validation failed: </p>")
				For Each notification In contract.Notifications
					sb.Append($"- {notification.Key}: {notification.Message}<br>")
				Next notification
			End If

			Dim renderer = New HtmlToPdf()
			' Set HTML content for the page
			Dim pdfDocument = renderer.RenderHtmlAsPdf(sb.ToString())
			' Save the document
			pdfDocument.SaveAs("output.pdf")
			' Dispose the renderer object
			renderer.Dispose()
			' Display a message
			Console.WriteLine("Report generated successfully!")
		End Sub
	End Class

	Public Class Person
		Public Property Name() As String
		Public Property Age() As Integer
	End Class

	Public Class PersonContract
		Inherits Contract(Of Person)

		Public Sub New(ByVal person As Person)
			Requires().IsNotNull(person, NameOf(person)).IsNotEmpty(person.Name, NameOf(person.Name), "Name is required").IsGreaterThan(person.Age, 0, NameOf(person.Age), "Age must be a positive number")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

以下是上述程式碼的執行輸出:

Flunt C#(它是如何為開發人員工作的):圖3 - 利用Flunt和IronPDF的上述程式碼範例輸出

結論

IronPDF和Flunt是兩個強大的C#程式庫,能夠一起工作以簡化文件建立和資料驗證的工作流程。 憑藉IronPDF的高級PDF生產特性和Flunt的強大驗證功能,開發者可以為各種應用程式構建可靠、高效和高品質的解決方案。 Flunt和IronPDF為開發者提供了建立滿足使用者和利益相關者需求的高品質軟體所需的工具,無論是開發桌面應用程式、Web應用程式,還是基於雲的解決方案。

軟體支援一年,永久授權和程式庫升級均包含在$999 Lite套件中。 IronPDF提供IronPDF的免費授權詳細資訊,以獲取有關費用和授權需求的進一步資訊。 如需了解更多有關Iron Software程式庫的資訊,請存取Iron Software官方網站。

常見問題

Flunt C#如何改善我的應用程式中的驗證流程?

Flunt C#通過提供一個流暢的介面來增強驗證流程,允許開發人員以可讀和易於維護的方式建立複雜的驗證規則。它支持可鏈式驗證場景,並與ASP.NET Core和Entity Framework等框架無縫整合。

設置Flunt C#進行驗證的步驟有哪些?

要設置Flunt C#進行驗證,您需要建立一個新的C#專案,從NuGet安裝Flunt套件,導入必要的命名空間,並繼承基類來構建驗證規則和邏輯。

IronPDF如何與Flunt C#整合來增強文件建立?

IronPDF可以與Flunt C#一同使用,以在生成PDF之前驗證輸入資料。這確保只有有效的資料被使用,從而提高生成文件的可靠性。驗證後,IronPDF允許您以程式化的方式建立專業質量的PDF文件。

在測試驅動開發中使用Flunt C#的好處是什麼?

Flunt C#支持測試驅動開發,通過實現驗證邏輯和應用程式程式碼的清晰分離。這種分離允許開發人員輕鬆地編寫和運行驗證規則的單元測試,確保應用程式的正確性和穩健性。

Flunt C#可以處理自定義驗證規則嗎?

是的,Flunt C#允許開發人員定義自定義驗證規則,以滿足特定的應用程式需求。這種靈活性有助於解決內建驗證器未涵蓋的獨特驗證場景。

在C#專案中安裝IronPDF的過程是什麼?

要安裝IronPDF,請打開您的Visual Studio專案,導航到“工具”>“NuGet套件管理員”>“套件管理員控制台”,並執行命令Install-Package IronPdf。或者,您可以使用解決方案的NuGet套件管理器將IronPDF新增到您的專案中。

Flunt C#中的通知系統扮演什麼角色?

Flunt C#中的通知系統旨在捕獲和報告驗證錯誤。它允許開發人員收集錯誤消息和反饋,這些資訊可以用來通知使用者或應用程式的其他組件有關驗證問題。

Flunt C#適合用於開源專案嗎?

是的,Flunt C#是開源的,由一個開發者社群維護。這使其成為開源專案的可靠選擇,並提供持續的更新和支持。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話