FARENTAL.Utils 1.0.12

dotnet add package FARENTAL.Utils --version 1.0.12
NuGet\Install-Package FARENTAL.Utils -Version 1.0.12
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="FARENTAL.Utils" Version="1.0.12" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add FARENTAL.Utils --version 1.0.12
#r "nuget: FARENTAL.Utils, 1.0.12"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install FARENTAL.Utils as a Cake Addin
#addin nuget:?package=FARENTAL.Utils&version=1.0.12

// Install FARENTAL.Utils as a Cake Tool
#tool nuget:?package=FARENTAL.Utils&version=1.0.12

What's in this package?

  • Password validator - a password validator for Microsoft.AspNetCore.Identity.PasswordOptions
  • PostgresCache - A cache solution that store data in postgresql database
  • FirebasePush - A service for sending push notification via firebase
  • GoogleCaptchaService - A service to validate google captcha token
  • PostgresLogger - An ILogger provider to log messages to postgresql database
  • WkHtmlToPdfCommandBuilder - Convert HTML to PDF via wkhtmltopdf utility

Microsoft.AspNetCore.Identity.PasswordOptions.PasswordValidator(string password)

Validate the given password

PostgresCache

Cache using postgresql as data store. To use,

  1. add nuget package Npgsql.EntityFrameworkCore.PostgreSQL
  2. Create an instance of DbContextOptions
   var opt = new DbContextOptionsBuilder().UseNpgsql("host=localhost;database=db;user id=user;password=pwd").Options;
  1. Ensure database is exists
   await PostgresCache.EnsureCachedDbExistsAsync(opt);
  1. How to use example
   public Task<List<Customer>> GetCustomersFromDatabase()
   {
       // get customer from database
   }
   
   public async Task<Customer> GetCustomersAsync() 
   {
       var key = "customers";
       
       // get from cache, if not exist, call the method GetCustomersFromDatabase to get 
       // data and add to the cache and cache for 1 hour
       var customers = PostgresCache.Instance.GetOrCreate<List<Customer>>(
           key, 
           GetCustomersFromDatabase,
           TimeSpan.FromHours(1) );
       
       // return the customer
       return customers;
   }

FirebasePush

Send push notification via firebase.

To use in console app

// set the default options
FirebasePush.DefaultOptions = 
    new FirebaseOptions {
        ApplicationId = "aaaa",
        SenderId = "bbbb",
        DeviceToken = "xxxx"
    };
    
// send
var payload = new { message = "Hellow World!" };

FirebasePush.Instance.SendAsync(payload);

// send to a different device
var opt = FirebasePush.DefaultOptions with { DeviceToken = "yyyy" };

FirebasePush.Instance.SendAsync(payload, opt);

Google Captcha verification

To use in console app

// set default secret
GoogleCaptchaService.DefaultOptions.Secret = "abc";

// validate
await GoogleCaptchaService.Instance.EnsureValidCaptchaAsync("token", "client ip");

// if need to validate more than one captcha each with different secret then call this overload
await GoogleCaptchaService.Instance.EnsureValidCaptchaAsync("secret", "token", "client ip");

To use with Microsoft hosting dependency injection like ASP.NET Core

services.AddScoped<ICaptchaService,GoogleCaptchaService>();

Configure the options (not mandatory). Add this to appsettings.json

 "GoogleCaptcha": {
     "EndPointUrl": "https://www.google.com/recaptcha/api/siteverify",
     "Secret": "your captcha secret"
 }

Add this to ConfigureServices of your Startup class

services.Configure<GoogleCaptchaServiceOptions>(Configuration.GetSection("GoogleCaptcha"));

then call EnsureValidCaptchaAsync like this

await captchaService.EnsureValidCaptchaAsync("token","client ip");

PostgresLogger

To use with Microsoft hosting dependency injection like ASP.NET Core

  1. Add PostgresLogger section to the Logging section of your appsettings.json file like so
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "PostgresLogger": {
      "LogLevel": {
        "Default": "Debug",
        "Microsoft": "Information",
        "Your.Other.Namespace": "Trace"
      },
      "ConnectionString": "host=localhost;database=logs;user id=testuser;password=testuser",
      "EventId": [],
      "BufferSize": 10,
      "ApplicationName": "MyApp"
    }
  }
}

EventId - If you need to log only for specific event then add your the event ID to this list. BufferSize - Number of messages collect before write to database. ApplicationName - Name of the application send logs. Useful when multiple applications are sending logs to the same database.

  1. Add extension method AddPostgresLogger to CreateHostBuilder like below
public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logBuilder =>
                {
                    logBuilder.AddPostgresLogger();
                })
                .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
  1. Add extension method UsePostgresLogger to Configure method of your Startup class to flush all messages after every request like this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UsePostgresLogger();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
  1. Ensure that the database user has permission to create a database.

WkHtmlToPdfCommandBuilder

Requirements - wkhtmltopdf command line utility must be installed in the target machine

To install on MacOS:

brew install wkhtmltopdf

To install on Linux:

wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6.1-3/wkhtmltox_0.12.6.1-3.bullseye_amd64.deb
apt install -y ./wkhtmltox_0.12.6.1-3.bullseye_amd64.deb

Note - the above is for Debian 11 (bullseye) AMD 64bit. For other versions, see https://github.com/wkhtmltopdf/packaging/releases

Sample Usage

// html string as input
const string html = 
  """
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <title>Title</title>
  </head>
  <body>
  Test
  </body>
  </html>
  """;

var builder = new WkHtmlToPdfCommandBuilder();
var pdfFile = await builder
    .HeaderRight("Page [page] to [topage]")  // set the RHS of header to text e.g Page 1 of 3
    .HeaderLine(true)                        // draw line between header and content
    .Margin(30)                              // set margin to 30mm on all sides
    .Html(html)                              // set the html string as input
    .Url("https://www.google.com")           // set the url as input
    .ExecuteAsync();                         // execute the command
    
// result pdfFile should contains 2 pages, the first page is the html string and the second page is the google page
Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.12 205 12/16/2023
1.0.11 118 12/15/2023
1.0.10 109 12/15/2023
1.0.9 643 7/5/2021
1.0.4 392 6/20/2021
1.0.3 314 6/9/2021
1.0.2 333 6/9/2021
1.0.1 343 6/9/2021
1.0.0 340 6/9/2021