Skip to content

rosslight/Darp.Utils

Repository files navigation

Darp.Utils

Test (and publish) License

This repository bundles all open source c# helper modules of 'rosslight GmbH'. To extend, add a new project and test project.

Darp.Utils.Assets

NuGet Downloads

A collection of simple interfaces for app assets targeting desktop apps.

Currently implemented:

  • FolderAssetsService: Read or write to a specific folder DI extensions provide helpers for ApplicationData, ProgramData, and the App's BaseDirectory
  • EmbeddedResourceAssetsService: Read files marked as EmbeddedResource of a specific Assembly
  • MemoryAssetsService: InMemory service that can be used for testing

When using DI, it is possible to retrieve the following services:

  • IAssetsFactory: A factory which is able to retrieve named asset services
  • IReadOnlyAssets: The base interface which provides readonly access to your assets
  • IAssetsService: A writable view on your assets, extends IReadOnlyAssets
  • IFolderAssetsService: A writable view on your assets with helpers specific to a directory

Named asset services:

  • Supports registration of multiple different asset services
  • Retrieval via IAssetFactory by supplying the name

Example:

// Add EmbeddedResources and AppData assets to the DI Container
ServiceProvider provider = new ServiceCollection()
    .AddAppDataAssetsService(relativePath: "RelativePath")
    .AddEmbeddedResourceAssetsService(name: "AssemblyResources", typeof(Test).Assembly)
    .BuildServiceProvider();

// Example read and write operations with the app data
IAssetsService service = provider.GetRequiredService<IAssetsService>();
await service.SerializeJsonAsync("test.json", new Test("value"));
Test deserialized = await service.DeserializeJsonAsync<Test>("test.json");
await service.WriteTextAsync("test2.txt", "some content");

// Retrieve a named assets service and copy an embedded resource to the app data
IAssetsFactory factory = provider.GetRequiredService<IAssetsFactory>();
IReadOnlyAssetsService resourceService = factory.GetReadOnlyAssets("AssemblyResources");
await resourceService.CopyToAsync("test.json", service, "test.json");

file sealed record Test(string Prop1);

Darp.Utils.Configuration

NuGet Downloads

A writable configuration service. Can be registered using DI and injected into target services. Usage might include reading, writing and listening to changes via the INotifyPropertyChanged interface.

Example:

ServiceProvider provider = new ServiceCollection()
    .AddAppDataAssetsService("RelativePath")
    .AddConfigurationFile<TestConfig>("config.json")
    .BuildServiceProvider();

ConfigService<TestConfig> service = provider.GetRequiredService<ConfigService<TestConfig>>();
TestConfig config = await service.LoadConfigAsync(() => new TestConfig());
await service.UpdateConfigAsync(config => config with { Setting = "NewValue" });

Darp.Utils.Dialog

NuGet Downloads

A lightweight dialog service which allows for opening dialogs from the ViewModel.

Implementation Description
NuGet Implementation based on FluentAvalonia

Example:

ServiceProvider provider = new ServiceCollection()
    .AddSingleton<IDialogService, AvaloniaDialogService>()
    .BuildServiceProvider();

IDialogService dialogService = provider.GetRequiredService<IDialogService>();
// Specify the Type of the dataContext of the window the dialog is supposed to be shown on
//    .WithDialogRoot<MainWindowViewModel>()
await dialogService.CreateMessageBoxDialog("Title", "Message").ShowAsync();

// Assumes you have registered a view for 'SomeViewModel' in a ViewLocator
// Works with any kind of content
var viewModel = new SomeViewModel();
await dialogService.CreateContentDialog("Title", viewModel)
    .SetDefaultButton(ContentDialogButton.Primary)
    .SetCloseButton("Close")
    .SetPrimaryButton("Ok", onClick: model => model.IsModelValid)
    .ShowAsync();

Darp.Utils.Avalonia

NuGet Downloads

A collection of classes and methods to help reduce the boilerplate when working with Avalonia. These contain:

  • ViewLocatorBase: Resolve views at compile-time
  • UserControlBase, WindowBase: Add a ViewModel property to have typed access to the DataContext
  • AvaloniaHelpers: A collection of helper methods

Darp.Utils.ResxSourceGenerator

NuGet Downloads

A source generator for generating strongly typed singleton resource classes from .resx files. Additional documentation here.

Darp.Utils.TestRail

NuGet Downloads

A library allowing for communication with a TestRail instance in a easy and modern way.

Core features:

  • Modern: Build on the latest .Net technologies. NativeAot compatible
  • Extensible: ITestRailService is the core with a bunch of extension methods defining the actual API
  • Testable: Operates purely on the interface ITestRailService which can be mocked easily

Getting started:

var service = TestRailService.Create("https://[your-organization].testrail.io", "username", "passwordOrApiKey");
var projectsEnumerable = service.GetProjects(ProjectsFilter.ActiveProjectsOnly);
await foreach (var project in projectsEnumerable)
{
    var casesEnumerable = service.GetCases(project.Id);
}
var caseResponse = await service.GetCaseAsync((CaseId)1);
var customProperty = caseResponse.Properties["custom_property"].GetString();
await service.UpdateCase(new UpdateCaseRequest { CaseId = caseResponse.Id, Title = "New Title" });

Extension methods:

public static async Task<GetCaseResponse> GetCaseAsync(this ITestRailService testRailService, CaseId caseId)
{
    var jsonTypeInfo = YourSourceGenerationContext.Default.GetCaseResponse;
    return await testRailService.GetAsync($"/get_case/{(int)caseId}", jsonTypeInfo, default(cancellationToken));
}

Usage with IHttpClientFactory for http client caching:

var provider = new ServiceCollection()
    .AddHttpClient("TestRailClient", (provider, client) =>
        {
            client.BaseAddress = new Uri("https://[your-organization].testrail.io");
            var authBytes = Encoding.UTF8.GetBytes("username:passwordOrApiKey");
            var base64Authorization = Convert.ToBase64String(authBytes);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64Authorization);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
        })
    .AddSingleton<ITestRailService>(provider => new TestRailService<IHttpClientFactory>(
        provider.GetRequiredService<IHttpClientFactory>(),
        factory => factory.CreateClient("TestRailClient"),
        NullLogger.Instance))
    .BuildServiceProvider();
var service = provider.GetRequiredService<ITestRailService>();

Darp.Utils.SimpleArgumentParser

NuGet Downloads

A simple argument parser for command line applications. Provides a simple, typed syntax for parsing command line arguments without a complex CLI configuration.

It was created to have a simple argument parser that can be used for example scripts or single-command CLIs.

Features:

  • Positional arguments
  • Named arguments (options)
  • Flags (store_true)
  • Required/default values
  • AOT/trimming friendly

No goals:

How to use:

By default, every type that implements ISpanParsable can be parsed automatically. Other types have to provide a manual parser. After parsing, the values can be resolved from the ParseResult object. Optional arguments return nullable values.

var parser = new ArgumentParser();
Argument<string> myNameArgument = parser.AddRequiredPositional<string>("myName");
OptionalArgument<int> myAgeArgument = parser.AddPositional<int>("myAge");
Argument<bool> isVerboseArgument = parser.AddFlag("--verbose");
Argument<Size> isAwesomeArgument = parser.AddNamed("--size", parser: ArgumentParsers.TryParseEnumIgnoreCase, defaultValue: Size.Medium);
OptionalArgument<bool> livesInEuropeArgument = parser.AddNamed<bool>("--livesInEurope", parser: static (value, _, out result) =>
{
    if (value is "y" or "yes")
    {
        result = true;
        return true;
    }
    result = false;
    return false;
});

ParseResult result = parser.ParseOrExit(args);

string myName = result.GetValue(myNameArgument);
int? myAge = result.GetValue(myAgeArgument);
bool isVerbose = result.GetValue(isVerboseArgument);
Size isAwesome = result.GetValue(isAwesomeArgument);
bool? livesInEurope = result.GetValue(livesInEuropeArgument);

public enum Size
{
    Small,
    Medium,
    Large,
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages