Getting started
Installation
From an empty Blazor app to the first component, step by step. Every snippet has a copy button.
Requirements
- .NET 9 SDK; the library targets net9.0.
- A Blazor Web App with interactive Server rendering, or a standalone Blazor WebAssembly app.
- Bootstrap, the icon fonts, TinyMCE, PDF.js and the other browser libraries ship with the package.
Add the package
From a NuGet feed that hosts the package:
dotnet add package DWSBlazorComponentLibrary --version 20261206222504-6e8ff32.dirtyOr as a project reference to a checkout of the repository:
<ItemGroup>
<ProjectReference Include="..\DWS-BlazorComponentLibrary-VS-Solution\DWSBlazorComponentLibrary\DWSBlazorComponentLibrary.csproj" />
</ItemGroup>Then add the namespace to _Imports.razor:
@using DWSBlazorComponentLibraryAdd styles and scripts
In <head> of App.razor (Server) or wwwroot/index.html (WebAssembly). The theme script comes first and without defer or async: it restores the theme of the last visit before the first paint.
<script src="_content/DWSBlazorComponentLibrary/js/dws.theme.js"></script>
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/css/bootstrap_v5_3_8/bootstrap.min.css" />
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/icons/bootstrap_icons_v1_13_1/font/bootstrap-icons.min.css" />
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/css/DWSBlazorComponentLibrary.min.css" />
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/fonts/fontawesome_v7_3_1/css/fontawesome.min.css" />
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/fonts/fontawesome_v7_3_1/css/brands.min.css" />
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/fonts/fontawesome_v7_3_1/css/regular.min.css" />
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/fonts/fontawesome_v7_3_1/css/solid.min.css" />
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/icons/open_iconic_v1_1_1/font/css/open-iconic-bootstrap.min.css" />
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/fonts/roboto.css" />
<link rel="stylesheet" href="_content/DWSBlazorComponentLibrary/fonts/caveat.css" />At the end of <body>, after blazor.web.js (Server) or blazor.webassembly.js (WebAssembly), one script: <DwsScripts /> in App.razor, or the plain tag in index.html. It loads every other library script (rich text editor, map, charts, media, ...) the first time a page needs it; the Preload parameter (data-preload on the plain tag) names modules to fetch early.
@* App.razor (Blazor Server / Web App), after blazor.web.js *@
@using DWSBlazorComponentLibrary.Components.Scripts
<DwsScripts />
@* Optional: modules a page will need soon, fetched once the browser is idle *@
<DwsScripts Preload="@(new[] { DwsScriptModules.Popover, DwsScriptModules.Select })" />
<!-- wwwroot/index.html (standalone WebAssembly), after blazor.webassembly.js -->
<script src="_content/DWSBlazorComponentLibrary/js/dws.js"></script>
<!-- Optional, the same with preloading -->
<script src="_content/DWSBlazorComponentLibrary/js/dws.js" data-preload="popover,select" data-preload-idle></script>TinyMCE, PDF.js, Prism, zxing, mammoth and SheetJS are loaded on demand and need no tag, and Bootstrap's JavaScript is not needed. In an app that maps its static files with app.MapStaticAssets(), write the URLs as @Assets["_content/DWSBlazorComponentLibrary/..."]: they become content-hash URLs that browsers cache for a year without asking again. DwsStyles and DwsScripts do this on their own.
Register services in one call
AddDwsComponents() registers everything the components need and picks the Server or the WebAssembly registration itself (OperatingSystem.IsBrowser(); HostModel overrides it). The optional parts - app updates, the ILogger adapter, environment info, a desktop window host - are added on the builder it returns, so an app pulls in only what it uses.
using DWSBlazorComponentLibrary;
// Server (Blazor Server, static SSR, a Web App's server project) or WebAssembly: picked for you.
builder.Services.AddDwsComponents(options =>
{
options.Navigation = navigationOptions => navigationOptions.HomeRoute = "/";
options.Localization = localizationOptions => { /* your translation files, see Advanced setup */ };
// options.HostModel = DwsComponentsHostModel.Server; // only to override the automatic choice
})
.AddAppUpdate() // optional: releases, planned restarts and maintenance (DwsUpdateBanner)
.AddILoggerAdapter(); // optional: ILogger<T> writes into the library's loggerIt calls the same methods as the two sections below, which show every option one by one; both ways stay supported. A WebAssembly app still needs the .csproj setting and the awaited InitializeAsync() described there.
Register services: Blazor Server
In Program.cs, after AddRazorComponents(). The five configurators are optional: parameter encryption, navigation, logger, localisation and haptics.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddHubOptions(options => options.MaximumReceiveMessageSize = 256 * 1024); // optional, see the note below
builder.Services.AddDWSComponentLibraryServicesServer(
parameterEncryptionOptions => { /* see Advanced setup */ },
navigationOptions => { /* see Advanced setup */ },
loggerOptions => { /* see Advanced setup */ },
localizationOptions => { /* see Advanced setup */ },
hapticOptions => { /* see Advanced setup */ });
builder.Services.AddILoggerToDwsLoggerServiceAdapter(); // optional
builder.Services.AddDwsAppUpdateServer(); // optional: maintenance directory watcher (AppUpdate.Server)
builder.Services.AddDWSAppUpdate(o => o.AddSource<DwsFileAppUpdateSource>());
builder.Services.TryAddSingleton<IDwsBaseAppStateContainer, CustomeAppStateContainer>();
builder.Services.TryAddScoped<IDwsBaseUserStateContainer, CustomeUserStateContainer>();
builder.Services.TryAddScoped<IDwsBaseUserContainer, CustomeUserContainer>();
builder.Services.TryAddScoped<IDwsBaseUserService, CustomeUserService>();
var app = builder.Build();
DwsServiceLocator.ServiceProvider = app.Services;On Server the translation files are loaded while the services are registered. Awaiting InitializeAsync() is optional there and keeps one code path with WebAssembly.
A bound text field sends its whole text with every change. SignalR accepts at most 32 KB per message from the browser by default, and a larger message closes the circuit. If your users edit long texts (DwsInput with Lines, DwsCodeEditor), raise MaximumReceiveMessageSize as above.
Register services: Blazor WebAssembly
Required in the app's .csproj: the localisation sets a specific culture, and Blazor ships trimmed globalisation data by default.
<PropertyGroup>
<BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData>
</PropertyGroup>In Program.cs. Your own translation files are fetched over HTTP, and InitializeAsync() must be awaited before RunAsync():
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddDWSEnvironmentInfo(options => options.EnvironmentName = builder.HostEnvironment.Environment);
var localizationHttpClient = new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) };
builder.Services.AddDWSComponentLibraryServicesClient(
configureLocalization: localizationOptions =>
{
localizationOptions.LocalizationFiles = new List<DwsLocalizationFileEntry>
{
new DwsLocalizationFileEntry { LanguageCode = "en-US", Path = "Localization/consumer_en.xml", FormatTypeKey = "xml", ResolveRelativeToBaseDirectory = false },
new DwsLocalizationFileEntry { LanguageCode = "de-DE", Path = "Localization/consumer_de.xml", FormatTypeKey = "xml", ResolveRelativeToBaseDirectory = false }
};
localizationOptions.FallbackLanguage = "en-US";
localizationOptions.FileLoaders.Add(new DwsLocalizationWasmXmlFileLoader(localizationHttpClient));
});
// optional: announced updates and temporary offline mode
builder.Services.AddDWSAppUpdate(o => o.AddHttpPolling(new Uri(new Uri(builder.HostEnvironment.BaseAddress), "app-update.json")));
builder.Services.TryAddSingleton<IDwsBaseAppStateContainer, CustomeAppStateContainer>();
builder.Services.TryAddScoped<IDwsBaseUserStateContainer, CustomeUserStateContainer>();
builder.Services.TryAddScoped<IDwsBaseUserContainer, CustomeUserContainer>();
builder.Services.TryAddScoped<IDwsBaseUserService, CustomeUserService>();
var host = builder.Build();
DwsServiceLocator.ServiceProvider = host.Services;
await host.Services.GetRequiredService<IDwsLocalizationService>().InitializeAsync();
await host.RunAsync();Updates and maintenance work the same in both hosts (AddDWSAppUpdate, shown by DwsUpdateBanner). Under WebAssembly the status is polled from a static app-update.json or the server's endpoint, or pushed over SignalR with the AppUpdate.Client package; the file watcher, endpoint and hub are in AppUpdate.Server.
Implement the required classes
The app supplies two state containers (base classes DwsBaseAppStateContainer and DwsBaseUserStateContainer) and the user abstractions (interfaces IDwsBaseUserContainer and IDwsBaseUserService). The demo's versions:
public class CustomeAppStateContainer : DwsBaseAppStateContainer
{
// Custom implementation if needed
}
public class CustomeUserStateContainer : DwsBaseUserStateContainer
{
public bool LogViewerEnabled { get; set; } = false;
}
public class CustomeUserContainer : IDwsBaseUserContainer
{
public bool? IsAdministrator { get; set; } = true;
public Dictionary<string, (bool enabled, bool visible)> ApplicationPermissionNameSpaces { get; set; } = new();
public Dictionary<string, (bool enabled, bool visible)> UserDefinedNameSpaces { get; set; } = new();
public ClaimsPrincipal User { get; set; }
public IEnumerable<Claim> Claims { get; set; } = new List<Claim>();
}
public class CustomeUserService : IDwsBaseUserService
{
private readonly IDwsBaseUserContainer _userContainer;
public CustomeUserService(IDwsBaseUserContainer userContainer)
{
_userContainer = userContainer;
}
public Task<IDwsBaseUserContainer> GetCurrentUserAsync()
{
if (_userContainer.User == null)
{
var connectionId = Guid.NewGuid().ToString();
_userContainer.User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "NewUser"),
new Claim(ClaimTypes.Role, "User"),
new Claim("ConnectionId", connectionId)
}, "mock"));
_userContainer.IsAdministrator = false;
_userContainer.Claims = _userContainer.User.Claims;
}
return Task.FromResult(_userContainer);
}
}CustomeUserService is a demo that creates a new user per connection. Connect your identity provider in your own implementation.
Prepare the main layout
Add the hosts for dialogs, toasts and snackbars at the top of MainLayout.razor:
<DwsDialogProvider Name="MainLayout_DialogProvider" />
<DwsToast Name="MainLayout_Toast" />
<DwsSnackbar Name="MainLayout_Snackbar" />Initialise the navigation service and the dispatchers in MainLayout.razor.cs:
// The navigation service initialises itself; Routes.razor renders pages through DwsNavigationOutlet:
// <Found Context="routeData">
// <DwsNavigationOutlet Name="AppOutlet" RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
// </Found>
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
DwsJsDispatcher.Initialize(JS);
DwsStorageDispatcher.Initialize(LocalStorageService, ProtectedLocalStorageService, SessionStorageService, ProtectedSessionStorageService);
}
}Advanced setup
Custom encryption key
DwsParameterEncryptionConfig sets the AES-GCM key that IDwsProtectedParameter uses (32 characters, or the base64 of 32 random bytes). Without it a random key is used until the app restarts. Use your own key, never the demo's.
builder.Services.AddDWSComponentLibraryServicesServer(parameterEncryptionOptions =>
{
parameterEncryptionOptions.Config = new DwsParameterEncryptionConfig
{
// From configuration or a secret store: 32 characters, or the base64 of 32 random bytes.
Key = builder.Configuration["Dws:ParameterKey"]!
};
});Navigation
DwsNavigationOptions sets the routes the permission system redirects to, and can replace the navigation service.
builder.Services.AddDWSComponentLibraryServicesServer(configureNavigation: navigationOptions =>
{
navigationOptions.HomeRoute = "/";
navigationOptions.LoginRoute = "/";
navigationOptions.LogoutRoute = "/";
navigationOptions.AccessDeniedRoute = "/access-denied";
// navigationOptions.CustomNavigationService = new YourCustomNavigationService();
});Localisation
DwsLocalizationOptions adds your own translation files. The library's English and German strings are always included.
builder.Services.AddDWSComponentLibraryServicesServer(configureLocalization: localizationOptions =>
{
localizationOptions.LocalizationFiles = new List<DwsLocalizationFileEntry>
{
new DwsLocalizationFileEntry { LanguageCode = "en-US", Path = "Localization/consumer_en.xml", FormatTypeKey = "xml" },
new DwsLocalizationFileEntry { LanguageCode = "de-DE", Path = "Localization/consumer_de.xml", FormatTypeKey = "xml" }
};
localizationOptions.FallbackLanguage = "en-US";
});More file formats: implement IDwsLocalizationFileLoader (its FormatType matches the FormatTypeKey of a file entry) and add it to FileLoaders. Loaders for XML, JSON and CSV are built in.
// MyYamlFileLoader implements IDwsLocalizationFileLoader with FormatType = "yaml"
localizationOptions.FileLoaders.Add(new MyYamlFileLoader());Logging
DwsLoggerOptions sets the log level and the logger providers. AddILoggerToDwsLoggerServiceAdapter() also sends ILogger<T> output to them.
builder.Services.AddDWSComponentLibraryServicesServer(configureLogger: loggerOptions =>
{
loggerOptions.GlobalLogLevel = LogLevel.Information;
loggerOptions.LogJavaScriptInterop = true;
loggerOptions.LogJavaScript = true;
loggerOptions.DwsLoggerProviders = new List<IDwsLoggerService>
{
new DwsDebugLogger(),
// more providers as needed
};
});
builder.Services.AddILoggerToDwsLoggerServiceAdapter();Haptic feedback
Haptic feedback is off by default. DwsHapticOptions.Enabled switches it on at start-up; IDwsHapticService.SetEnabled switches it at run time, for example from a settings page. Android vibrates, iOS Safari plays the system tick, other platforms and reduced motion play nothing.
builder.Services.AddDWSComponentLibraryServicesServer(configureHaptics: hapticOptions =>
{
hapticOptions.Enabled = true;
});
// at run time, e.g. from a settings page:
// @inject IDwsHapticService Haptics
// Haptics.SetEnabled(userWantsHaptics);