### Installing Blazored.LocalStorage.TestExtensions
Source: https://github.com/blazored/localstorage/blob/main/README.md
Shows how to install the Blazored.LocalStorage.TestExtensions package via the .csproj file or the .NET CLI for testing components with bUnit.
```csharp
```
```bash
dotnet add package Blazored.LocalStorage.TestExtensions
```
--------------------------------
### Install Blazored LocalStorage via .NET CLI
Source: https://github.com/blazored/localstorage/blob/main/README.md
Provides the .NET CLI command to install the Blazored.LocalStorage package. This is an alternative to using the NuGet package manager.
```bash
dotnet add package Blazored.LocalStorage
```
--------------------------------
### bUnit Test Example
Source: https://github.com/blazored/localstorage/blob/main/README.md
An example of a bUnit test that utilizes Blazored.LocalStorage test extensions to verify that a component correctly saves data to local storage.
```csharp
public class IndexPageTests : TestContext
{
[Fact]
public async Task SavesNameToLocalStorage()
{
// Arrange
const string inputName = "John Smith";
var localStorage = this.AddBlazoredLocalStorage();
var cut = RenderComponent();
// Act
cut.Find("#Name").Change(inputName);
cut.Find("#NameButton").Click();
// Assert
var name = await localStorage.GetItemAsync("name");
Assert.Equal(inputName, name);
}
}
```
--------------------------------
### Install Blazored LocalStorage via NuGet
Source: https://github.com/blazored/localstorage/blob/main/README.md
Shows how to add the Blazored.LocalStorage package to a Blazor project's csproj file. Replace 'x.x.x' with the latest version number.
```bash
```
--------------------------------
### Configuring JSON Serializer Options
Source: https://github.com/blazored/localstorage/blob/main/README.md
Provides an example of configuring System.Text.Json serializer options when registering Blazored.LocalStorage services in a Blazor WebAssembly application.
```csharp
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("app");
builder.Services.AddBlazoredLocalStorage(config =>
config.JsonSerializerOptions.WriteIndented = true
);
await builder.Build().RunAsync();
}
```
--------------------------------
### Blazor WebAssembly Usage (Async)
Source: https://github.com/blazored/localstorage/blob/main/README.md
Demonstrates injecting and using the asynchronous ILocalStorageService in a Blazor WebAssembly application to set and get items from local storage.
```csharp
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@code {
protected override async Task OnInitializedAsync()
{
await localStorage.SetItemAsync("name", "John Smith");
var name = await localStorage.GetItemAsync("name");
}
}
```
--------------------------------
### Using Open Iconic SVG Sprite
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/css/open-iconic/README.md
Explains how to utilize the SVG sprite for efficient icon display. This approach allows all icons to be loaded in a single request, similar to icon fonts but without the associated drawbacks. It includes examples for applying classes for styling and sizing.
```html
```
```css
.icon {
width: 16px;
height: 16px;
}
```
```css
.icon-account-login {
fill: #f00;
}
```
--------------------------------
### Blazor.start Configuration for GitHub Pages
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/index.html
This JavaScript code configures Blazor.start to load resources efficiently for Blazor WebAssembly applications, especially when hosted on GitHub Pages. It includes logic to use Brotli-compressed files for faster downloads and handles decompression when necessary.
```javascript
Blazor.start({ loadBootResource: function (type, name, defaultUri, integrity) { if (type !== 'dotnetjs' && location.hostname !== 'localhost') { return (async function () { const response = await fetch(defaultUri + '.br', { cache: 'no-cache' }); if (!response.ok) { throw new Error(response.statusText); } const originalResponseBuffer = await response.arrayBuffer(); const originalResponseArray = new Int8Array(originalResponseBuffer); const decompressedResponseArray = BrotliDecode(originalResponseArray); const contentType = type === 'dotnetwasm' ? 'application/wasm' : 'application/octet-stream'; return new Response(decompressedResponseArray, { headers: { 'content-type': contentType } }); })(); } } });
```
--------------------------------
### Local Storage Service Interface
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/404.html
Defines the interface for the Blazored Local Storage service, outlining the available methods for interacting with the browser's local storage.
```csharp
public interface ILocalStorageService
{
ValueTask ClearAsync();
ValueTask GetItemAsync(string key);
ValueTask KeyAsync(int index);
ValueTask LengthAsync();
ValueTask RemoveItemAsync(string key);
ValueTask SetItemAsync(string key, TItem data);
ValueTask SetItemAsync(string key, byte[] data);
ValueTask ContainKeyAsync(string key);
}
```
--------------------------------
### Registering a Custom JSON Serializer
Source: https://github.com/blazored/localstorage/blob/main/README.md
Demonstrates how to replace the default System.Text.Json serializer with a custom implementation that adheres to the IJsonSerializer interface.
```csharp
builder.Services.AddBlazoredLocalStorage();
builder.Services.Replace(ServiceDescriptor.Scoped());
```
--------------------------------
### Blazor Local Storage Integration
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/404.html
Demonstrates how to integrate and use the Blazor Local Storage component in a Blazor application. This involves injecting the service and calling its methods to interact with the browser's local storage.
```csharp
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components;
public class MyComponent : ComponentBase
{
[Inject]
private ILocalStorageService LocalStorage { get; set; }
private async Task SaveDataAsync()
{
await LocalStorage.SetItemAsync("myKey", "myValue");
}
private async Task GetDataAsync()
{
return await LocalStorage.GetItemAsync("myKey");
}
private async Task RemoveDataAsync()
{
await LocalStorage.RemoveItemAsync("myKey");
}
}
```
--------------------------------
### Blazor Server Usage
Source: https://github.com/blazored/localstorage/blob/main/README.md
Illustrates using the asynchronous ILocalStorageService in Blazor Server, noting the requirement to perform JS interop after the OnAfterRender lifecycle method.
```csharp
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await localStorage.SetItemAsync("name", "John Smith");
var name = await localStorage.GetItemAsync("name");
}
}
```
--------------------------------
### Register Blazored LocalStorage in Blazor Server
Source: https://github.com/blazored/localstorage/blob/main/README.md
Illustrates how to register the Blazored LocalStorage services in the `ConfigureServices` method of `Startup.cs` for Blazor Server applications.
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddBlazoredLocalStorage();
}
```
--------------------------------
### Single Page App URL Rewriting for GitHub Pages
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/404.html
This JavaScript code is designed to handle URL rewriting for single-page applications hosted on GitHub Pages. It converts the current URL's path and query string into a format suitable for GitHub Pages, typically redirecting to the root with query parameters indicating the original path and query.
```javascript
var segmentCount = 1;
var l = window.location;
l.replace( l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') + l.pathname.split('/').slice(0, 1 + segmentCount).join('/') + '/?p=/' + l.pathname.slice(1).split('/').slice(segmentCount).join('/').replace(/&/g, '~and~') + (l.search ? '&q=' + l.search.slice(1).replace(/&/g, '~and~') : '') + l.hash );
```
--------------------------------
### Open Iconic with Foundation
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/css/open-iconic/README.md
Details the integration of Open Iconic with the Foundation framework. Similar to Bootstrap, this requires linking the Foundation-specific stylesheet and using the `` element with the `fi` class for icons.
```html
```
```html
```
--------------------------------
### Register Blazored LocalStorage Streaming Services
Source: https://github.com/blazored/localstorage/blob/main/README.md
Demonstrates how to register the streaming local storage service for handling large data transfers in Blazor Server apps, bypassing SignalR message size limits.
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddBlazoredLocalStorageStreaming();
}
```
--------------------------------
### Open Iconic with Bootstrap
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/css/open-iconic/README.md
Provides instructions for integrating Open Iconic with the Bootstrap framework. This involves linking the Bootstrap-specific stylesheet and using the provided `` element with the `oi` class for icon display.
```html
```
```html
```
--------------------------------
### Blazor WebAssembly Usage (Sync)
Source: https://github.com/blazored/localstorage/blob/main/README.md
Shows how to inject and use the synchronous ISyncLocalStorageService in Blazor WebAssembly for direct local storage operations without async/await.
```csharp
@inject Blazored.LocalStorage.ISyncLocalStorageService localStorage
@code {
protected override void OnInitialized()
{
localStorage.SetItem("name", "John Smith");
var name = localStorage.GetItem("name");
}
}
```
--------------------------------
### Register Blazored LocalStorage in Blazor WebAssembly
Source: https://github.com/blazored/localstorage/blob/main/README.md
Shows how to register Blazored LocalStorage services in the `Program.cs` file for Blazor WebAssembly applications.
```csharp
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("app");
builder.Services.AddBlazoredLocalStorage();
await builder.Build().RunAsync();
}
```
--------------------------------
### Include Blazored.LocalStorage JavaScript File
Source: https://github.com/blazored/localstorage/blob/main/README.md
Shows how to add the Blazored.LocalStorage.js JavaScript file to the `App.razor` file to enable JS Interop streaming functionality.
```html
```
--------------------------------
### Register Blazored LocalStorage as Singleton (Blazor WebAssembly Only)
Source: https://github.com/blazored/localstorage/blob/main/README.md
Explains how to register Blazored LocalStorage services as a Singleton in Blazor WebAssembly. This is for specific scenarios and not recommended for most users.
```csharp
builder.Services.AddBlazoredLocalStorageAsSingleton();
```
--------------------------------
### Using Open Iconic SVGs
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/css/open-iconic/README.md
Demonstrates how to use individual SVG files from the Open Iconic set. This method involves referencing the SVG file directly in an `` tag, ensuring accessibility with an `alt` attribute.
```html
```
--------------------------------
### Configure JsonSerializerOptions for Blazored LocalStorage
Source: https://github.com/blazored/localstorage/blob/main/README.md
Demonstrates how to configure JsonSerializerOptions for Blazored LocalStorage to retain v3 settings in v4 and later. This is useful for maintaining consistent serialization behavior.
```csharp
builder.Services.AddBlazoredLocalStorage(config =>
{
config.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
config.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
config.JsonSerializerOptions.IgnoreReadOnlyProperties = true;
config.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
config.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
config.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;
config.JsonSerializerOptions.WriteIndented = false;
});
```
--------------------------------
### Open Iconic Standalone Usage
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/css/open-iconic/README.md
Illustrates how to use Open Iconic's icon font independently, without a specific framework. This involves linking the default stylesheet and using a `` element with the `oi` class and a `data-glyph` attribute.
```html
```
```html
```
--------------------------------
### Redirect Handling in Single Page Apps
Source: https://github.com/blazored/localstorage/blob/main/samples/BlazorWebAssembly/wwwroot/index.html
This JavaScript code snippet handles redirects in single-page applications by parsing query parameters from the URL and updating the browser's history. It's designed to work with SPAs hosted on platforms like GitHub Pages.
```javascript
(function (l) { if (l.search) { var q = {}; l.search.slice(1).split('&').forEach(function (v) { var a = v.split('='); q[a[0]] = a.slice(1).join('=').replace(/~and~/g, '&'); }); if (q.p !== undefined) { window.history.replaceState(null, null, l.pathname.slice(0, -1) + (q.p || '') + (q.q ? ('?' + q.q) : '') + l.hash ); } } }(window.location))
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.