-
Notifications
You must be signed in to change notification settings - Fork 0
Validate argument value before command execution
From version 0.2.0, it is possbile to write custom valdators for arguments. This page shows how to:
- write custom value validators
- use the
IValueValidator
interface - use the
ValueValidator
attribute - use this feature in a practice with a simple program
Before version 0.2.0, InterAppConnector is only able to check if the value digited by the user can be assigned to an argument, but there is not a way to define the value that are considered valid for that particular argument before the command execution (except for enumerations). For example, in version 0.1.0 if you want to define an argument called score
that can accept a value between 0 and 100 you have to write something like te code below
public string Main(DataModel arguments)
{
string scoreResult = CommandOutput.Ok("The score is " + arguments.Score);;
if (arguments.Score > 100)
{
scoreResult = CommandOutput.Error("Please insert a value between 0 and 100");
}
return scoreResult;
}
From version 0.2.0, it is possible to control the value inserted before the command execution. There is a new interface called IValueValidator
that must contain the validation code and a new attribute called ValueValidator
that must be assigned to the property associated to the argument to validate.
First of all, write a class that implements the IValueValidator
interface. This interface has two methods that must be implemented:
-
GetSampleValidValue()
returns an valid value for that specific argument -
ValidateValue(object)
is the method that checks if the value is correct or not. InterAppConnector passes the value inserted by the user as arguments and the method must return a boolean, and in particulartrue
if the value is correct, otherwisefalse
.
So, if you want to validate the score defined above and you want to use the validator feature, you have to write something like the code below
public class ScoreValidator : IValueValidator
{
public object GetSampleValidValue()
{
return 52;
}
public bool ValidateValue(object value)
{
bool isValid = true;
if ((uint) value > 100)
{
isValid = false;
}
return isValid;
}
}
Then, you can assign the custom validator to the ValueValidator
attribute. This attribute must be assigned to the property you want to validate. ValueValidator
accepts as paramter the type of the validator, so in this case if you want to use the validator created above you can write for instance the code below
[ValueValidator(typeof(ScoreValidator))]
public uint Score { get; set; }
The library will throw a TypeMismatchException
exception if you assign a type that does not have an IValueValidator
interface as paramter of the ValueValidator
attribute.
After that, you don't have to validate the value in your command. InterAppConnector will do the validation before the command execution. If the validator returns true
, the command is execute. So you can simply write the code below in your command
public string Main(DataModel arguments)
{
return CommandOutput.Ok(arguments.Score);
}
If you try to execute the command with a wrong value, for example 150, you will have this error and the command will not be executed
[10/12/2023 19:38:18] ERROR (3) : The value provided to argument score is not valid according to the validation procedure
The error mentioned above may not be very useful for a customer. For this reason, from version 0.3.0, InterAppConnector provides the possiblity to define custom errors in order to give useful feedbacks and user friendly errors. In order to do this, you have to throw an exception in the validator code. You can choose the exception to be thrown.
Let's assume that we want to inform the user that the value must be between 0 and 100. Edit the ScoreValidator
class written above in this way
public class ScoreValidator : IValueValidator
{
public object GetSampleValidValue()
{
return 52;
}
public bool ValidateValue(object value)
{
bool isValid = true;
if ((uint) value > 100)
{
throw new Exception("The value must be a number between 0 and 100");
}
return isValid;
}
}
In this example, you are creating the example mentioned above from scratch
For this example it is assumed that you have learned what is a command and how to implement it. Follow these steps to complete this example:
-
Open Visual Studio, create a blank solution and name it ScoreValidator. Choose the language version (.NET 6 or above) and choose a location for your solution (for example C:\SampleProjects)
-
Create a new library project and call it ScoreValidator.Library. Then follow the steps below to complete the class library
-
Add the InterAppConnector library as project reference
-
Add two files to the project and call it DataModel.cs and ScoreValidator.cs. Replace the content of the ScoreValidator.cs file with the code below
using InterAppConnector.Interfaces; namespace ScoreValidator.Library { public class ScoreValidator : IValueValidator { public object GetSampleValidValue() { return 52; } public bool ValidateValue(object value) { bool isValid = true; if ((uint) value > 100) { isValid = false; } return isValid; } } }
-
Replace the content of DataModel.cs with the code below
using InterAppConnector.Attributes; namespace ScoreValidator.Library { public class DataModel { [ValueValidator(typeof(ScoreValidator))] public uint Score { get; set; } } }
-
Rename Class1.cs to GetScoreCommand.cs
-
Replace the content of GetScoreCommand.cs with the code below
using InterAppConnector; using InterAppConnector.Attributes; using InterAppConnector.Interfaces; namespace ScoreValidator.Library { [Command("getscore", Description = "Get the score")] public class GetScoreCommand : ICommand<DataModel> { public string Main(DataModel arguments) { return CommandOutput.Ok(arguments.Score); } } }
-
-
Create a new console application project and name it ScoreValidator.CLI. Then follow the steps below to complete the console application:
-
Add the InterAppConnector library as project reference
-
Add the UserManager.Library project as project reference
-
Replace the content of Program.cs with the code below (
CommandManager
andInterAppConnector
are explained in detail in Integration with console applications page)using InterAppConnector; using ScoreValidator.Library; namespace ScoreValidator.CLI { internal class Program { static void Main(string[] args) { CommandManager manager = new CommandManager(); manager.AddCommand<GetScoreCommand, DataModel>(); InterAppCommunication comminucation = new InterAppCommunication(manager); comminucation.ExecuteAsInteractiveCLI(args); } } }
-
-
Build the solution (you can leave the debug mode if you want)
-
Open the Command Prompt and go to the location of the executable. For instance, if you have placed your solution in C:\SampleProjects you can go to the executable by typing the above command
cd C:\SampleProjects\ScoreValidator\ScoreValidator.CLI\bin\Debug\net6.0
-
Type the executable name with the extension (for instance ScoreValidator.CLI.exe). You should see an output similar to the one below
----------------------------------------------------------------------------------------------------------------------- ScoreValidator.CLI 1.0.0.0 ----------------------------------------------------------------------------------------------------------------------- Available actions: - getscore Get the score -score (required) : No description provided
As you can see the argument
name
is mandatory for thecreate
command and optional for thedelete
one. Ignore the parameter description for the moment -
Define a wrong value for the score, for example 150. Type ScoreValidator.CLI.exe getscore -score 150. You should have an error mesaage like the one below
[10/12/2023 20:53:21] ERROR (3) : The value provided to argument score is not valid according to the validation procedure
-
Now type a correct value for the argument. Type ScoreValidator.CLI.exe getscore -score 60. You should have an error mesaage like the one below
[10/12/2023 20:55:01] SUCCESS (0) : 60
- Getting started
- Create Commands
- Manage arguments
- Argument basics
- Shared arguments between different commands
- Argument aliases
- Argument description
- Exclude an argument from argument list
- Use enumerations as argument
- Use objects and structs as argument type
- Validate argument value before command execution
- Customize the command example in command help
- Define rules