### Configure BlazorDexie Services Source: https://github.com/simon-kuster/blazordexie/blob/master/README.md Initial setup for the BlazorDexie library. This includes installing the NuGet package, referencing the JavaScript dependency, and registering the service in the application container. ```bash dotnet add package BlazorDexie ``` ```html ``` ```csharp builder.Services.AddBlazorDexie(); ``` -------------------------------- ### Retrieve and Delete Records by Primary Key Source: https://context7.com/simon-kuster/blazordexie/llms.txt Demonstrates how to fetch a single record using Get and remove a record using Delete. Get returns null if the primary key does not exist in the store. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); await db.Friends.Put(new Friend { Id = 1, Name = "Alice", Age = 25 }); await db.Friends.Put(new Friend { Id = 2, Name = "Bob", Age = 30 }); Friend? alice = await db.Friends.Get(1); if (alice != null) { Console.WriteLine($"Found: {alice.Name}, Age: {alice.Age}"); } Friend? notFound = await db.Friends.Get(999); Console.WriteLine(notFound == null ? "Not found" : "Found"); await db.Friends.Delete(1); Friend? deleted = await db.Friends.Get(1); Console.WriteLine(deleted == null ? "Successfully deleted" : "Still exists"); ``` -------------------------------- ### Atomic Transactions in BlazorDexie with C# Source: https://context7.com/simon-kuster/blazordexie/llms.txt Demonstrates how to use transactions to ensure atomicity for multiple database operations. If any operation within the transaction fails, all changes are rolled back, maintaining data consistency. This example shows both a successful transaction and a simulated failed transaction with rollback. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); // Setup initial data await db.Friends.Put(new Friend { Id = 1, Name = "Alice", Age = 25 }); await db.Friends.Put(new Friend { Id = 2, Name = "Bob", Age = 30 }); // Successful transaction try { await db.Transaction("rw", new[] { nameof(FriendDatabase.Friends) }, 60000, async () => { // All operations within this block are atomic var alice = await db.Friends.Get(1) ?? throw new InvalidOperationException(); alice.Age = 26; await db.Friends.Put(alice); var bob = await db.Friends.Get(2) ?? throw new InvalidOperationException(); bob.Age = 31; await db.Friends.Put(bob); }); Console.WriteLine("Transaction completed successfully"); } catch (Exception ex) { Console.WriteLine($"Transaction failed: {ex.Message}"); } // Failed transaction - changes are rolled back try { await db.Transaction("rw", new[] { nameof(FriendDatabase.Friends) }, 60000, async () => { var alice = await db.Friends.Get(1) ?? throw new InvalidOperationException(); alice.Age = 100; // This change will be rolled back await db.Friends.Put(alice); throw new InvalidOperationException("Simulated error"); }); } catch (Exception) { // Alice's age remains 26, not 100 var alice = await db.Friends.Get(1); Console.WriteLine($"Alice's age after rollback: {alice!.Age}"); // Output: Alice's age after rollback: 26 } ``` -------------------------------- ### Retrieving Keys with PrimaryKeys and Keys in C# Source: https://context7.com/simon-kuster/blazordexie/llms.txt Explains how to retrieve only the keys from database records without fetching the entire data. This includes getting all primary keys, filtering keys based on criteria, and retrieving index keys for a specific indexed column. This is useful for optimizing queries where only identifiers or indexed values are needed. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); await db.Friends.BulkPut(new Friend[] { new() { Id = 1, Name = "Alice", Age = 25 }, new() { Id = 2, Name = "Bob", Age = 30 }, new() { Id = 3, Name = "Charlie", Age = 35 } }); // Get all primary keys from the store int[] allPrimaryKeys = await db.Friends.PrimaryKeys(); Console.WriteLine($"All primary keys: {string.Join(", ", allPrimaryKeys)}"); // Output: All primary keys: 1, 2, 3 // Get primary keys from a filtered collection int[] filteredKeys = await db.Friends .Where(nameof(Friend.Age)).Above(25) .PrimaryKeys(); Console.WriteLine($"Keys where age > 25: {string.Join(", ", filteredKeys)}"); // Output: Keys where age > 25: 2, 3 // Get index keys (values of the indexed column) string[] nameKeys = await db.Friends .OrderBy(nameof(Friend.Name)) .Keys(); Console.WriteLine($"Name index keys: {string.Join(", ", nameKeys)}"); // Output: Name index keys: Alice, Bob, Charlie ``` -------------------------------- ### Generic Db Class Usage in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Provides an example of how to use the generic Db class in BlazorDexie, where the generic parameter TConcrete represents the concrete class extending Db. ```csharp public class MyDb : Db {} ``` -------------------------------- ### Database Lifecycle Management Source: https://context7.com/simon-kuster/blazordexie/llms.txt Illustrates best practices for database connection management, including automatic disposal using 'await using' and manual closing of connections to ensure resource cleanup. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); await db.Friends.Put(new Friend { Id = 1, Name = "Alice" }); var db2 = new FriendDatabase(BlazorDexieOptions); try { await db2.Friends.Put(new Friend { Id = 2, Name = "Bob" }); await db2.Close(); } finally { await db2.DisposeAsync(); } ``` -------------------------------- ### BlazorDexie: Building Where Clause Queries in C# Source: https://context7.com/simon-kuster/blazordexie/llms.txt Demonstrates how to construct queries using the `Where` method in BlazorDexie with various comparison operators like IsEqual, Between, Above, Below, StartsWith, and AnyOf/NoneOf. This allows for flexible data filtering based on specific criteria. It requires the BlazorDexie library and a defined FriendDatabase context. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); await db.Friends.BulkPut(new Friend[] { new() { Id = 1, Name = "Alice", Age = 25 }, new() { Id = 2, Name = "Bob", Age = 30 }, new() { Id = 3, Name = "Charlie", Age = 35 }, new() { Id = 4, Name = "Anna", Age = 28 }, new() { Id = 5, Name = "Brian", Age = 22 } }); // IsEqual - exact match var bob = await db.Friends.Where(nameof(Friend.Name)).IsEqual("Bob").ToArray(); Console.WriteLine($"Found: {bob[0].Name}"); // Output: Found: Bob // Between - range query (inclusive min, exclusive max by default) var ageBetween = await db.Friends.Where(nameof(Friend.Age)).Between(25, 35).ToArray(); Console.WriteLine($"Ages 25-34: {string.Join(", ", ageBetween.Select(f => f.Name))}"); // Output: Ages 25-34: Alice, Bob, Anna // Above/Below - comparison queries var above30 = await db.Friends.Where(nameof(Friend.Age)).Above(30).ToArray(); Console.WriteLine($"Over 30: {string.Join(", ", above30.Select(f => f.Name))}"); // Output: Over 30: Charlie // StartsWith - prefix matching var startsWithA = await db.Friends.Where(nameof(Friend.Name)).StartsWith("A").ToArray(); Console.WriteLine($"Names starting with A: {string.Join(", ", startsWithA.Select(f => f.Name))}"); // Output: Names starting with A: Alice, Anna // AnyOf - match any of multiple values var anyOf = await db.Friends.Where(nameof(Friend.Age)).AnyOf(25, 30, 35).ToArray(); Console.WriteLine($"Ages 25, 30, or 35: {string.Join(", ", anyOf.Select(f => f.Name))}"); // Output: Ages 25, 30, or 35: Alice, Bob, Charlie // NoneOf - exclude specific values var noneOf = await db.Friends.Where(nameof(Friend.Age)).NoneOf(25, 30).ToArray(); Console.WriteLine($"Not ages 25 or 30: {string.Join(", ", noneOf.Select(f => f.Name))}"); // Output: Not ages 25 or 30: Charlie, Anna, Brian ``` -------------------------------- ### Integrating Open Iconic with Frameworks Source: https://github.com/simon-kuster/blazordexie/blob/master/BlazorDexie.Demo/wwwroot/css/open-iconic/README.md How to link the necessary stylesheets and implement icons for Bootstrap, Foundation, or standalone usage. ```html ``` -------------------------------- ### Manage Binary Blobs in IndexedDB Source: https://context7.com/simon-kuster/blazordexie/llms.txt Demonstrates how to store, retrieve, and update binary data as blobs, as well as managing ObjectURLs for file handling. It requires the BlazorDexie.ObjUrl service for URL creation and cleanup. ```csharp public class BlobDatabase : Db { public Store BlobData { get; set; } = new(string.Empty); public BlobDatabase(BlazorDexieOptions options) : base("BlobDatabase", 1, Array.Empty(), options) { } } public async Task BlobOperations() { await using var db = new BlobDatabase(BlazorDexieOptions); byte[] imageData = new byte[] { 0x89, 0x50, 0x4E, 0x47 }; Guid blobKey = Guid.NewGuid(); await db.BlobData.AddBlob(imageData, blobKey, "image/png"); byte[] retrievedData = await db.BlobData.GetBlob(blobKey); string objectUrl = await ObjectUrlService.Create(new byte[] { 1, 2, 3 }, "application/octet-stream"); await db.BlobData.AddObjectUrl(objectUrl, Guid.NewGuid()); await ObjectUrlService.Revoke(objectUrl); } ``` -------------------------------- ### Define BlazorDexie Database and Models Source: https://context7.com/simon-kuster/blazordexie/llms.txt Illustrates how to define a database schema and data models for BlazorDexie. It shows extending Db to create stores with primary keys and indexes, and how to use these definitions within a Blazor component. ```csharp using BlazorDexie.Database; using BlazorDexie.Options; // Define your model public class Friend { public int Id { get; set; } public string Name { get; set; } = string.Empty; public int Age { get; set; } public string Email { get; set; } = string.Empty; } // Define your database with stores public class FriendDatabase : Db { // Store with primary key "Id" and indexes on "Name" and "Age" public Store Friends { get; set; } = new( nameof(Friend.Id), // Primary key nameof(Friend.Name), // Index nameof(Friend.Age) // Index ); public FriendDatabase(BlazorDexieOptions options) : base("FriendDatabase", 1, Array.Empty(), options) { } } // Usage in a Blazor component public partial class FriendsPage { [Inject] public BlazorDexieOptions BlazorDexieOptions { get; set; } = null!; protected override async Task OnInitializedAsync() { await using var db = new FriendDatabase(BlazorDexieOptions); // Database ready to use } } ``` -------------------------------- ### BlazorDexie Store Add and Put Operations Source: https://context7.com/simon-kuster/blazordexie/llms.txt Explains and demonstrates the `Add` and `Put` methods for BlazorDexie stores. `Add` inserts a new record and fails if the key exists, while `Put` performs an upsert (insert or update). Both methods return the primary key of the affected record. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); // Add a new friend - throws if Id already exists var friend1 = new Friend { Id = 1, Name = "Alice", Age = 25 }; int key1 = await db.Friends.Add(friend1); Console.WriteLine($"Added friend with key: {key1}"); // Output: Added friend with key: 1 // Put (insert or update) - will update if key exists var friend2 = new Friend { Id = 2, Name = "Bob", Age = 30 }; int key2 = await db.Friends.Put(friend2); Console.WriteLine($"Put friend with key: {key2}"); // Output: Put friend with key: 2 // Update existing record using Put friend2.Age = 31; await db.Friends.Put(friend2); // Updates Bob's age to 31 // Add with explicit key parameter var friend3 = new Friend { Name = "Charlie", Age = 28 }; int key3 = await db.Friends.Add(friend3, 3); ``` -------------------------------- ### Define Initial Database Schema (Version 1) Source: https://github.com/simon-kuster/blazordexie/blob/master/README.md This C# code defines the initial schema for the Dexie database, including the 'Friends' store with its properties. It sets up the database name, version, and initial configuration. ```csharp public class MyDb : Db { public Store Friends { get; set; } = new("++" + nameof(Friend.Id), nameof(Friend.Name), nameof(Friend.Age)); public MyDb(BlazorDexieOptions blazorDexieOptions) : base("TestDb", 1, new IDbVersion[0], blazorDexieOptions) { } } ``` -------------------------------- ### Database Versioning - Version 1 Source: https://github.com/simon-kuster/blazordexie/blob/master/README.md Defines the initial structure of the database with a 'Friends' store. ```APIDOC ## Database Versioning - Version 1 ### Description Defines the initial structure of the database with a 'Friends' store, including its primary and secondary indexes. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```csharp public class MyDb : Db { public Store Friends { get; set; } = new("++" + nameof(Friend.Id), nameof(Friend.Name), nameof(Friend.Age)); public MyDb(BlazorDexieOptions blazorDexieOptions) : base("TestDb", 1, new IDbVersion[0], blazorDexieOptions) { } } ``` ``` -------------------------------- ### Add Upgrade and UpgradeModule Parameters to Db and Version Constructors Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Explains the addition of 'upgrade' and 'upgradeModule' parameters to the constructors of the Db and Version classes in BlazorDexie, enabling custom version upgrade logic. ```csharp Add parameters upgrade and upgradeModule to constructor of classes Db and Version to call Version.upgrade in Dexie.js. ``` -------------------------------- ### Register BlazorDexie Services Source: https://context7.com/simon-kuster/blazordexie/llms.txt Demonstrates how to register BlazorDexie services in the .NET dependency injection container using the AddBlazorDexie extension method. Supports basic registration and advanced configuration with custom module paths and store name casing. ```csharp using BlazorDexie.Extensions; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("#app"); // Basic registration builder.Services.AddBlazorDexie(); // With custom user module base path and camelCase store names builder.Services.AddBlazorDexie(userModuleBasePath: "modules/", camelCaseStoreNames: true); await builder.Build().RunAsync(); ``` -------------------------------- ### Configure Auto-Increment Primary Key Source: https://context7.com/simon-kuster/blazordexie/llms.txt Shows how to set up auto-incrementing primary keys for database records in BlazorDexie. This involves prefixing the primary key definition with '++' and using JsonIgnore for default values. ```csharp using System.Text.Json.Serialization; using BlazorDexie.Database; using BlazorDexie.Options; public class Product { [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public int Id { get; set; } public string Name { get; set; } = string.Empty; public decimal Price { get; set; } } public class ShopDatabase : Db { // Auto-increment primary key with "++" prefix public Store Products { get; set; } = new( $"++{nameof(Product.Id)}", // Auto-increment primary key nameof(Product.Name) ); public ShopDatabase(BlazorDexieOptions options) : base("ShopDatabase", 1, Array.Empty(), options) { } } // Usage - Id is auto-generated await using var db = new ShopDatabase(BlazorDexieOptions); await db.Products.Put(new Product { Name = "Widget", Price = 9.99m }); await db.Products.Put(new Product { Name = "Gadget", Price = 19.99m }); // Products now have auto-generated Ids: 1, 2 ``` -------------------------------- ### Perform CRUD and Query Operations Source: https://github.com/simon-kuster/blazordexie/blob/master/README.md Demonstrates how to perform bulk insertions and complex queries using the BlazorDexie API. This includes filtering by range, ordering, and string matching. ```csharp var db = new MyDb(BlazorDexieOptions); await db.Friends.BulkPut(new Friend[] { new Friend(){ Id = 1, Name = "Josephine", Age = 21 }, new Friend(){ Id = 2, Name = "Per", Age = 75 }, new Friend(){ Id = 3, Name = "Simon", Age = 5 } }); var youngFriends = await db.Friends.Where("age").Between(0, 25).ToArray(); ``` -------------------------------- ### C# Static Dexie Database Operations Source: https://context7.com/simon-kuster/blazordexie/llms.txt Demonstrates using the static `Dexie` class for performing database-level operations such as checking if a database exists and deleting it. It also shows creating a database and adding data. ```csharp [Inject] public BlazorDexieOptions BlazorDexieOptions { get; set; } = null!; public async Task DatabaseOperations() { var dexie = new Dexie(BlazorDexieOptions); // Check if database exists bool exists = await dexie.Exits("FriendDatabase"); Console.WriteLine($"Database exists: {exists}"); if (exists) { // Delete the entire database await dexie.Delete("FriendDatabase"); Console.WriteLine("Database deleted"); } // Create new database await using var db = new FriendDatabase(BlazorDexieOptions); await db.Friends.Put(new Friend { Id = 1, Name = "Alice", Age = 25 }); // Delete database using Db instance await db.Delete(); } ``` -------------------------------- ### Sorting Query Results with OrderBy and SortBy in C# Source: https://context7.com/simon-kuster/blazordexie/llms.txt Demonstrates how to sort query results using OrderBy for index-based sorting and SortBy for in-memory sorting. OrderBy is faster when an index is available, while SortBy works on any property and can operate on collections. It also shows how to reverse the sort order and retrieve results as a List. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); await db.Friends.BulkPut(new Friend[] { new() { Id = 1, Name = "Charlie", Age = 35 }, new() { Id = 2, Name = "Alice", Age = 25 }, new() { Id = 3, Name = "Bob", Age = 30 }, new() { Id = 4, Name = "Diana", Age = 28 } }); // OrderBy - uses index (must be an indexed property) var orderedByAge = await db.Friends.OrderBy(nameof(Friend.Age)).ToArray(); Console.WriteLine("Ordered by age: " + string.Join(", ", orderedByAge.Select(f => $"{f.Name}({f.Age})"))); // Output: Ordered by age: Alice(25), Diana(28), Bob(30), Charlie(35) // OrderBy with Reverse var oldestFirst = await db.Friends.OrderBy(nameof(Friend.Age)).Reverse().ToArray(); Console.WriteLine("Oldest first: " + string.Join(", ", oldestFirst.Select(f => $"{f.Name}({f.Age})"))); // Output: Oldest first: Charlie(35), Bob(30), Diana(28), Alice(25) // SortBy - in-memory sort (works on Collection, not Store) var sortedByName = await db.Friends .Where(nameof(Friend.Age)).Above(0) // Create a Collection .SortBy(nameof(Friend.Name)); Console.WriteLine("Sorted by name: " + string.Join(", ", sortedByName.Select(f => f.Name))); // Output: Sorted by name: Alice, Bob, Charlie, Diana // SortByToList returns List instead of array List sortedList = await db.Friends.ToCollection().SortByToList(nameof(Friend.Name)); ``` -------------------------------- ### BlazorDexie: Collection Operations in C# Source: https://context7.com/simon-kuster/blazordexie/llms.txt Illustrates how to manipulate query results using collection operations in BlazorDexie, including ToArray, ToList, Count, Limit, Offset, Reverse, and Filter. These methods enable efficient pagination, result aggregation, and custom filtering of data. Requires the BlazorDexie library and a defined FriendDatabase context. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); await db.Friends.BulkPut(new Friend[] { new() { Id = 1, Name = "Alice", Age = 25 }, new() { Id = 2, Name = "Bob", Age = 30 }, new() { Id = 3, Name = "Charlie", Age = 35 }, new() { Id = 4, Name = "Diana", Age = 28 }, new() { Id = 5, Name = "Eve", Age = 22 } }); // ToArray - get all results Friend[] allFriends = await db.Friends.ToCollection().ToArray(); Console.WriteLine($"Total friends: {allFriends.Length}"); // Output: Total friends: 5 // ToList - get results as List List friendList = await db.Friends.ToCollection().ToList(); // Count - get number of matching records int count = await db.Friends.ToCollection().Count(); Console.WriteLine($"Count: {count}"); // Output: Count: 5 // Limit - restrict number of results var firstTwo = await db.Friends.ToCollection().Limit(2).ToArray(); Console.WriteLine($"First two: {string.Join(", ", firstTwo.Select(f => f.Name))}"); // Output: First two: Alice, Bob // Offset - skip records (useful for pagination) var page2 = await db.Friends.ToCollection().Offset(2).Limit(2).ToArray(); Console.WriteLine($"Page 2: {string.Join(", ", page2.Select(f => f.Name))}"); // Output: Page 2: Charlie, Diana // Reverse - reverse the order var reversed = await db.Friends.OrderBy(nameof(Friend.Age)).Reverse().ToArray(); Console.WriteLine($"Oldest first: {string.Join(", ", reversed.Select(f => $"{f.Name}({f.Age})"))}"); // Output: Oldest first: Charlie(35), Bob(30), Diana(28), Alice(25), Eve(22) // Filter with JavaScript function var filtered = await db.Friends.ToCollection() .Filter("item => item.age > 25 && item.name.startsWith('B')") .ToArray(); Console.WriteLine($"Filtered: {string.Join(", ", filtered.Select(f => f.Name))}"); // Output: Filtered: Bob ``` -------------------------------- ### Update Service Registration Method in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Demonstrates the change in the service registration method for BlazorDexie. The old method AddDexieWrapper has been replaced by AddBlazorDexie, which includes a new parameter for camel case store names and removes the user module base path. ```csharp AddDexieWrapper(IServiceCollection services, string userModuleBasePath = "") ``` ```csharp AddBlazorDexie(IServiceCollection services, bool camelCaseStoreNames = false) ``` -------------------------------- ### Store.Add and Store.Put Source: https://context7.com/simon-kuster/blazordexie/llms.txt Use `Add` to insert a new record (fails if key exists) and `Put` to insert or update a record (upsert). Both return the primary key. ```APIDOC ## Store.Add and Store.Put The `Add` method inserts a new record (fails if key exists), while `Put` inserts or updates a record (upsert). Both return the primary key of the stored record. ### Method Store Methods ### Endpoint N/A ### Parameters N/A ### Request Example ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); // Add a new friend - throws if Id already exists var friend1 = new Friend { Id = 1, Name = "Alice", Age = 25 }; int key1 = await db.Friends.Add(friend1); Console.WriteLine($"Added friend with key: {key1}"); // Output: Added friend with key: 1 // Put (insert or update) - will update if key exists var friend2 = new Friend { Id = 2, Name = "Bob", Age = 30 }; int key2 = await db.Friends.Put(friend2); Console.WriteLine($"Put friend with key: {key2}"); // Output: Put friend with key: 2 // Update existing record using Put friend2.Age = 31; await db.Friends.Put(friend2); // Updates Bob's age to 31 // Add with explicit key parameter var friend3 = new Friend { Name = "Charlie", Age = 28 }; int key3 = await db.Friends.Add(friend3, 3); ``` ### Response N/A ``` -------------------------------- ### Migrate Database Schema and Data (Version 2) Source: https://github.com/simon-kuster/blazordexie/blob/master/README.md This C# code demonstrates migrating the database schema to version 2. It involves creating a new version class, updating the main database class to include previous versions, and defining an upgrade function to transform existing data. ```csharp public class Version1 : DbVersion { public Store Friends { get; set; } = new("++id", "name" + "age"); public Version1() : base(1) { } } ``` ```csharp public class MyDb : Db { public Store Friends { get; set; } = new("++" + nameof(Friend.Id), nameof(Friend.Name), nameof(Friend.BirthDate)); public MyDb(BlazorDexieOptions blazorDexieOptions) : base("TestDb", 2, new IDbVersion[] { new Version1() }, blazorDexieOptions, GetUpgrade()) { } private static string GetUpgrade() { return "var YEAR = 365 * 24 * 60 * 60 * 1000; " + "return tx.table(\"Friends\").toCollection().modify(friend => { " + " friend.birthdate = new Date(Date.now() - (friend.age * YEAR)); " + " delete friend.age; " + "}); "; } } ``` -------------------------------- ### Enable Camel Case Store Names in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Demonstrates how to enable camel case for store names in BlazorDexie by passing the optional parameter 'camelCaseStoreNames : true' to the constructor of the Db class. ```csharp camelCaseStoreNames : true ``` -------------------------------- ### Service Registration Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Configures the BlazorDexie service within the .NET dependency injection container. ```APIDOC ## POST /ServiceRegistration ### Description Registers the BlazorDexie services in the IServiceCollection. ### Method POST ### Parameters #### Request Body - **services** (IServiceCollection) - Required - The service collection to register into. - **camelCaseStoreNames** (bool) - Optional - Whether to use camelCase for store names (default: false). ### Request Example services.AddBlazorDexie(services, camelCaseStoreNames: false); ``` -------------------------------- ### Add Blob Handling Methods to Store in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Details the addition of methods to the Store class in BlazorDexie for handling blobs. These include AddBlob, PutBlob, GetBlob for byte arrays, and AddObjectUrl, PutObjectUrl, GetObjectUrl for ObjectUrls. ```csharp AddBlob: Add byte array as blob to the db PutBlob: Put byte array as blob to the db GetBlob: Get blob from the DB as byte array AddObjecUrl: Add ObjectUrl as blob to the db PutObjectUrl: Put ObjectUrl as blob to the db GetObjectUrl: Get blob from the DB as ObjectUrl ``` -------------------------------- ### Generic DbVersion Class Usage in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Illustrates the usage of the generic DbVersion class in BlazorDexie, where TConcrete is the concrete class that extends DbVersion. ```csharp public class Version1 : DbVersion {} ``` -------------------------------- ### Add Static Delete and Exists Methods to Dexie Class in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Introduces static Delete and Exists methods to the Dexie class in BlazorDexie, enabling database-level operations for checking existence and deletion. ```csharp Add class Dexie with the static methods (static for Dexie not in C#) Delete and Exists ``` -------------------------------- ### Upgrade Database using External JavaScript Module Source: https://github.com/simon-kuster/blazordexie/blob/master/README.md This C# code shows an alternative approach to database upgrades by referencing an external JavaScript module. The upgrade logic is defined in a separate JS file, promoting better organization for complex upgrade routines. ```csharp public class MyDb : Db { public Store Friends { get; set; } = new("++" + nameof(Friend.Id), nameof(Friend.Name), nameof(Friend.BirthDate)); public MyDb(BlazorDexieOptions blazorDexieOptions) : base("TestDb", 2, new IDbVersion[] { new V1.Version1() }, blazorDexieOptions, upgradeModule: "dbUpgrade2.js") { } } ``` ```javascript export default function update(tx) { var YEAR = 365 * 24 * 60 * 60 * 1000; return tx.table("Friends").toCollection().modify(friend => { friend.birthdate = new Date(Date.now() - (friend.age * YEAR)); delete friend.age; }); } ``` -------------------------------- ### Execute Bulk Database Operations Source: https://context7.com/simon-kuster/blazordexie/llms.txt Covers batch processing methods including BulkPut, BulkGet, and BulkDelete. These operations are optimized to reduce round-trips to the underlying IndexedDB storage. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); var friends = new Friend[] { new() { Id = 1, Name = "Alice", Age = 25 }, new() { Id = 2, Name = "Bob", Age = 30 }, new() { Id = 3, Name = "Charlie", Age = 35 }, new() { Id = 4, Name = "Diana", Age = 28 } }; await db.Friends.BulkPut(friends); List allKeys = await db.Friends.BulkPutReturnAllKeys(friends); int[] keysToGet = { 1, 2, 5 }; Friend?[] results = await db.Friends.BulkGet(keysToGet); foreach (var result in results) { Console.WriteLine(result != null ? $"Found: {result.Name}" : "Not found"); } int[] keysToDelete = { 1, 2 }; await db.Friends.BulkDelete(keysToDelete); int remaining = await db.Friends.ToCollection().Count(); Console.WriteLine($"Remaining friends: {remaining}"); ``` -------------------------------- ### Perform Partial Record Updates Source: https://context7.com/simon-kuster/blazordexie/llms.txt Shows how to update specific fields of a record by providing a dictionary of changes. This allows for partial modifications without overwriting the entire object. ```csharp await using var db = new FriendDatabase(BlazorDexieOptions); await db.Friends.Put(new Friend { Id = 1, Name = "Alice", Age = 25, Email = "alice@example.com" }); var changes = new Dictionary { { nameof(Friend.Age), 26 }, { nameof(Friend.Email), "alice.new@example.com" } }; int updateCount = await db.Friends.Update(1, changes); Console.WriteLine($"Updated {updateCount} record(s)"); var updated = await db.Friends.Get(1); Console.WriteLine($"{updated!.Name}: Age={updated.Age}, Email={updated.Email}"); ``` -------------------------------- ### C# Database Versioning with External JS Upgrade Module Source: https://context7.com/simon-kuster/blazordexie/llms.txt Defines database schema versions and references an external JavaScript file for schema upgrade logic. This approach separates migration code into a dedicated module. ```csharp using BlazorDexie.Database; using BlazorDexie.Options; // Version 1 schema definition (for migration history) public class Version1 : DbVersion { public Store Friends { get; set; } = new("++id", "name", "age"); public Version1() : base(1) { } } public class FriendV1 { public int Id { get; set; } public string Name { get; set; } = string.Empty; public int Age { get; set; } } // Current model (version 2) with BirthDate instead of Age public class FriendV2 { public int Id { get; set; } public string Name { get; set; } = string.Empty; public DateTime BirthDate { get; set; } } // Alternative: Use ES module for upgrade logic public class FriendDatabaseV2Alt : Db { public Store Friends { get; set; } = new( $"++{nameof(FriendV2.Id)}", nameof(FriendV2.Name), nameof(FriendV2.BirthDate) ); public FriendDatabaseV2Alt(BlazorDexieOptions options) : base("FriendDatabase", 2, new IDbVersion[] { new Version1() }, options, upgradeModule: "dbUpgrade2.js") { } } // dbUpgrade2.js (place in wwwroot) // export default function upgrade(tx) { // var YEAR = 365 * 24 * 60 * 60 * 1000; // return tx.table('Friends').toCollection().modify(friend => { // friend.birthDate = new Date(Date.now() - (friend.age * YEAR)); // delete friend.age; // }); // } ``` -------------------------------- ### Add .NET 9 Support to BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Notes the inclusion of support for the .NET 9 development platform in BlazorDexie, expanding its compatibility. ```csharp - Add support for .NET 9.0 ``` -------------------------------- ### C# Database Versioning with Upgrade Function Source: https://context7.com/simon-kuster/blazordexie/llms.txt Defines database schema versions and includes an inline JavaScript upgrade function to migrate data between versions. It demonstrates converting 'age' to 'birthDate' during schema upgrades. ```csharp using BlazorDexie.Database; using BlazorDexie.Options; // Version 1 schema definition (for migration history) public class Version1 : DbVersion { public Store Friends { get; set; } = new("++id", "name", "age"); public Version1() : base(1) { } } public class FriendV1 { public int Id { get; set; } public string Name { get; set; } = string.Empty; public int Age { get; set; } } // Current model (version 2) with BirthDate instead of Age public class FriendV2 { public int Id { get; set; } public string Name { get; set; } = string.Empty; public DateTime BirthDate { get; set; } } // Version 2 database with upgrade function public class FriendDatabaseV2 : Db { public Store Friends { get; set; } = new( $"++{nameof(FriendV2.Id)}", nameof(FriendV2.Name), nameof(FriendV2.BirthDate) ); public FriendDatabaseV2(BlazorDexieOptions options) : base("FriendDatabase", 2, new IDbVersion[] { new Version1() }, options, GetUpgrade()) { } private static string GetUpgrade() { // JavaScript upgrade function to convert age to birthDate return @" var YEAR = 365 * 24 * 60 * 60 * 1000; return tx.table('Friends').toCollection().modify(friend => { friend.birthDate = new Date(Date.now() - (friend.age * YEAR)); delete friend.age; }); "; } } ``` -------------------------------- ### Store Operations Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Methods available for interacting with object stores, including blob support. ```APIDOC ## METHODS Store Operations ### Description Operations for managing data within an IndexedDB store. ### Methods - **AddBlob(byte[])**: Adds a byte array as a blob. - **PutBlob(byte[])**: Updates/Puts a byte array as a blob. - **GetBlob()**: Retrieves a blob as a byte array. - **AddObjectUrl(string)**: Adds an ObjectUrl as a blob. - **PutObjectUrl(string)**: Updates/Puts an ObjectUrl as a blob. - **GetObjectUrl()**: Retrieves a blob as an ObjectUrl. ``` -------------------------------- ### Add .NET 7 and .NET 8 Support to BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Confirms the addition of support for .NET 7.0 and .NET 8.0 in BlazorDexie, enhancing its compatibility with recent .NET releases. ```csharp - Add support for .NET 7.0 and .NET 8.0 ``` -------------------------------- ### Store.Get and Store.Delete Source: https://context7.com/simon-kuster/blazordexie/llms.txt Retrieve or remove individual records from the store using their primary key. ```APIDOC ## GET /Store.Get ### Description Retrieves a single record from the store by its primary key. Returns null if no record is found. ### Method GET ### Endpoint /Store.Get/{key} ### Parameters #### Path Parameters - **key** (any) - Required - The primary key of the record to retrieve. ### Response #### Success Response (200) - **record** (object) - The requested record or null. ## DELETE /Store.Delete ### Description Removes a single record from the store based on the provided primary key. ### Method DELETE ### Endpoint /Store.Delete/{key} ### Parameters #### Path Parameters - **key** (any) - Required - The primary key of the record to delete. ``` -------------------------------- ### Add SortBy Methods to Collection in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Introduces the SortBy and SortByToList methods to the Collection class in BlazorDexie, allowing for ordered retrieval of data from stores. ```csharp Add methods SortBy and SortByToList (same as SortBy but returns a list instead of an array) to Collection. ``` -------------------------------- ### Update Db Class Constructor in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Illustrates the modification of the Db class constructor in BlazorDexie. The constructor now uses a generic type parameter TConcrete and replaces moduleFactory and camelCaseStoreNames parameters with BlazorDexieOptions. ```csharp protected Db( string databaseName, int currentVersionNumber, IEnumerable previousVersions, IModuleFactory moduleFactory, string? upgrade = null, string? upgradeModule = null, bool camelCaseStoreNames = false) ``` ```csharp protected Db( string databaseName, int currentVersionNumber, IEnumerable previousVersions, BlazorDexieOptions blazorDexieOptions, string? upgrade = null, string? upgradeModule = null) ``` -------------------------------- ### Database Versioning - Version 2 with JavaScript Module Upgrade Source: https://github.com/simon-kuster/blazordexie/blob/master/README.md Upgrades the database from Version 1 to Version 2 using an external JavaScript module for the upgrade function. ```APIDOC ## Database Versioning - Version 2 with JavaScript Module Upgrade ### Description This demonstrates an alternative approach to database versioning where the upgrade logic is contained within an external JavaScript module (`dbUpgrade2.js`). This module is then referenced in the `BlazorDexieOptions` constructor. This method promotes better organization for complex upgrade scripts. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example **Main Database Class:** ```csharp public class MyDb : Db { public Store Friends { get; set; } = new("++" + nameof(Friend.Id), nameof(Friend.Name), nameof(Friend.BirthDate)); public MyDb(BlazorDexieOptions blazorDexieOptions) : base("TestDb", 2, new IDbVersion[] { new V1.Version1() }, blazorDexieOptions, upgradeModule: "dbUpgrade2.js") { } } ``` **`dbUpgrade2.js`:** ```javascript export default function update(tx) { var YEAR = 365 * 24 * 60 * 60 * 1000; return tx.table("Friends").toCollection().modify(friend => { friend.birthdate = new Date(Date.now() - (friend.age * YEAR)); delete friend.age; }); } ``` **Note on `camelCaseStoreNames`:** Depending on the `camelCaseStoreNames` setting (default is false), use `tx.table("Friends")` or `tx.table("friends")`. ``` -------------------------------- ### Database Configuration Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Defines the structure and versioning of the IndexedDB database. ```APIDOC ## CLASS Db ### Description Base class for defining a database schema. Inherit from this class to create a specific database implementation. ### Constructor Parameters - **databaseName** (string) - Required - Name of the database. - **currentVersionNumber** (int) - Required - Current schema version. - **previousVersions** (IEnumerable) - Required - List of previous schema versions. - **blazorDexieOptions** (BlazorDexieOptions) - Required - Configuration options including module factory. - **upgrade** (string) - Optional - Upgrade script path. - **upgradeModule** (string) - Optional - Upgrade module path. ### Example public class MyDb : Db { } ``` -------------------------------- ### Add Transaction Support in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Highlights the addition of transaction support in BlazorDexie, enabling more robust data operations within the IndexedDB. ```csharp // Transaction support added in version 1.5.0 ``` -------------------------------- ### Database Versioning - Version 2 with JavaScript Upgrade Source: https://github.com/simon-kuster/blazordexie/blob/master/README.md Upgrades the database from Version 1 to Version 2, including a JavaScript function to modify existing data and update the schema. ```APIDOC ## Database Versioning - Version 2 with JavaScript Upgrade ### Description This section details the process of upgrading the database schema from Version 1 to Version 2. It involves creating a new version class, updating the main database class to include the previous version, and providing a JavaScript upgrade function to migrate data. The upgrade function calculates birthdates based on age and removes the 'age' field. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example **Version 1 Class (for reference):** ```csharp public class Version1 : DbVersion { public Store Friends { get; set; } = new("++id", "name" + "age"); public Version1() : base(1) { } } ``` **Main Database Class (Version 2):** ```csharp public class MyDb : Db { public Store Friends { get; set; } = new("++" + nameof(Friend.Id), nameof(Friend.Name), nameof(Friend.BirthDate)); public MyDb(BlazorDexieOptions blazorDexieOptions) : base("TestDb", 2, new IDbVersion[] { new Version1() }, blazorDexieOptions, GetUpgrade()) { } private static string GetUpgrade() { return "var YEAR = 365 * 24 * 60 * 60 * 1000; " + "return tx.table(\"Friends\").toCollection().modify(friend => { " + " friend.birthdate = new Date(Date.now() - (friend.age * YEAR)); " + " delete friend.age; " + "}); "; } } ``` **Note on `camelCaseStoreNames`:** Depending on the `camelCaseStoreNames` setting (default is false), use `tx.table("Friends")` or `tx.table("friends")`. ``` -------------------------------- ### Displaying Icons via SVG Source: https://github.com/simon-kuster/blazordexie/blob/master/BlazorDexie.Demo/wwwroot/css/open-iconic/README.md Standard method for displaying individual icons using the HTML img tag. Requires a valid path to the SVG file and an alt attribute for accessibility. ```html icon name ``` -------------------------------- ### Update Dexie Class Constructor in BlazorDexie Source: https://github.com/simon-kuster/blazordexie/blob/master/CHANGELOG.md Shows the change in the Dexie class constructor. The constructor's parameter has been updated from BlazorDexieOptions to IModuleFactory jsModuleFactory, reflecting a shift in dependency injection. ```csharp public Dexie(BlazorDexieOptions blazorDexieOptions) ``` ```csharp public Dexie(IModuleFactory jsModuleFactory) ```