Command & Conquer

Command-and-Conquer-Generals-Deluxe-Edition-for-OS-X-logo

Today’s post is a look @ a nuget package that has been around for a while (2005 to be exact) & is still commanding respect in the developer community.

If you find yourself developing a command line application that requires various input, maybe for the purpose of automating a process on your continuous integration pipeline or perhaps its just for simple input to get data into a system, chances being if you are writing this from scratch you will have spent a bit of time trying to ensure the user input is parsed correctly,  this can be time consuming right?

Well fear no more, the CommandLineParser library is here to the rescue.  CommandLineParser is, err..as the name suggests, a command line parser for .NET.  The API offers a nice array of features out of the box, one of the biggest ones being a help text guide for each of the inputs you specify which gives a bit of vavoom to your console app (not to mention relief for your end users).

A small example, we will create a console application that will display various command line parameter inputs to the screen.  This kind of application without using the nuget package might be a bit time consuming, as you would need to validate the inputs, etc etc.

Downloading the package from nuget (currently @ v2 at time of writing this post), you create a class, lets call it UserOptions and create a series of properties that will represent your command line parameter inputs such as Id, Name & Hobbies.  Next, you will add an attribute called Option above each of the properties as in the following screenshot (il explain this attribute further on):code_sample_1

Under the main method, apply the following API call like socode_sample_2.PNG

Both methods in the fluent calls, DisplayOptionsInputted & HandleParserError are displayed below – these are just methods that would perform the task required.code_sample_3.PNG

To see the application in action set the command line arguments like so in the project properties window & run the project:code_sample_4.PNG

And voila.. output to the console screen the inputs supplied from above:code_sample_5

If i pass in an unknown parameter like so:code_sample_7.PNG

This will trigger the .WithNotParsed() method to execute..the API out of the box will also display the Helper text as so (this can be overridden if required):code_sample_6.PNG

The Option attribute (set in the UserOptions class above) is one of the magic ingredients that will perform the out of the box validation for your parameters.  In the above i have applied some of the basic properties that can be used.

Interesting properties to set are HelpText which will be displayed when user specifies the built in parameter –help,  you also have different ways as to how you want the parameter parsed, for example if you want the input Name to be abbreviated to ‘n’ on the command line then you can do this by passing ‘n’ as per above.  If you don’t specify this the field will default to its original property name.  If a parameter is always needed as input then you can set it as Required=true, if you omit this parameter when running the app you will get error like following.. (specific error highlighted in yellow)code_sample_8

Pretty cool, right!   You can also pass in an enumerated list of items like strings and have it parse each of them via a seperator character like ‘:’, this can be applied using  Seperator=’:’ as can be seen in UserOptions example.

If you pass in a string value instead of a numeric type like for Id input above it will fail validation and display as so:code_sample_9.PNG

Nifty, i hear you say.  All of this is done with hardly any effort by the developer, all out of the box functionality which as Tony the Tiger would say is juust greeeat!

Finally, there is also another type of attribute setting you can apply if your console app deals with many commands which in turn have many arguments like the ones applied above which is called Verb.  Examples of this usage would be FTP programs that have commands like clone, download, upload, etc etc.   In our simple example above we will apply a User Admin set of command options for the client to use & with minimal effort by us which will create, amend & delete users.

Below i have created three classes, CreateOptions, AmendOptions & DeleteOptions

code_sample_10.PNG

code_sample_11.PNG

These classes each contain the required set of properties for each command operation, for example, CreateOptions will read in all the properties for the user from the cmd line and store these.  AmendOptions will read in an Id and the updated Name & Hobbies fields, finally DeleteOptions will read in the Id that is the user to be removed.

Main method has the following API call setup which will listen for what inputs have been supplied and process accordingly, all applied in a nice concise fluent way:code_sample_12.PNG

The AddUser, AmendUser & DeleteUser methods would fulfill the processing of the CRUD functionailty, for brevity i have put in place holder text output to illustrate so.

code_sample_13.PNG

code_sample_14.PNG

code_sample_15

Also notice how i have access to the properties (id, name, hobbies) from each class in each method.

A lot of capability out of the box in a few lines of code, which normally would take a bit of effort if built manually.

I have successfully used this library for building custom command line applications that i plugged into Continuous Integration pipelines using Team City in the past & i have to say its made my life a lot easier as a result.

As usual, all of the code examples above are available on my GITHUB page so feel free to play around.  I would recommend having a read over the nuget wiki page provided by their team which was very helpful.

NOW…go forth, & command & conquer your own console applications today!

Reach for the Top Shelf

slide.1

In this weeks post id like to give a mention to a very fine nuget package called TopShelf,  TopShelf is essentially a container (or bootstrapper) for running Windows Services, it shields the developer from having to worry about the low level window service plumbing code & lets them run a windows service with minimal effort in debug mode within VS & also provides much neater cmd line syntax for installing/un-installing.

Any developer who has built or maintained windows services knows the pain of debugging these applications or installing them.   A typical windows service looks like following

ts-ws-2

 

 

 

 

 

When this is run directly in VS it will give you this errorts-ws-3

This can typically be fixed by applying following technique..

  1. Change the Windows Service project type from ‘Windows Application’ to a ‘Console Application’.
  2. Replace above static Main method code with  following:ts-ws-1

When you run this in VS now under either debug or release the service will run as expected & can allow you to debug (the above just prints hello world with the current time each second).

ts-ws-4

All of this is a valid work around BUT can be a little time consuming, cumbersome & also not ideal to having to write boiler plate code specifically for debugging purposes,  installing the service also involves a bit of heavy command line syntax too.

Step forward TopShelf..

Setting up a windows service from scratch using this library involves 4 steps:

  1. Create a console application
  2. Install the Topshelf NUGET package,
  3. Configure a startup class
  4. Run the service from within VS

TopShelf has a fluent API that is easy to use, some very simple examples are show cased here, # 3 above is the HelloWorldServiceManager class which contains two methods Start() & Stop() that are wired up in the below code under WhenStarted & WhenStopped() calls.ts-ws-5

Also notice the nice API methods SetDescription, & SetDisplayName which should be self explanatory, pretty cool right?

The HelloWorldServiceManager class Start & Stop methods just contain a thread which fires off every second printing to console screents-ws-6

The other nice thing as i mentioned earlier about using TopShelf if you haven’t noticed already on above screenshots is that nowhere are the low level windows service framework code referenced i.e.: ServiceBase, this is all abstracted away under the hood by TopShelf so you the developer just worry about wiring the package up & then writing your own custom code that gets on with solving business requirements.

Installing/Un-installing the service on the Service Control Manger (SCM) is simplified through TopShelf cmd line syntax. Navigate to the bin folder of the service via cmd line, & run either:

  • NameOfWindowsService.exe -install
  • NameOfWindowsService.exe -uninstall

Neat right?

There is a host of other features it offers as well like exception handling, logging & dependancy injection, it also supports parameters being supplied @ startup of the service. Note: Some of these features will require additional TopShelf nuget package to be installed.

The one small thing id like to see improved upon with TopShelf is the documentation, while i have found it great when learning the tool initially, it is a bit outdated (written in 2011) so it could do with a refresh/update of content, some of this could be about the additional nuget packages that need to be installed for supporting additional requirements like using parameters @ startup which i had to do a bit of digging on.

Saying all that, its a terrific package to work with & has made my life much easier in dealing with Windows Services, something i approached with a little trepidation in days gone by just because of the drawbacks i covered above.

A side note – i have only used TopShelf with the .NET 4.6.1 framework, at time of writing no support exists yet for .NET Core 2 but am sure this will change soon enough.

The above sample code can be found on my Github page.  In my source code samples i also have included a section with examples for using startup parameters & dependancy injection (using ninject).

So if you build windows services & have struggled with the points i raised above, fear not, reach for the top shelf @ the nuget store and enjoy frictionless windows service development for ever more!

 

 

Who’s a pretty Polly

Blue-Beak-Parrot.png

This week i want to highlight another excellent NUGET package i found on my travels called Polly.  Polly is a fault handling library that allows you to apply retry attempts to remote call failures such as database connections or a HTTP request.

I stumbled across the package whilst reading Microservices in .NET Core (if you have an interest in micro-services i highly recommend this as a read) & immediately i was impressed by what it could do in a fluent code API manner making it tidy & succinct to read.

The library itself covers various ways of how you want to handle failure retry attempts, the more common API calls being the following:

  • Retry again & repeat this cycle x amount of times before giving up.
  • wait for x amount of seconds & retry again, repeating this cycle x amount of times before giving up (or until successful).
  • wait for x amount of seconds & retry again, repeating this cycle forever until successful.

For this blog post i will cover a very simple example by fetching data from SQL & apply the first point above.  Note that Polly has much much more features than those listed above, it can also provide circuit breaker and fallback handling, i haven’t tried these yet so i wont cover them in this post.

The easiest way to get up and running with Polly is to first identify an exception type that you need to apply fault handing for, lets go with an obvious one in this example by using SqlException, this will typically fail when a connection string is not valid, or the network is down, etc.

So first up, in red below i have declared a static property of Policy (from the Polly library) & using fluent API set the exception type we want to apply retry attempts on, the Retry function with parameter 1 is the actual policy & means if this exception is raised in an operation than please make 1 attempt to try again, …all nice & easy right?

polly-1

Next up we apply the declared policy to a function, as per below in red.  Notice the neatness which Fluent API brings to the code, again, all very readable.   For this example i have wrapped the code in a try/catch which captures the error stack trace for the caller, you obviously don’t have to do this & could just let it bubble up to the caller.

polly-2.png

PerformDatabaseReadById is just a helper method which is performing the SQL work for us as can be seen below (In case your not familiar with the db.Query<Person> syntax below, this was taken from a previous post i did on Dapper).polly-3.PNG

Everything is now in place to test the supreme power of fault handling by Polly.  For this demo i have a console app which calls GetById and displays to the screen, if the call is not successful display an error.

polly-4.PNG

To prove that Polly is indeed retrying, i have added a console output in green colour for when the SQL fetch method is being called by Polly.  In this instance everything was successful & only one call was made to fetch the data (note the one green trace output). polly-7.PNG

Now the acid test, we will invalidate the connection string with an extra character & force the policy to kick in & retry once after initial capture of the SqlException.   Running the app again we will now get a failure message on screen but only after Polly has attempted to retry once & then give up before finally displaying the SqlException message, note the two green text outputs to indicate one normal call & one retry attempt..pretty cool right!polly-8.PNG

I have made extensive use of the package in my latest project, where i have wrapped the library calls around SQL database & RabbitMQ connections & it has met those needs perfectly.

It gives great confidence to you the developer knowing that resiliency is now well handled in your application and is totally configurable without any significant effort at all, that is a huge win in my  eyes.  I have only covered a tiny bit of what the framework has to offer but hopefully i have convinced you a little to explore it some more & start applying it in your own mission critical projects.

All the code samples above are available on my GitHub page so please free to dissect at your leisure.

So now, plenty of reasons to be chirpy about the resiliency of your application code!

The Dapper Developer

download

Sometimes you get a NUGET package that just makes a good first impression & looks the part & this weeks mention is one of those, ladies & gentleman,  i present to you, Dapper.

Dapper is a very simple lightweight ORM (a micro ORM if you will) that is nothing but a pleasure to work with.  It is lean & non intrusive to your code base, & most importantly it runs fast.

Dapper is a great tool to consider on a project where more complex database considerations such as transaction mgmt, etc are not paramount to an application & you just want to do simple CRUD.  Typically for apps like this a developer will fire open NUGET manager & download the latest Entity framework library, Linq to SQL or perhaps handroll ADO.NET calls from scratch & attempt to plumb all the bits together just to do be doing a simple query or write operation, this can be quite taxing & for a lot of the time feels like overkill.

Well, Dapper eliminates all of that, download from NUGET, and if all your doing is performing a simple query than the following snippet will do this for you

dapper_code1

Everything within the using statement is what Dapper will perform, elegant right?

Person is just a typical POCO class with properties that match to what is being returned from SQL query, just to prove there is no magic here it is

dapper_code2

The magic behind Dapper is that it is an extension to the IDBConnection interface so its piggy backing on the underlying ADO.NET framework.

It has come to my rescue lately a lot for doing work around automated integration tests where i want to verify data in a table has been created, updated, etc.   In these situations i wanted something quick & easy to use for talking to a database without any manual plumbing or bloated features slowing things down & am delighted to say Dapper has exceeded those requirements.

For the benefit of this post i have put together a small console application demonstrating CRUD operations using Dapper on my GITHub page, so please feel free to download, the above code samples are taken from it.

Everyone likes to look Dapper, now your code can too!

Testing..Testing..1..2..1..2, is this thing on?

In the words of Bruce Buffer..”WE ARE LIIIVE”

Greetings all from Cork city in south-west Ireland on a cold-ish February Friday evening.  Let me firstly introduce myself, my name is Adrian & I’m a full-time senior software engineer currently working with a financial organisation.  I have a passion for back-end development with strong focus on Microsoft technologies such as Visual Studio, SQL Server & TFS & my go to programming language is C# which I really enjoy coding in.

So after a bit of stewing iv decided to give blogging a go in 2018, i just thought it would be something different to try out & hopefully fun.  Id like to thank John Sonmez & his wonderful blog posts for giving me that bit of extra motivation I needed to give this a go (i recently completed his mini blog course & the graduate badge is proudly sitting on the blog mantle piece @ end of this post), & i wont lie, it does feels a little bit exciting typing up this inaugural post which will be read by only a handful of people me!, but hey…hopefully maybe sometime in the far distant future i might be able to count on both hands the number of readers i have 🙂

The main content theme of my blogs will be covering mostly technical stuff that I come across in my day job, books iv purchased or perhaps articles that i have read via other blogs, or LinkedIn & Twitter posts.   One area in particular, Nuget packages, is something I will do my best to post regularly on.  I tend to stumble across various packages on a daily basis & some can be absolute gems to a project am working on, so i’l share my success with using them to the world & who knows they may help you out too!

OK, ok enough of the cheesy introductions dude I hear you grumble from the other side of the screen,  i hear you dear reader, so with that i’l get to work on my next post which will cover one of my new favorite Nuget packages i discovered recently.

……..until next time!