.NET HELP

LiteDB .NET (How It Works For Developers)

Published August 13, 2024
Share:

Introduction

LiteDB is a simple, fast, and lightweight embedded .NET document database. LiteDB .NET was inspired by the MongoDB database and its API is very similar to MongoDB’s official .NET API. LiteDB is a serverless database that works well for small projects and mobile applications.

This article will provide you with accurate instructions on utilizing the capabilities of LiteDB in your projects. We also introduce the use of IronPDF, a .NET library made by IronSoftware, for generating and manipulating PDF's and how you can employ it to output a LiteDB database contents as a PDF for viewing and sharing.

Key Features of LiteDB

  1. Embedded Database: No need for a separate server. LiteDB runs within your application's process.

  2. Single Data File: You can store in a single file database, all of your data, simplifying deployment and backup.

  3. BSON Format: Uses BSON format for storage, ensuring fast read and write operations.

  4. LINQ Support: Fully supports LINQ for querying, making it intuitive for .NET developers.

  5. ACID Transactions: Ensures data integrity with support for ACID transactions.

  6. Cross-Platform: Works on Windows, Linux, and macOS.

Setting Up LiteDB in .NET Projects

Open your project in Visual Studio. Then, in the Solution Explorer, right-click on your project and choose "Manage NuGet Packages." Search for LiteDB and install it to incorporate this database solution into your project effortlessly.

Alternatively, you can install it by using Package Manager Console. To install LiteDB in the NuGet Package Manager Console, use the following command:

Install-Package LiteDB
Install-Package LiteDB
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Getting Started with LiteDB

Once installed, you can start using LiteDB in your application. Let's go through some examples to illustrate its usage.

Example 1: Creating and Inserting Data

First, let's create a simple Product class to represent our data:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Next, we'll create a database and insert some products:

using LiteDB;
using System;
class Program
{
   static void Main()
{
    using (var db = new LiteDatabase(@"MyData.db"))
    {
        var products = db.GetCollection<Product>("products");
        var productList = new[]
        {
            new Product { Id = 201, Name = "Apple", Price = 0.99m },
            new Product { Id = 202, Name = "Banana", Price = 0.59m },
            new Product { Id = 203, Name = "Orange", Price = 0.79m },
            new Product { Id = 204, Name = "Grape", Price = 2.99m },
            new Product { Id = 205, Name = "Watermelon", Price = 4.99m }
        };
        foreach (var product in productList)
        {
            products.Insert(product);
        }
        Console.WriteLine("Product inserted successfully.");
    }
}
}
using LiteDB;
using System;
class Program
{
   static void Main()
{
    using (var db = new LiteDatabase(@"MyData.db"))
    {
        var products = db.GetCollection<Product>("products");
        var productList = new[]
        {
            new Product { Id = 201, Name = "Apple", Price = 0.99m },
            new Product { Id = 202, Name = "Banana", Price = 0.59m },
            new Product { Id = 203, Name = "Orange", Price = 0.79m },
            new Product { Id = 204, Name = "Grape", Price = 2.99m },
            new Product { Id = 205, Name = "Watermelon", Price = 4.99m }
        };
        foreach (var product in productList)
        {
            products.Insert(product);
        }
        Console.WriteLine("Product inserted successfully.");
    }
}
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Code Description

The code initializes a connection to a LiteDB database named "MyData.db" and retrieves a collection called "products". It then creates an array of Product objects with various properties, such as ID, Name, and Price. Each product in the array is inserted into the "products" collection within the database. After successfully inserting all products, it prints a confirmation message to the console.

Output is as:

LiteDB .NET (How It Works For Developers): Figure 1 - Console output from the previous code

Example: Streamlining User Data Management

Imagine you're developing a mobile application that manages user accounts. Each user has a profile containing their name, email address, preferences (stored as a JSON object), and a list of favorite items. Here's how LiteDb.NET can simplify your data storage:

This code defines a User class to represent user data and a UserManager class to manage user operations in a LiteDb.NET database

using LiteDB;
public class User
{
    [BsonId]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Dictionary<string, string> Preferences { get; set; }
    public List<string> FavoriteItems { get; set; }
} 
public class UserManager
{
    private readonly LiteDatabase db;
    public UserManager(string connectionString)
    {
       db = new LiteDatabase(connectionString);
    }
    public void SaveUser(User user)
    {
        var collection = db.GetCollection<User>("users");
        collection.Insert(user);
    }
    public User GetUser(string userId)
    {
        var collection = db.GetCollection<User>("users");
        return collection.FindById(userId);
    }
    public void UpdateUser(User user)
    {
        var collection = db.GetCollection<User>("users");
        collection.Update(user);
    }
    public void DeleteUser(string userId)
    {
        var collection = db.GetCollection<User>("users");
        collection.Delete(userId);
    }
}
using LiteDB;
public class User
{
    [BsonId]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Dictionary<string, string> Preferences { get; set; }
    public List<string> FavoriteItems { get; set; }
} 
public class UserManager
{
    private readonly LiteDatabase db;
    public UserManager(string connectionString)
    {
       db = new LiteDatabase(connectionString);
    }
    public void SaveUser(User user)
    {
        var collection = db.GetCollection<User>("users");
        collection.Insert(user);
    }
    public User GetUser(string userId)
    {
        var collection = db.GetCollection<User>("users");
        return collection.FindById(userId);
    }
    public void UpdateUser(User user)
    {
        var collection = db.GetCollection<User>("users");
        collection.Update(user);
    }
    public void DeleteUser(string userId)
    {
        var collection = db.GetCollection<User>("users");
        collection.Delete(userId);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

This implementation effectively leverages LiteDb.NET's capabilities for user data management. The User class stores user information, while the UserManager class provides methods to save, retrieve, update, and delete users within the database.

LiteDB, embedded NoSQL database for .NET

LiteDB is perfect for small to medium-sized applications without user concurrency needs. For instance, it's great for a personal console app where you want to store data simply and swiftly. Developed solely in C#, it's lightweight, takes up less than 450KB, and doesn't rely on external dependencies.

Some more points, which are listed on theirGitHub page:

  1. Serverless NoSQL Document Store
  2. Simple API, similar to MongoDB
  3. Thread-safe
  4. Written entirely in C#, LiteDB is compatible with .NET 4.5, NETStandard 1.3/2.0, packaged into a single DLL file that occupies less than 450KB.
  5. ACID with full transaction support
  6. Data recovery after write failure (WAL log file)
  7. Datafile encryption using DES (AES) cryptography
  8. You can easily map your Plain Old CLR Objects (POCO) classes to BsonDocument using either attributes or the fluent mapper API provided by LiteDB.
  9. Store files and stream data (like GridFS in MongoDB)

    1. Single data file storage (like SQLite)
  10. Index document fields for fast search

    1. LINQ support for queries
  11. SQL-Like commands to access/transform data

    1. LiteDB Studio – Nice UI for data access
  12. Open source and free for everyone – including commercial use

Introduction to IronPDF: A C# PDF Library

LiteDB .NET (How It Works For Developers): Figure 2 - IronPDF webpage

IronPDF, a premier C# PDF library, facilitates seamless creation,editing, and manipulation of PDFs in .NET projects. It offers a comprehensive API for tasks like HTML to PDF conversion, dynamic PDF generation, and data extraction. Utilizing a .NET Chromium engine, ensures accurate rendering of HTML into PDF files, catering to diverse project needs across .NET Core, .NET Standard, and .NET Framework. IronPDF guarantees precision, simplicity, and efficiency in PDF generation from HTML content with support for web, desktop, and console applications,

Installing IronPDF Library

To initiate IronPDF in your project, install the library via the NuGet Package Manager within Visual Studio. Then simply follow these straightforward steps:

  1. Open Visual Studio and navigate to Solution Explorer.
  2. Right-click on Dependencies and select the "Manage NuGet Packages" option.
  3. Choose the "Browse" tab and search for "IronPdf."
  4. Select the IronPDF and click "Install."

Alternatively, within Visual Studio, you can utilize the Package Manager Console to install the library by executing the following command:

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

Example Usage of IronPDF with LiteDB

Here's a straightforward code example illustrating the usage of IronPDF to generate a PDF from HTML content, employing the 'using' statement to ensure proper resource disposal. Here we combine the functionality of LiteDB and IronPDF by showing how you can output the data within a LiteDB as a PDF for viewing purposes:

using DemoLiteDB1;
using LiteDB;
using System.Text;
class Program
{
    static void Main()
    {
        using (var db = new LiteDatabase(@"MyData.db"))
        {
            var products = db.GetCollection<Product>("products");
            var productList = new[]
            {
                new Product { Id = 101, Name = "Apple", Price = 0.99m },
                new Product { Id = 102, Name = "Banana", Price = 0.59m },
                new Product { Id = 103, Name = "Orange", Price = 0.79m },
                new Product { Id = 104, Name = "Grape", Price = 2.99m },
                new Product { Id = 105, Name = "Watermelon", Price = 4.99m }
            };
            foreach (var product in productList)
            {
                products.Insert(product);
            }
            Console.WriteLine("Product inserted successfully.");
            // Fetch all products from the database
            var allProducts = GetAllProducts(db);
            // Generate HTML content from the product list
            string htmlContent = GenerateHtml(allProducts);
            // Generate the PDF from the HTML content
            GeneratePDF(htmlContent);
            Console.WriteLine("PDF generated successfully.");
        }
    }
    public static List<Product> GetAllProducts(LiteDatabase db)
    {
        var products = db.GetCollection<Product>("products");
        return products.FindAll().ToList();
    }
    public static void GeneratePDF(string data)
    {
        IronPdf.License.LicenseKey = "Your-License-Key";
        Console.WriteLine("PDF Generating Started...");
        var renderer = new ChromePdfRenderer();
        Console.WriteLine("PDF Processing ....");
        var pdf = renderer.RenderHtmlAsPdf(data);
        string filePath = "Data.pdf";
        pdf.SaveAs(filePath);
        Console.WriteLine($"PDF Generation Completed, File Saved as {filePath}");
    }
    public static string GenerateHtml(List<Product> products)
    {
        StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.Append("<html><head><style>table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: left; }</style></head><body>");
        htmlBuilder.Append("<h1>Product List</h1>");
        htmlBuilder.Append("<table><tr><th>ID</th><th>Name</th><th>Price</th></tr>");
        foreach (var product in products)
        {
            htmlBuilder.Append($"<tr><td>{product.Id}</td><td>{product.Name}</td><td>{product.Price:C}</td></tr>");
        }
        htmlBuilder.Append("</table></body></html>");
        return htmlBuilder.ToString();
    }
}
using DemoLiteDB1;
using LiteDB;
using System.Text;
class Program
{
    static void Main()
    {
        using (var db = new LiteDatabase(@"MyData.db"))
        {
            var products = db.GetCollection<Product>("products");
            var productList = new[]
            {
                new Product { Id = 101, Name = "Apple", Price = 0.99m },
                new Product { Id = 102, Name = "Banana", Price = 0.59m },
                new Product { Id = 103, Name = "Orange", Price = 0.79m },
                new Product { Id = 104, Name = "Grape", Price = 2.99m },
                new Product { Id = 105, Name = "Watermelon", Price = 4.99m }
            };
            foreach (var product in productList)
            {
                products.Insert(product);
            }
            Console.WriteLine("Product inserted successfully.");
            // Fetch all products from the database
            var allProducts = GetAllProducts(db);
            // Generate HTML content from the product list
            string htmlContent = GenerateHtml(allProducts);
            // Generate the PDF from the HTML content
            GeneratePDF(htmlContent);
            Console.WriteLine("PDF generated successfully.");
        }
    }
    public static List<Product> GetAllProducts(LiteDatabase db)
    {
        var products = db.GetCollection<Product>("products");
        return products.FindAll().ToList();
    }
    public static void GeneratePDF(string data)
    {
        IronPdf.License.LicenseKey = "Your-License-Key";
        Console.WriteLine("PDF Generating Started...");
        var renderer = new ChromePdfRenderer();
        Console.WriteLine("PDF Processing ....");
        var pdf = renderer.RenderHtmlAsPdf(data);
        string filePath = "Data.pdf";
        pdf.SaveAs(filePath);
        Console.WriteLine($"PDF Generation Completed, File Saved as {filePath}");
    }
    public static string GenerateHtml(List<Product> products)
    {
        StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.Append("<html><head><style>table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: left; }</style></head><body>");
        htmlBuilder.Append("<h1>Product List</h1>");
        htmlBuilder.Append("<table><tr><th>ID</th><th>Name</th><th>Price</th></tr>");
        foreach (var product in products)
        {
            htmlBuilder.Append($"<tr><td>{product.Id}</td><td>{product.Name}</td><td>{product.Price:C}</td></tr>");
        }
        htmlBuilder.Append("</table></body></html>");
        return htmlBuilder.ToString();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

The code connects to a LiteDB database, adds a list of products, retrieves all products, and generates an HTML representation of the product list. This HTML content is then used to create a PDF file using the IronPDF library. The process includes methods for adding products, fetching them, converting the product list to HTML, and generating the PDF.

Output

LiteDB .NET (How It Works For Developers): Figure 3 - Console output from the previous code

PDF File Output

LiteDB .NET (How It Works For Developers): Figure 4 - Outputed PDF from the previous code

Conclusion

LiteDB presents C# developers with a lightweight, serverless embedded document database solution, ideal for small projects and mobile applications, boasting features like MongoDB-inspired API, embedded databases, and cross-platform compatibility.

Simultaneously, IronPDF emerges as a premier C# PDF library, simplifying PDF generation and manipulation within .NET projects with its HTML to PDF conversion and NuGet integration. Both LiteDB and IronPDF offer valuable tools for developers, with LiteDB excelling in database management and IronPDF in PDF handling.

IronPDF provides a free trial to unlock its full potential in PDF generation and manipulation.

< PREVIOUS
RestEase C# (How It Works For Developers)
NEXT >
FireSharp C# (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >