I am Nguele

My name is Jean-Dominique Nguele and this is my blog. FLVCTVAT NEC MERGITVR

Tag Archives: coding


NDepend’s static code analysis: Noob Review

Reading Time: 8 minutes

Today I am going to do something I have not done before. A couple months ago I was contacted by NDepend to play around their software. I did not check but there is probably a fair amount of software reviews out there. Hence why I will try an hopefully different approach. A noob approach. I’ll read the promise from the software to review and just dive into it without any sort of guidance. Let’s call it Noob Review. Yep, that’s how you create a series that might or might not live longer than a post.

NDepend’s promise

According to the website homepage, NDepend is the only Visual Studio extension that is able to tell us developers about created technical debt. This would then allow undoing the debt before it gets committed. The alleged debt is calculated based off a set of rules predefined using LINQ queries. We also can add our own queries.

Enough with introductions, let’s just get noobie!

Getting started

I downloaded the latest version 2018.1.0 released on Wednesday you can find the link to the latest version here. on NDepend upon download presents itself as a ZIP archive containing some executables and a Visual Studio Extention installer.

As you can see below, the installer propose you to install the NDepend extension to Visual Studio versions all the way back to VS2010.

From there I just installed the extension using the licence key the NDepend team nicely offered me.

Let’s jump right into it

From now on I am going full improv. I will have no idea of what I am doing because that is what most people do when they get a new tool. That approach works when you know how to use a pencil and grab a pen for the first time. It might be a bit more entertaining if I do so with NDepend. Since it is a tool that should allow me to detect technical debt I will write an ok piece of code then some less ok code to see what happens.

The project

First things first, I created a console project running on .Net Core. I am not seeing anything trigger automatically. Being used to Resharper, I check the toolbar and see an NDepend menu that was not there before.

Opening that menu I see that I can create an NDepend project which I do.

Once the project is created, it seems that I still cannot analyze my code. Not before attaching my solution to the NDepend project, which I do.

After attaching the project, I went back to run an analysis on my console app but I kept getting this error:

Turns out the NDepend project did not pick up the Visual Studio project. I then closed Visual Studio to reopen it yet I had the same error after loading the NDepend project and attempting to run the analysis again. Paying more attention to the error message this time, I noticed the error was about a reference to my solution not being loaded in NDepend. I thought that maybe the issue was with me not creating the NDepend project in my console app solution folder. I conjectured that maybe these errors occur because the NDepend project is not in the same directory as my solution. Probably a noob error on my end. So I went on to edit the NDepend project properties.

Above, you can see the NDepend project properties after I added the reference to my solution using the “Add Assemblies from VS solution(s)” button. It seems that it loaded the binary generated by the solution along with It also shows the 3rd-party binaries used by my solution, System.Runtime and System.Console. After that, I ran another analysis and it eventually worked as you can see below:

First analysis

Now that I finally set up the static analysis properly I can dive into what it reveals from a basic “Hello World!” console app. After that first successful analysis run, I could see that the NDepend menu changed. A whole new world opened to me. As a first reflex, I opened the “Rules” submenu. From there I could see that a rule was violated.

What rule could Microsoft’s “Hello World!” code possibly have violated? Well, look down.

Microsoft's coding sins

Microsoft’s code sins

Class with no descendant should be sealed if possible. It is actually more of a warning. A cool bit that I noted is that you even get a more detailed description of the warning cause along with why you should consider it.

I always learned that whenever possible we should have as little warnings as possible so let’s clean that up and make our Program class sealed. After making the change, when I re-ran the analysis, I got the same result and broken rules as before. Also, there was a message telling me that my file Program.cs was out of sync. I got a hunch and rebuilt the solution. Then the analysis result views updated.

NDepend all green

Technical debt (feel free to skip this part)

Now that the code is green and clean. It is time to try and build some technical debt. If you are not familiar with that term I will try to sum it up for you. Technical debt is the implied cost of rework needed in the future when choosing a quick and easy solution over one that would be more thorough but would take more time. More often than not chosing the easy way will hit you back. It will hit you hard.

Let’s say you take a complex subject at school. You could put in place a system to cheat to get good grades. It is easy and does not require extensive preparation work. Yet you can get caught and lose everything. Also, the ink can ruin your cheatsheet. Or, you could learn that subject and try to do your best mastering it class after class, exercise after exercise. You will not necessarily feel the effort was worth it from the start but eventually it will pay off. Learning your subject from the start is hard but you get more confidence to build on top of. Building technical debt on purpose is basically cheating on your Geometry class from high school. Don’t cheat on your Geometry class.

Back on the dirty coding

I felt like I did not want to spend months writing the perfect imperfect piece of code so I just googled “c# bad practices” and opened the first result that came up. From there I just copied the method and adjusted it to be called in our Main(). You can copy the code below if you are trying to reproduce the experiment.

Once the code ready, I rebuilt the solution and ran a new analysis.

In the post mentioned earlier, there are a few things wrong that are pointed at but some that would be unfair to criticize here. However, I will keep the points that I wish would have been picked up and were not.

What was found

  • The Calculate() method is public yet accessed by only one method in a console app. I hoped I would see more from the actually copied code and not from how I access it in my Main() method.

What was not found

  • The use of the magic numbers 0.1, 0.5, 0.7, 1, 2, 3 and 4.
  • Disrespect of the DRY principle with the same piece of logic written twice for discount calculation.
  • An alleged bug where the calculated price is 0 when none of the if-else is matched (to be fair, it might be a valid business logic in some cases but a warning would be welcome).

It can be considered unfair to point these out and it might be. I will try to spend some time later to see whether it would be possible to create custom rules to spot any of these. That will definitely be a fun exercise. Feel free to try the same at home.

Wrapping up

I originally planned on adding a section where I would try to get more warnings and errors but that would be outside the boundaries of what I want a Noob review to be. A follow-up post covering more complex cases and custom queries would be more fitting for a separate post anyway. Since there are loads of things currently happening in my life, that post might not happen for a while. That being said let’s wrap up with some pros and cons I noted during that quick take.

Pros

  • NDepend provides a clear explanation of what rules are broken and where in your project.
  • Don’t need an engineering degree to get started without a manual. I do have one so that might invalidate my comment so people without engineering degrees let me know if you found it hard to use without checking any guide.

Cons

  • Have to re-open the NDepend project when restarting Visual Studio.
  • Have to rebuild project when editing file to verify that no rule was violated or whether a violation was fixed. Also building the project does not automatically trigger NDepend’s analysis either.
  • Not available on VSCode or VS for Mac.

Special note on customization

While people love to customize things I do not trust myself for writing a rules engine determining my code’s quality. I’m likely to make a mistake in there and not notice it. I may actually change it to a pro after experimenting with it more.

Closing

After that first experiment, I do not think I would use NDepend for my personal projects. The cons I pointed above outweight the pros in my opinion. I do believe that spending more time with NDepend could change my vision of it and maybe make me realise that it fits my needs more than I think. I am no evangelist nor influencer, even if I was or become one by the time you read this, you should not take this post as absolute truth. It is a Noob Review after all, it cannot be right nor fair. My piece of advice is to go and have a look for yourself. If your interest got piqued by this post, you should download NDepend and figure out whether it fits your needs. You can have a 14-day trial to play with it. Happy experimentation!

.NET Core CLI Tools: Build a web API in 10 minutes

Reading Time: 7 minutes

This tutorial is an introduction to .NET Core CLI tools. More precisely it is about creating a web API using the CLI tools provided for .NET Core. Whether you are a beginner in development or just new to .NET Core this tutorial is for you. However, you need to be familiar with what an API is and unit tests to fully enjoy this tutorial. Today, we will set up a solution grouping an API project and a test project.

For the next steps, you will need to install .NET Core and Visual Studio Code (referred to as VSCode later for the sake of brevity) that are supported on Mac, Unix and Windows. If you want to know how that multi-platform/framework is working have a look here.

Creating the solution

First things first we will open a terminal (or Powershell for Windows users) to create our solution. Once this is done we can create our solution that I will name DotNetCoreSampleApi as follows:

This command will create a new folder and DotNetCoreSampleApi a solution file with the surprising name DotNetCoreSampleApi.sln .Next, we will enter that folder.

Creating and running the sample web API

Now that the solution is here, we can create our API project. Because I am not the most creative mind I will also name it DotNetCoreSampleApi. Here is the command to create the project.

That command will create a subfolder named DotNetCoreSampleApi to your solution DotNetCoreSampleApi. If you followed all the steps your solution root should contain a file DotNetCoreSampleApi.sln and the web API folder DotNetCoreSampleApi.sln. The web API folder should contain a few files but the one we need now is DotNetCoreSampleApi.csproj. We will add a reference to it in our solution. To do so, run the following command:

After getting a confirmation message we can now start the API by running that command:

After a few seconds, it should display a message notifying you that the API is now running locally. You may access it at http://localhost:5000/api/values which is the Values API default endpoint.

Adding the test project to the solution

You may be aching to see some code by now but unfortunately, you will have to wait a bit more. Back in the days of .NET Framework, there was no such thing as generating projects by command line. You had to use cumbersome windows to pick what you needed to create. So now all of this project generation can be done by command line thanks to the CLI tools you will like it. And this is merely a suggestion. Back to the terminal. If the API is still running you may kill it by pressing Ctrl+C in the window you opened it in.

We are now able to create a test project and add it to the solution. First, let’s create the test project using dotnet new as follows:

That command creates a new unit test project using MSTests in a new folder with the name DotNetCoreSampleApi.Tests. Note that if you are more of a xUnit person you can replace mstest in the command with xunit which will create a xUnit test project. Now similarly to what we did for our web API project, we will add our test project to the solution:

Almost instantly you should have a confirmation that the project was added.

Getting acquainted with VSCode

Now, open VSCode and open the folder containing the file DotNetCoreSampleApi.sln. At this point you have that structure into the folder:

If you never used VSCode before, or at least not for C# development you will be suggested to install the C# extension:

Select “Show Recommendations” and apply what VSCode suggests. Then, once you finished installing the C# extension you will get a warning about adding missing assets to build and debug the project, select “Yes”.

Don’t hesitate to go back a few steps or even to restart this tutorial if something does not seem to work as expected. Here is how your test folder should look like by now:

Time to write our test

And finally, we are getting in the fun code writing part. The part where we put aside our dear CLI tools  By code writing I mean copy/paste the code I will show you later. And by fun, I mean code that compiles. There is nothing less frustrating than code that does not compile. Especially when you have no idea why. Fortunately, this will not happen here.

Now that you have your code editor ready to use you can go ahead and delete the UnitTest1.cs file. Once done, you will create a new file named ValuesControllerTests.cs in your test project. Then your VSCode  more or less looks like this:

Using VSCode the file should be empty, but in case it is not, delete its contents to match the screenshot above. As soon as you get your nice and empty file copy the code below into it:

Now you should get some warnings, which is perfectly fine because they should be here. If you hover over these you will see some referencing related error messages like below:

These appear because we did not reference the API project into our test project yet. It is time to open your terminal again. However, if you feel like having a bit of an adventure you can try VSCode’s terminal that will open in your solution folder. In order to do so, you can press Ctrl+' while in VSCode to open it. Or Ctrl+` if you’re using a Mac, probably either work for Unix.

Once the terminal open we will reference our API project into the test one with that command:

If you don’t see the full command above, you can still copy it using the copy button present when hovering.

Now that the reference to the API project is here the referencing warnings concerning it should be gone. However, a new one might appear about the Get call as below:I am not quite sure why it happens but it seems to be a bug within VSCode not getting this reference is here through the API project. However, you should not worry about it because if you try to build the solution and or run the tests it will work.

Understanding and running our test

Now we lay into the crispy part, the one we need before getting any further. The part we can use as the basis before delving into more advanced stuff like continuous integration or continuous deployment. Running a test that validates our logic. If you had a look at the ValuesController.cs file inside our API project you will see that the Get()  method is returning an array of strings. This array contains the values “value1” and “value2”. The test class you copied earlier contains a method that verifies that both “value1” and “value2” are returned for this Get().

So, back to the ValuesControllerTests.cs file. You may have noticed some links appearing on top of our test method like this:

You can ignore the “0 references” and “debug test” links for now. Press “run test” to execute our test. Actually, it will first build our API project to have the latest version of it before linking it to our test binary. After running the test, you should see something like this:

And unsurprisingly our test is passing. Now let’s see if we remove “value2” from the array returned from ValueController.Get() and run the test again.

Running the test again:

As you can see this time it failed, in order to have it pass you may now undo your changes in ValuesController.cs.

 

A little more of .NET Core CLI tools

It’s nice to know that one of your tests failed, however, you know what is better? Knowing which test actually broke and why. Therefore, this is the perfect time to bring up the  .NET Core CLI tools again. Now, you can run our test using the .NET Core CLI tools with this command:

Which will actually provide you with some more details on what broke:

.NET Core CLI tools magic with tests

.NET Core CLI tools magic

As you can see you get the message “value2 is not returned” that we defined in our test file. Here is a little callback for you:

I won’t say that now you are a fully fledged .NET Core developer but it’s a good start. You just created your (maybe) first API and test projects. Moreover, the test actually validates some of the API controller logic. So you know, congrats on that. However, if for a reason or another, something did not go according to plan, feel free to check the source code here.

I hope you enjoyed this new entry of my future-proof series and I will see you next time. You should look forward to it as I will cover how to setup continuous integration for such a project. It should be different from that other post from last year using Appveyor.

And remember, if you ever need anything from the CLI tools:

dotnet new everything

Just dotnet new it!

No more, Bugs Funny, no more

Reading Time: 2 minutes

Have I ever told you about that annoying Bugs Funny?
Bothered me day and night from his irritating company.
And another day and another night, yet again another one,
Thinking I had nothing better to do, no joy, no life, no plan.

Sneaking in my code when I was all chill and compiling,
His exception traces eyeing at me seem almost smiling.
Even mocking, it doesn’t matter how hard I have studied,
As for next few days he will torture, get my brain crippled.

Burned in its light, blind to its weak spot, feeling hopeless,
I keep browsing StackOverflow with Redbull and stress.
It aches in every bone, my date nights and parties gone,
Bugs look at me, trick me, slap me. Show me mercy? None.

Really unfair you know, not one bug should have all that power,
Emprison, break my mind, haunt from the kitchen to the shower.
Drinking my misery when suddenly I remember, flabbergasted,
I inadvertently turned a comparison to an assignation, damned!

Run my program again as I get closer and closer to the rise of dawn,
I finally got rid of Bugs Funny, indeed now he’s dead and gone.
When I squashed it I wondered why I was so numb, so dumb,
More than ever I was so close to cry, beg, call for my mum.

Rest my head now I will, not ever rest on my success I shall,
Because his brothers are lurking in the shadows, right behind the wall.
Waiting for my vigilance to fall, letting room for them to spawn,
My testing shall betray them and help eradicating them in a yawn.

I will be the watcher on that wall, protector of my software,
None shall corrupt it with uncovered logic, noobs beware!
It will not be easy but a man’s got to do what a man’s got to do,
I shall head to the bar for a few drinks without any further ado.

I got pretty inspired as I wrote two of these over 24 hours between Monday and Tuesday where the first one was a month ago. Thanks for reading again, if you missed the last one you can also have a look there. I see that “Poetry time!” is quite popular on here so I’ll definitely write more tech-ish poems in the future. Thanks again for reading guys!

C# dynamic interface implementation at runtime

Reading Time: 2 minutes

Some context first

How did I come to write a class allowing dynamic interface implementation in the first place? Ever had to work on a huge company project over the weekend? Because it is the weekend you pick up fixes what should be easy configuration changes. Then you think it will take you only a couple of hours then you will be off to the gym. I thought that yesterday and boy I mislead myself, much mislead indeed. Basically I had to update a couple of big projects to remove fields that are null from the json response. All of that listening to stuff like the Ding Dong Song, Purple Lamborghini and Slipknot’s Psychosocial. On the first project I had to add a little line to have that working, so the second one should be the same right? I actually thought I would grab another task before leaving that improvised hackathon.

The thought journey

It was all fun and games until, surprise surprise, the second project used a custom formatter. That was to do some processing on the response objects and update some values to match our apps implementation. Fair enough. But the magical line of configuration to ignore null fields when rendering json did not work there. The obvious solution was to get rid of that custom formatter. The obvious thing to do was get rid of that formatter and figure a way to have that object value setting logic without touching the project classes. I say obvious because there were hundreds of classes there and I did not feel like changing all of them even to simply add an interface and its implementation. I had to set properties that may exist for hundred of objects. This is how I started googling, going through StackOverflow to try and figure how to achieve that.

The much lower scale Newton moment

During that thinking process I realized I could try to do something with dynamic objects instead of adding a value during the json formatting process. Interestingly enough, a few minutes later the StackOverflow ex-machina did its thing and I found that post “How to extend class with an extra property“. The answer from unsung hero Mario Stopfer brought me light on something I did not know was possible. You guessed it: Dynamic interface implementation at runtime. Not really in the form I needed but it opened a door of possibilities to me and a new perspective on the property setting issue. And I started coding, building, testing, debugging like crazy. After a few hours, I achieved what did not know was a possibility a few hours before. Dynamic interface implementation was there working and solving my issue.

Dynamic interface implementation: Epilogue

I had a nice afternoon of coding at the office, lots of laughs and problem solving that provides me with an article I really enjoyed writing and a new class for my in progress .NET utility project that should appear when mature enough on Github. However since you have been reading all of this you will have the code in a preview gist along with sample code. The only issue is that it does not work with the new .NET Core (yet?) so I will update it at a later stage when I find the time and solution. That or add another version. Without any further ado, here is what I called the TypeMixer.

Going full necromancian on old projects

Reading Time: 2 minutes

Old projects, they often end in what I call development hell. This odd place where some projects with a good potential become stale after a release or die because too late for a market. Very often personal projects end up there even when they are open source. Open source really seem like a tool to help spreading and sharing knowledge worldwide depending on the kind of project. Before open source democratized with the likes of Github  a huge number of personal projects probably took years to be released when not abandoned.

Today I decided to do the only kind of necromancy one should do: Bringing back an old project to life. A project for which I already wrote the code for the model and business logic. I had to make create a user interface and build a user experience as sleek as possible. However, I stopped it due to my vision of a market I thought crowded along with the lack of time. Now I see clearly that was not as true as I thought.

Here we are. Two months I did not post here, eleven months without working on a personal development project I am back at it. I spent my past weekends alternating between gym, party and sleep. Luckily, I work in a position where my brain I can keep my brain stimulated. Indeed, when not investigating an issue on one of our live apps nor working on our platform features I am defining development tools and processes to be used at company scale within the next months. Eventually, a lot of cool things will come out of that. I will definitely post a few related tutorials depending on schedule.

About the blog, I will try to post more regularly than I have maybe a tutorial. In terms of work I would like to share with you the video that we recorded last week. It is basically the new company careers video that I like not just because I am in it. You can definitely check it out below:

If you arrived that far in the post, first I would like to thank you for reading and watching the video. Second, do not abandon your old projects if you are not a 100% sure they are dead. Check your old source code even if it is to mock your old coding style. In the end you could actually have something worth the hassle.

Retail week hackathon 2016 aftermath

Reading Time: 3 minutes

Retail week hackathon 2016 result

Last week at the same time I was at home playing League of Legends to break away from the frustration of losing at the Retail Week hackathon 2016. I was frustrated because I was, well I still am, convinced that our idea was good enough to win. Actually, I wanted to write a post immediately after to express the mixed feelings I felt that day. On one hand, I loved the experience and the excitement of suiting up as my schools days nerd self. On the other hand I hated losing in a way that did not feel fair. I discussed about the outcome of the hackathon around and people felt like we should have won.

I still cannot believe that a system to book an hour in-store discussing with an employee about an item you see online. An employee you whose job is to sell you the said item, especially in 2016. Nowadays we are only clicks away from users reviews from all around the world. You can even have video reviews at least on youtube. I guess it makes more sense to the judges otherwise the Retail Week hackathon 2016 winner trophy would be on Poq’s trophies shelf.

When we first got the idea of the self-checkout we thought that the hardest challenge was having a working prototype. We were so wrong. We had a working prototype 4 hours before the hackathon ended. From there, we spent the rest of the time testing and fixing bugs to ensure the presentation’s success. The presentation did not go perfectly but the idea and the product were there. To be fair, I think that pretty much all the teams had a much presentation for lesser ideas which could be what cost us the gold. When the judges are involved in retail during a fashion event I guess this is key.

The self-checkout idea

We built a self checkout app that allows customers in a store to find items they want to purchase with indoor location using estimotes and geolocation to handle both indoor and outdoor app behaviour. The most interesting part is that you can scan your items so they add to your basket and when you leave the store you get charged automatically. We even built a mini-backend displaying the last paid basket.

We built a solid proof of concept even though there is some security flows that are fixable on the operational side. For the security tags, just add a device connected to the store system against which you scan your order generated QR code  to allow you unlocking the number of items you need to remove the tags from. Even further we can use security tags that would emit the value from the item barcode to enforce that someone is not unlocking something they did not buy. It is a 24 hour hackathon and still we thought about some corner cases.

We did focus on bringing people back to store. I think that we did show creativity and innovation using the latest technology. Maybe we did not manage to pass the idea to the judges but I know that this is the future of retail. Walk in a store pick what you need and go. No more queuing hassle. Basically shoplifting without the criminal aspect.

Learning and progressing

I may go next year if we put up a team again and learn from our mistake. Technical advancement is not the focus, presentation is. Coding the whole night to get a working prototype is not the focus, sugar coat is. Still it will remain a special moment to me because I did have fun. The self-checkout will be in your hands in a few years, I will do my best for it. I went, I saw, I learned, that is probably what I do best, learning. I learned things my whole life, both at school and out of it. Even now that I worked for a few years I still try to learn as many things as possible. Learning is key to evolution, it is the key to become a better version of one self.

A great way of learning is to take part in open source development, looking at other people’s code, taking on challenges. Since a few days now I am helping other developers on community based websites such as StackOverflow and Github. I had an account on both for some time but did not do much with them. The good part is that on one hand I can learn and sharpen my skills by taking on issues and at the same time I help others. Well, there is not much downside. On Tuesday I submitted my first (non-professional) pull request and it got approved and merged pretty much instantly. It was not much but it still feels nice, you can check it here.  And yesterday I got my first upvotes on a few posts on StackOverflow showing that giving time is enough sometimes.

That’s where I will end today’s post before I start spreading on random stuff, thank you for reading.