Simple.BotUtils 1.5.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package Simple.BotUtils --version 1.5.1                
NuGet\Install-Package Simple.BotUtils -Version 1.5.1                
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="Simple.BotUtils" Version="1.5.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Simple.BotUtils --version 1.5.1                
#r "nuget: Simple.BotUtils, 1.5.1"                
#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 Simple.BotUtils as a Cake Addin
#addin nuget:?package=Simple.BotUtils&version=1.5.1

// Install Simple.BotUtils as a Cake Tool
#tool nuget:?package=Simple.BotUtils&version=1.5.1                

.NET

NuGet

Simple.BotUtils

Some Bots Utilities containing common features such as Dependency Injection, Job Scheduler, MemoryCache and Argument Parser

Lightweight, simple, compatible, and depends only Newtonsoft.Json.

Works for small projects in any platform (see compatibility list)

Compatibility List:

Direct targets:

  • Net Core 3.1, and 2.1
  • Net Standard 1.0*, and 2.0
  • Net 6.0 (and 5.0)
  • Net Framework 4.0, 4.5, 4.6.1, 4.7.2, and 4.8

Indirect Support from Net Standard 2.0:

  • Net Core 2.0+
  • Net Framework 4.6.1+
  • Mono 5.4+
  • Xamarin.iOS 10.14+
  • Xamarin.Android 8.0+
  • UWP 10.0.16299+
  • Unity 2018.1

Dependency Injection

Simple Dependency Injection implementation supporting Singleton and Transient

Singleton are objects instantiated once and reused for the entire application life-time

Setup the object tasker as Scheduler

  var scheduler = new Scheduler();
  Injector.AddSingleton<Scheduler>(scheduler);

Retrieving the scheduler object previous instantiated

  var scheduler = Injector.Get<Scheduler>();

Transient are objects re-created for every use

Setup the class Config setting up a Func to create a new instance

  Injector.AddTransient<Config>(() => Config.Load());

Retrieve a new instance for each use

  using(Config cfg = Injector.Get<Config>()){
    // Do stuff
  }

Endpoint-like controllers

A simple mechanism for endpoint creation similar to ASP.net controllers with DI support

Create some endpoints

public class MyMethods : IController
{
  public void ShowInfo(string info) => Console.WriteLine(info);
  public void ShowNumber(int number) => Console.WriteLine(number);
  public void ShowDouble(double number) => Console.WriteLine(number);
}

and then easily call them

ctrl.Execute("ShowInfo", "Bla bla bla bla");
ctrl.Execute("ShowNumber", "42"); // string
ctrl.Execute("ShowNumber", 42); // Native
ctrl.Execute("ShowDouble", "42.42"); // string
ctrl.Execute("ShowDouble", 42.42); // Native

Each controller is an instance allowing multiple clusters of endpoints or what is sometimes called "namespace" (A kind of "route")

Is possible to parse the entire text from a Bot or external access command line

string message = "ShowCallerInfo \"Bla bla bla bla\"";
ctrl.ExecuteFromText(message);

In addition to DI support, is possible to pass Context values when calling ExecuteFromText

public void ShowCallerInfo(int contextParam, string textParams, [FromDI] MyConfig cfg)
          => Console.WriteLine($"ShowCallerInfo[{contextParam}] {textParams}");

Then called by

ctrl.ExecuteFromText(context: 42, text: message);

Command-Line parser

A simple parser for program arguments

Allows access and selection with an Argument object, a dictionary or a NameValueCollection

Is also possible to map the arguments to an Object/Class

Read arguments as a Dictionary

  // argument access
  public static void Main(string[] args)
  {
    // app.exe -a AA --bb BBBB cccc
    var arguments = ArgumentParser.Parse(args);
    ...
    var a = arguments.Get("-a"); // "AA"
    var bb = arguments.Get("--bb"); // "BBBB"
    // Only one [Empty/""] is allowed
    var empty = arguments.Get(""); // "cccc"
  }

Create a class with the arguments

  // app.exe -n Name --number 12345
  public static void Main(string[] args)
  { 
    var data = Startup.ArgumentParser.ParseAs<MyData>(args);
    ...
  }
  class MyData{
    [Startup.ArgumentKey("-n", "--name")]
    public string MyName { get; set; }
    [Startup.ArgumentKey("-nb", "--number")]
    public int MyInt { get; set; }
  }

// Fill an existing class with arguments

  // app.exe -n Name --number 12345
  public static void Main(string[] args)
  { 
    // Load existing configuration
    var cfg = ConfigBase.Load<Config>("config.xml");
    // Update config with arguments, if any
    if (args.Length > 0)
    {
        ArgumentParser.ParseInto(args, cfg);
        // and save to next boot
        cfg.Save();
    }
    ...
  }
  class Config : ConfigBase{
    [Startup.ArgumentKey("-n", "--name")]
    public string MyName { get; set; }
    [Startup.ArgumentKey("-nb", "--number")]
    public int MyInt { get; set; }
  }

Job/Task Scheduler

Execute timed jobs in pré-defined intervals

Create jobs

  class PingJob : IJob
  {
    public bool CanBeInvoked { get; set; } = false;
    public bool CanBeScheduled { get; set; } = true;
    public bool RunOnStartUp { get; set; } = false;
    public TimeSpan StartEvery { get; set; } = TimeSpan.FromSeconds(30);

    public async Task ExecuteAsync(ExecutionTrigger trigger, object parameter)
    {
        var ping = new System.Net.NetworkInformation.Ping();
        await ping.SendPingAsync("localhost");
    }
  }

Setup the scheduler

  // create a scheduler
  var scheduler = new Scheduler();
  // All your tasks
  scheduler.Add<PingJob>(new PingJob());

  // This method will block execution
  scheduler.RunJobsSynchronously(cancellationToken);

Memory Caching

A simple and versatile Memory Caching class, supports renew based on LastAccess and LastWrite

  var cache = new MemoryCache();
  // Setup a cache that expires only if not accessed for 1 hour
  cache.Add("cache-key", new CacheOptions()
  {
      ExpirationPolicy = ExpirationPolicy.LastAccess,
      ExpirationValue = TimeSpan.FromHours(1),
      // Setup a update method
      UpdateCallback = () => db.Query<Data>(),
  });
  ...
  // For use, simply calls Get<T>("key")
  var data = cache.Get<Data[]>("cache-key");

Xml and Json Serialization

Not available in Net Standard 1.0

XmlSerializer

A Static class wrapped around .Net native XmlSerializer to load and save objects in Xml Files

JsonSerializer

A Static class wrapped around Newtonsoft Json to load and save objects in json Files

Saving file example:

var data = new Data();
...
XmlSerializer.ToFile("myData.xml", data);
JsonSerializer.ToFile("myData.json", data);

Loading from file or create a new instance

// load data or creates a new
var data = XmlSerializer.LoadOrCreate("myData.xml", new Data());
var data = JsonSerializer.LoadOrCreate("myData.json", new Data());

Test if a file exists and loads if it do exist

// load data or creates a new
if(XmlSerializer.TryLoadFile("myData.xml", out Data myData)){...}
if(JsonSerializer.TryLoadFile("myData.json", out Data myData)){...}

Sample project

See a bot example with dependency injection, configuration file, JobScheduler and a Telegram-bot interface

BotEngine

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 was computed.  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 was computed.  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. 
.NET Core netcoreapp1.0 was computed.  netcoreapp1.1 was computed.  netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 is compatible. 
.NET Standard netstandard1.0 is compatible.  netstandard1.1 was computed.  netstandard1.2 was computed.  netstandard1.3 was computed.  netstandard1.4 was computed.  netstandard1.5 was computed.  netstandard1.6 was computed.  netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net40 is compatible.  net403 was computed.  net45 is compatible.  net451 was computed.  net452 was computed.  net46 was computed.  net461 is compatible.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 is compatible.  net48 is compatible.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen30 was computed.  tizen40 was computed.  tizen60 was computed. 
Universal Windows Platform uap was computed.  uap10.0 was computed. 
Windows Phone wp8 was computed.  wp81 was computed.  wpa81 was computed. 
Windows Store netcore was computed.  netcore45 was computed.  netcore451 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos 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.6.5 125 9/24/2024
1.6.4 113 9/16/2024
1.6.3 232 3/26/2024
1.6.2 381 9/23/2023
1.6.1 561 1/31/2023
1.6.0 274 1/31/2023
1.5.5 421 8/7/2022
1.5.4 412 8/1/2022
1.5.3 381 7/29/2022
1.5.2 411 7/9/2022
1.5.1 432 7/3/2022
1.5.0 435 3/26/2022
1.4.3.4 411 3/14/2022
1.4.3.3 399 2/21/2022
1.4.3.2 447 2/17/2022
1.4.3.1 416 2/14/2022
1.4.3 428 2/13/2022
1.4.2 429 2/13/2022
1.4.1 440 2/12/2022
1.4.0 432 2/12/2022
1.3.8 288 12/7/2021
1.3.7 1,014 12/3/2021 1.3.7 is deprecated.
1.3.6 305 8/10/2021
1.3.5 393 6/6/2021
1.3.4 302 6/3/2021
1.3.3 355 5/29/2021
1.3.2 390 5/29/2021
1.3.1 373 5/29/2021
1.3.0 339 5/29/2021
1.2.2 486 5/22/2021
1.2.1 501 5/22/2021
1.1.2 310 5/19/2021
1.0.0 400 5/16/2021

See examples and documentation on the GitHub page
Paired with commit 94b0208
https://github.com/RafaelEstevamReis/Simple.BotUtils