Skip to content

Exclude an argument from argument list

Giuseppe Cramarossa edited this page Dec 15, 2023 · 2 revisions

This page describes how to exclude an argument from commands. In particolar you will find details regarding

  • the ExcludeItemFromCommand attribute
  • an example that shows how to use this attribute

The ExcludeItemFromCommand attribute

In arguments basics page, it is suggested that you create a dedicated class for your arguments. However, there may be a case when you don't want to expose all public properties and transform them in arguments that can be set by the user. In this case, InterAppConnector provides an attribute, ExcludeItemFromCommand, that permits to exclude the property from argument list.

In order to use it, add the attribute in your property as showed below

[ExcludeItemFromCommand]
public string Name {get; set;}

You can place this attribute wherever you want when you declare attributes in your property, but be aware that all attributes handled by InterAppConnector will be ignored.

Example

In this example, you are creating a simple user management application that has two commands

  • CreateUserCommand
  • DeleteUserCommand

These commands have two arguments:

  • usercode : contains the user code. This argument is mandatory for both commands
  • name : contains the user name. This argument is mandatory in user creation and mandatory in user deletion.

For this example you are using Visual Studio 2022 and you are creating:

  • A project library that contains the commands and a file containing the arguments necessary to run the application
  • A console application that will be used to call the command via cli

For this example it is assumed that you have learned what is a command and how to implement it

For simplicity, you will use the previous example and you will set the FileLocation property in the code

Follow these steps to complete this example:

  1. Open Visual Studio, create a blank solution and name it UserManager. Choose the language version (.NET 6 or above) and choose a location for your solution (for example C:\SampleProjects)

  2. Create a new library project and call it UserManager.Library. Then follow the steps below to complete the class library

    1. Add the InterAppConnector library as project reference

    2. Add a file to the project and call it UserManagerDataModel.cs

    3. Replace the content of UserManagerDataModel.cs with the code below

      namespace UserManager.Library
      {
          public class UserManagerDataModel
          {
              public string UserCode { get; set; } = string.Empty;
              public string FileLocation { get; set; } = string.Empty;
              public string Name { get; set; }
          }
      }
    4. Rename Class1.cs to CreateUserCommand.cs and create a new file called DeleteUserCommand.cs. Change the visibility in the classes from internal to public

    5. Replace the content of UserManagerDataModel.cs with the code below

      using InterAppConnector.Attributes;
      
      namespace UserManager.Library
      {
          public class UserManagerDataModel
          {
              public string UserCode { get; set; } = string.Empty;
      
              [ExcludeItemFromCommand]
              public string FileLocation { get; set; } = @".\addressbook.txt";
      
              [MandatoryForCommand(typeof(CreateUserCommand))]
              public string Name { get; set; }
          }
      }
    6. Replace the content of CreateUserCommand.cs with the code below

      using InterAppConnector;
      using InterAppConnector.Attributes;
      using InterAppConnector.Interfaces;
      using System.Text.RegularExpressions;
      
      namespace UserManager.Library
      {
          [Command("create", Description = "Create a user in a file")]
          public class CreateUserCommand : ICommand<UserManagerDataModel>
          {
              public string Main(UserManagerDataModel arguments)
              {
                  string message = "";
                  bool userAlreadyExists = false;
      
                  if (Regex.IsMatch(arguments.UserCode, @"^[a-z0-9]+$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(1000))
                      && Regex.IsMatch(arguments.Name, @"^[a-z ]+$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(1000)))
                  {
                      if (File.Exists(arguments.FileLocation))
                      {
                          List<string> userList = new List<string>(File.ReadLines(arguments.FileLocation));
                          int rowsFound = (from item in userList
                                          where item.ToLower().StartsWith(arguments.UserCode.ToLower() + ",")
                                          select item).Count();
      
                          if (rowsFound > 0)
                          {
                              userAlreadyExists = true;
                          }
                      }
      
                      if (userAlreadyExists)
                      {
                          message = CommandOutput.Warning("The user code already exists. No row was added");
                      }
                      else
                      {
                          File.AppendAllText(arguments.FileLocation, arguments.UserCode.Trim() + "," + arguments.Name + Environment.NewLine);
                          message = CommandOutput.Ok("The user was added to the list");
                      }
                  }
                  else
                  {
                      message = CommandOutput.Error("The user code or the name contains invalid characters.\nPossible causes:\n-user code contain other characters than letter and numbers\n-name contains other characters other than letters and spaces");
                  }
      
                  return message;
              }
          }
      }
    7. Replace the content of DeleteUserCommand.cs with the code below

      using InterAppConnector;
      using InterAppConnector.Attributes;
      using InterAppConnector.Interfaces;
      using System.Text.RegularExpressions;
      
      namespace UserManager.Library
      {
          [Command("delete", Description = "Delete a user in a file")]
          public class DeleteUserCommand : ICommand<UserManagerDataModel>
          {
              public string Main(UserManagerDataModel arguments)
              {
                  string message = "";
      
                  if (Regex.IsMatch(arguments.UserCode, @"^[a-z0-9]+$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(1000)))
                  {
                      if (File.Exists(arguments.FileLocation))
                      {
                          string name = "";
                          bool isNameValid = true;
                          List<string> userList = new List<string>(File.ReadLines(arguments.FileLocation));
                          List<string> rowsFound = new List<string>();
      
                          if (!string.IsNullOrEmpty(arguments.Name))
                          {                    
                              if (Regex.IsMatch(arguments.Name, @"^[a-z ]+$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(1000)))
                              {
                                  name = arguments.Name;
                                  rowsFound = (from item in userList
                                              where item.ToLower() == arguments.UserCode.ToLower() + "," + name.ToLower()
                                              select item).ToList();
                              }
                              else
                              {
                                  isNameValid = false;
                              }
                          }
                          else
                          {
                              rowsFound = (from item in userList
                                          where item.ToLower().StartsWith(arguments.UserCode.ToLower() + ",")
                                          select item).ToList();
                          }
      
                          if (isNameValid)
                          {
                              
                              if (rowsFound.Count > 0)
                              {
                                  userList.Remove(rowsFound[0]);
                                  File.WriteAllLines(arguments.FileLocation, userList);
                                  message = CommandOutput.Ok("User deleted successfully");
                              }
                              else
                              {
                                  message = CommandOutput.Warning("The user does not exist. No rows was deleted");
                              }
                          }
                          else
                          {
                              message = CommandOutput.Error("The name contains invalid characters. Only letters and spaces are allowed");
                          }
      
                      }
                      else
                      {
                          message = CommandOutput.Error("The file does not exist");
                      }
                  }
                  else
                  {
                      message = CommandOutput.Error("The user code contains invalid characters. Only letters and numbers are allowed");
                  }
      
                  return message;
              }
          }
      }
  3. Create a new console application project and name it UserManager.CLI. Then follow the steps below to complete the console application:

    1. Add the InterAppConnector library as project reference

    2. Add the UserManager.Library project as project reference

    3. Replace the content of Program.cs with the code below (CommandManager and InterAppConnector are explained in detail in Integration with console applications page)

      using InterAppConnector;
      using UserManager.Library;
      
      namespace UserManager.CLI
      {
          public class Program
          {
              static void Main(string[] args)
              {
                  CommandManager commandManager = new CommandManager();
                  commandManager.AddCommand<CreateUserCommand, UserManagerDataModel>()
                      .AddCommand<DeleteUserCommand, UserManagerDataModel>();
      
                  InterAppCommunication interAppCommunication = new InterAppCommunication(commandManager);
                  interAppCommunication.ExecuteAsInteractiveCLI(args);
              }
          }
      }
  4. Build the solution (you can leave the debug mode if you want)

  5. 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\UserManager\UserManager.CLI\bin\Debug\net6.0
  6. Type the executable name with the extension (for instance UserManager.CLI.exe). You should see an output similar to the one below

    ----------------------------------------------------------------------------------
    
    UserManager.CLI 1.0.0.0
    
    ----------------------------------------------------------------------------------
    
    Available actions:
    
    - create
    Create a user in a file
            -usercode (required) : No description provided
            -name (required) : No description provided
    
    - delete
    Delete a user in a file
            -usercode (required) : No description provided
            -name (optional) : No description provided

    As you can see the argument name is mandatory for the create command and optional for the delete one. Ignore the parameter description for the moment

  7. Create a new user and try to not define the name. For instance, type UserManager.CLI.exe create -usercode john. You should see this error

    [22/10/2023 17:19:45] ERROR (3) : Cannot execute the selected action because some mandatory parameters are missing. Missing parameters: name
    - create
    Create a user in a file
           -usercode (required) : No description provided
           -name (required) : No description provided
  8. Now type all required parameters (for instance type UserManager.CLI.exe create -usercode john -filelocation ".\users.csv" -name John). You should see a success message like the message below

    [22/10/2023 17:31:27] SUCCESS (0) : The user was added to the list
  9. Now let's try to delete the user without using the optional parameter. Type UserManager.CLI.exe delete -usercode john -filelocation ".\users.csv" and press enter. You should see a message like the one below

    [22/10/2023 19:47:50] SUCCESS (0) : User deleted successfully

Note that the value assigned to -filelocation via CLI is ignored