Extension Methods

Introduction

Spark includes a variety of C# extension methods to extend base functionality.

DbSet Extensions

DbSet.Save()

The DbSet.Save method saves a model to the database through entity framework.

using var db = factory.CreateDbContext();
db.Developers.Save(newDeveloper);

If the model doesn’t exist in the database yet, the Save() method sets the CreatedAt property to the current datetime and creates a new record.

If the model does exist in the database, the Save() method sets the UpdatedAt property to the current datetime and updates the existing record.

DbSet.Delete()

The DbSet.Delete method deletes a model from the database.

using var db = factory.CreateDbContext();
db.Developers.Delete(developer);

The NavigationManager.Route method provides the route of the current page.

@page "/developers"
@inject NavigationManager NavManager

@code {
    protected override async Task OnInitializedAsync()
    {
        var route = NavManager.Route();
        
        // route = "developers"
    }
}

The NavigationManager.XRedirect method allows you to do a page redirect with HTMX.

@page "/developers"
@inject NavigationManager NavManager

@code {
    protected void OnSubmit()
    {
        ...
        NavManager.XRedirect(HttpContext, "profile/edit");
    }
}

String Extensions

String.Clamp(int maxChars)

The String.Clamp method reduces the length of a string to the passed maxChars value. 3 elipses are also added to the end of the string.

var str = "this is some string";
var clampedStr = str.Clamp(4);

// clampedStr = "this..."

String.ToSlug()

The String.ToSlug method converts a string to a url friendly slug.

var str = "This is some string";
var slugStr = str.ToSlug();

// slugStr = "this-is-some-string"