Table of Contents

Summary

In 4 steps we created a simple module, added settings with validation and learned how to receive/send messages. The code used in these steps is summarized below.


using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Crosser.EdgeNode.Flows.Models.Abstractions.Models;
using Crosser.EdgeNode.Common.Abstractions.Utilities.Validation;
using Crosser.EdgeNode.Flows;
using Crosser.EdgeNode.Flows.Abstractions;

namespace MyOrg.FlowModule.RandomNumberModule;

public class RandomNumberModule : FlowModule<RandomNumberModuleSettings>
{
    public override string UserFriendlyName => "Random Number";
    private readonly Random random = new();
    public RandomNumberModule() : base(FlowModuleType.Function) { }

    protected override async Task MessageReceived(IFlowMessage message)
    {
        // Generate random value based on settings
        var randomValue = this.random.Next(
            this.Settings.TargetMin,
            this.Settings.TargetMax);

        // Add value to message using the configured property name
        message.Set(this.Settings.TargetName, randomValue);

        // For now we just return null...
        // Pass the message to the next module(s) in the flow
        await this.Next(message);
    }
}

public class RandomNumberModuleSettings : FlowModuleSettings
{
    [Display(Name = "Minimum Value", Description = "The lowest value in the random range")]
    [DefaultValue(1)]
    [Range(1, 10000)]
    public int TargetMin { get; set; } = 1;

    [Display(Name = "Maximum Value", Description = "The highest value in the random range")]
    [DefaultValue(100)]
    [Range(1, 10000)]
    public int TargetMax { get; set; } = 100;

    [Display(Name = "Target Property", Description = "The property to store the random value in")]
    [DefaultValue("data")]
    [MinLength(1)]
    [MaxLength(64)]
    public string TargetName { get; set; } = "data";

    public override void Validate(SettingsValidator validator)
    {
        // Built-in validators
        validator.Validate(nameof(this.TargetMin), this.TargetMin)
            .MinValue(1)
            .MaxValue(10000);

        validator.Validate(nameof(this.TargetMax), this.TargetMax)
            .MinValue(1)
            .MaxValue(10000);

        validator.Validate(nameof(this.TargetName), this.TargetName)
            .NotNull()
            .MinLength(1)
            .MaxLength(64);

        // Custom validation logic
        if (this.TargetMin >= this.TargetMax)
        {
            validator.AddError(nameof(this.TargetMin),
                "Minimum value must be less than maximum value");
        }
    }
}

You can now build your module with

dotnet build .\MyOrg.FlowModule.RandomNumberModule.csproj

You should of course test your modules (see Testing Your Module), but if you are happy with it you can deploy your module to Crosser Cloud.

>> Deploy Your Module