Skip to footer content
.NET HELP

Flunt C# (How It Works For Developers)

In the current software development environment, producing high-caliber documentation and guaranteeing data integrity are essential tasks. In this post, we'll look at how to combine the potent C# libraries, Flunt C#, and IronPDF to improve workflows for data validation and document creation. Developers can construct effective and dependable solutions for a variety of software applications by utilizing IronPDF's sophisticated PDF production features and Flunt's strong validation capabilities.

How to use Flunt in C#

  1. Create a new C# console project.
  2. Install the Flunt package from NuGet.
  3. Import the namespace and inherit the class.
  4. Add the validation to the data model.
  5. Perform validation checks and display the result.

Understanding of Flunt C#

The versatile and lightweight .NET framework, Flunt, was created to facilitate the development of fluent validation and notification patterns in C# applications. Code becomes more legible and maintained when developers use Flunt to construct validation rules and business logic in a fluid and expressive way. With Flunt's extensive range of integrated validation techniques and extensions, developers can easily validate intricate data structures like objects and collections.

Moreover, Flunt is a useful tool for boosting the dependability and robustness of .NET library applications since it easily integrates with current codebases and frameworks. All in all, Flunt encourages a declarative approach to validation and error handling, enabling developers to write cleaner, more robust code.

Features of Flunt C#

Fluent Interface: Flunt offers a legible and succinct interface for building validation rules, which simplifies the expression of complex validation logic.

Chainable Validation: Chainable validation scenarios can be created with little code by connecting validation rules naturally.

Integrated Validators: Flunt comes with several built-in validators for frequently used data types, including dates, integers, strings, and collections. Fluent syntax allows for the easy application of these validators to properties.

Custom Validation Rules: By expanding the Flunt framework, developers can add custom validation rules that allow validation logic adapted to particular domain requirements.

Notification System: To report validation issues and gather error messages, Flunt offers a notification system. This makes it simple for developers to inform users or other application components of validation failures.

Integration with Frameworks: Flunt easily connects with well-known frameworks and libraries, including Entity Framework and ASP.NET Core, making it simple to add validation logic to already-existing projects.

Testability: Flunt facilitates test-driven development (TDD) by offering a distinct division between application code and validation logic, making it simple to unit test validation rules.

Open Source and Thriving Community: A group of developers actively maintains Flunt, making it open-source. This guarantees continued maintenance, enhancements, and support for the framework.

Getting Started with Flunt C#

Setting Up Flunt in C# Projects

The Notifications and Validation namespace are part of the Flunt Base Class Library and should be accessible by default in your C# project. Flunt accelerates validation for C# programs by providing a flexible interface for defining and applying validation rules. Its support for cleaner code, enhanced readability, and thorough error handling makes validating user input, domain objects, and API requests easier.

Implementing Flunt in Windows Console and Forms

Flunt is implemented by numerous C# application types, including Windows Console, web applications, and Windows Forms (WinForms). Although each framework has a different implementation, the general concept is always the same.

Flunt C# (How It Works For Developers): Figure 1 - Search for Flunt with the Visual Studio Package Manager and install it

Flunt C# Example

You can use the following code Flunt as soon as it's installed. This is a simple example that shows you how to use Flunt to construct validation rules:

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 Class: Represents an entity with Name and Age properties.

PersonContract: This class derives from Flunt's fundamental concept of Contract<T>. Using the Requires method, the constructor takes a Person object and provides validation rules. Requires offers a chainable method for defining multiple validations. Validations are carried out by methods like IsNotNull, IsNotEmpty, IsGreaterThan. Each validation rule has an associated custom error message.

Validation: Similar to a FluentValidation example, this creates an instance of a PersonContract and a Person object. The validation results are shown by the contract's IsValid attribute. Notifications of success or failure, as well as specific error messages, are displayed based on the validation outcome.

Flunt Operations

For validation and notification handling in C# applications, Flunt offers many operations, such as:

Creating Validation Rules: To create validation rules for attributes like mandatory fields, data types, value ranges, maximum length, and minimum length, use the fluent interface.

Executing Validation: To guarantee data integrity and adherence to business logic, validate objects against predefined rules.

Managing Validation Mistakes: Note and record validation mistakes as alerts and respond to them politely by giving users error messages or recording errors for troubleshooting.

Custom Validation Logic: Use unique validation rules to extend Flunt in response to intricate validation circumstances or particular domain requirements.

Integration with Frameworks: To improve validation capabilities in current applications, Flunt may be seamlessly integrated with many well-known .NET frameworks and libraries, including Entity Framework, ASP.NET Core, and more.

Integrating Flunt with IronPDF

Developers can harness the strengths of both technologies to expedite business logic validation and document creation in C# applications by integrating Flunt with IronPDF. Applications can be made more dependable and user-friendly by developers by using IronPDF to create PDF documents after validating input data with Flunt.

Install IronPDF

  • Launch the Visual Studio project.
  • Select "Tools" > "NuGet Package Manager" > "Package Manager Console".
  • Input this command into the Package Manager Console:
Install-Package IronPdf
  • As an alternative, you can use the NuGet Package Manager for Solutions to install IronPDF and other necessary NuGet Packages.
  • Click the "Install" button after exploring and choosing the IronPDF package from the search results. The installation and download will be handled by 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.

  • Installing the IronPDF package and any dependencies needed for your project will be handled by NuGet.
  • After installation, IronPDF is available for use in your project.

Install Through the NuGet Website

To find out more about IronPDF's features, compatibility, and other download choices, see its NuGet package details page on the NuGet website.

Utilize DLL to Install

As an alternative, you can utilize IronPDF's DLL file to include it straight into your project. To obtain the ZIP file containing the DLL, visit the following IronPDF ZIP download page. Once the DLL has been unzipped, include it in your project.

Implementing Logic

Let's create a basic C# application that uses IronPDF for PDF creation and Flunt for data validation. In this example, we will use Flunt to validate user input for a registration form, and IronPDF to create a PDF document with a summary of the user data that has been verified.

  1. Person Class: A Person class with attributes for name and age is defined. We validate the Person data against predefined validation rules by using Flunt's fluent interface in the constructor.
  2. Generate Pdf: A method called RenderHtmlAsPdf is defined, and it accepts a User object as input. This function renders the HTML text representing the user registration summary into a PDF document by using IronPDF's HtmlToPdf class.
  3. Main Method: Using sample Person data, we build an instance of the User class in the Main method. Next, we use Flunt's IsValid attribute to determine whether the Person data is legitimate. To create the PDF document, we invoke the IronPdf method if the data is correct. If not, the validation problems are shown on the console.

We have developed a fast workflow for evaluating user input and generating PDF documents in a C# application by combining IronPDF for PDF generation with Flunt for data validation. This method ensures data integrity, generates professional-quality documents, and encourages the writing of clear, readable, and maintainable code. To read more about IronPDF's capabilities, refer to the documentation page. Below is the sample code snippet.

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

Below is the execution output from the above code:

Flunt C# (How It Works For Developers): Figure 3 - Example output from the code above utilizing both Flunt and IronPDF

Conclusion

IronPDF and Flunt are two strong C# libraries that work well together to streamline workflows for document creation and data validation. With IronPDF's sophisticated PDF production features and Flunt's strong validation capabilities, developers can construct dependable, effective, and high-caliber solutions for a variety of applications. Flunt and IronPDF equip developers with the tools necessary to create high-quality software that meets the needs of users and stakeholders, whether they are developing desktop apps, web applications, or cloud-based solutions.

A year of software support, a permanent license, and a library upgrade are all included in the $749 Lite bundle. IronPDF provides free licensing details of IronPDF for further details regarding cost and license requirements. For additional information about the Iron Software libraries, visit the Iron Software official website.

Frequently Asked Questions

What is the versatile and lightweight .NET framework for fluent validation?

Flunt C# is a versatile and lightweight .NET framework designed to facilitate the development of fluent validation and notification patterns in C# applications.

How do I install the fluent validation package in a C# project?

To install Flunt in a C# project, create a new C# console project, install the Flunt package from NuGet, import the namespace, and inherit the class to add validation to your data model.

What are the main features of the .NET framework designed for validation?

Flunt C# offers a fluent interface for building validation rules, chainable validation scenarios, integrated validators, custom validation rules, a notification system, easy integration with frameworks, testability, and is open source with a thriving community.

How does the validation framework integrate with existing frameworks?

Flunt integrates seamlessly with well-known frameworks and libraries like Entity Framework and ASP.NET Core, allowing for easy addition of validation logic to existing projects.

Can the validation framework be used for test-driven development?

Yes, Flunt facilitates test-driven development (TDD) by providing a clear separation between application code and validation logic, making it easy to unit test validation rules.

What is the C# library used for creating PDF documents?

IronPDF is a C# library used for creating PDF documents. It can be integrated with Flunt to validate input data before generating PDF documents, enhancing the reliability and user-friendliness of applications.

How can I install the PDF creation library in my C# project?

To install IronPDF, launch your Visual Studio project, go to 'Tools' > 'NuGet Package Manager' > 'Package Manager Console', and input 'Install-Package IronPdf'. Alternatively, use the NuGet Package Manager for Solutions.

What are the benefits of using the validation framework in C# applications?

Flunt improves code legibility and maintainability by allowing developers to construct validation rules and business logic in a fluid and expressive way. It also enhances the reliability and robustness of applications through easy integration with existing codebases.

How does the validation framework handle validation notifications?

Flunt offers a notification system to report validation issues and gather error messages, making it easy for developers to inform users or other application components of validation failures.

Is the .NET framework for validation open source?

Yes, Flunt C# is open source and maintained by a group of developers, ensuring continued maintenance, enhancements, and support for the framework.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.