Skip to main content

Digging through SignalR - Command Line Arguments

SignalR contains a console application that can be used to make stress tests. The solution that was used to parse the command parameters was ‘cmdline – Command Line Parser’. This is a pretty nice library that can be installed using NuGet. This command line parses works perfectly, this is why the last time when it was updated in in September 2012.
Beside this solution, you can find another solution on Codeplex and github called very similar “Command Line Parser Library”. Both solutions are great and resolve the same problem in a very similar way. First time when I saw this two solutions I could swear that are the same solution (from the available API).
I saw a lot of projects, where people started to implement their own arguments parsers, even if we have plenty of them on the marker. It is not so important what command line parser you use it, as long you use it and don’t rewrite it again and again. In general, the use cases that we need to support are pretty simple and are covered by almost all the current solutions.

Because I prefer Command Line Parser library, I will present this one. I’m a fan of it because this stack is available from 2009 and it is still updated and maintained. This is a key feature of any framework.
When you are using this stack you have the possibility to declare a class that will represent the parameters that are send by the user to you. Each input argument from the console application can be mapped to a property of the class. In this way, it will be pretty easily to check what arguments were introduce by the user, what is the value and so on.
This mapping between input arguments and your class property is made through attributes. There is a base attribute called ‘Option’ that is used in most common cases. For each attribute you have the ability to set a normal name of the option and also a short name. For example you can have an argument that has the full name ‘help’ and a short name called ‘?’ (for power user).
protected class MyFooOptions
{
  [Option("c", "copy", Required = true, HelpText = "Copy file.")]
  public bool Copy { get; set; }

  [Option("d", "delete", DefaultValue = false, HelpText = "Delete file.")]
  public bool Delete { get; set; };

  [Option(null, "input", HelpText = "Location of input file.")]
  public string InputFilePath { get; set; };
}
For each argument we have the ability to specify if the argument is optionality or required. When we set the ‘HelpText’ property we will have the ability to generate automatically the help legend for all arguments without needing to format it and so on. The only thing that we need to do is to use ‘HelpText’ class that can render automatically our help messages pretty nice.
[HelpOption]
public string GetHelp()
{
    HelpText help = new HelpText {
        Heading = new HeadingInfo("<>", "<>"),
        AdditionalNewLineAfterOption = true,
        AddDashesToOption = true };
    help.AddPreOptionsLine("<>");

    // Add our options.
    help.AddOptions(this);
    return help;
  }
To be able to parse the input arguments and map them to our class we need to call the following method:
MyFooOptions myOpt = new MyFooOptions();
ICommandLineParser parser = new CommandLineParser();
parser.ParseArguments(args, myOpt)
Magic.
Other features are supported like having a list of items for a specific option or specify a method that will be used when the user wants to access the help.
protected class MyFooOptions
{
  [Option("c", "copy", Required = true, HelpText = "Copy file.")]
  public bool Copy { get; set; }

  [Option("d", "delete", DefaultValue = false, HelpText = "Delete file.")]
  public bool Delete { get; set; };

  [Option(null, "input", HelpText = "Location of input file.")]
  public string InputFilePath { get; set; };

  [OptionList("inputlist", "inputlist", Separator = ',', HelpText = "List of files.")]
  public IList<string> InputList { get; set; };
}
The last thing that I like to this solution is ‘ValueListAttribute’. This attribute is useful when user start to enter or use arguments that are not mapped. In this case, we can have a property of type lList<string> where all this arguments will be added. We can process this list if we want or we can ignore it.
protected class MyFooOptions
{
  [Option("c", "copy", Required = true, HelpText = "Copy file.")]
  public bool Copy { get; set; }

  [Option("d", "delete", DefaultValue = false, HelpText = "Delete file.")]
  public bool Delete { get; set; };

  [Option(null, "input", HelpText = "Location of input file.")]
  public string InputFilePath { get; set; };

  [OptionList("inputlist", "inputlist", Separator = ',', HelpText = "List of files.")]
  public IList<string> InputList { get; set; };

  [ValueList(typeof(List<string>), MaximumElements = 10)]
  public IList<string> Items { get; set; };
}
Cases like missing required options are already managed by this solution. Of course you can set custom behavior to it.

Enjoy!

Comments

Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.
publ…