2019-01-22

Code Analysis for C# – Comparing Visual Studio and Sonar Capabilities


I have made some attempts to run code analysis tools on C# code and I have a couple remarks and examples.

But first, let's clarify what is the technology that makes it so easy to inspect static C# code: the Roslyn compiler.

Roslyn doesn't have a preference for any particular set of rules. The "Rules" are just a plugin. Each of us could write our own set of rules if we wanted to (see "Tutorial: Write your first analyzer and code fix | Microsoft Docs" ).

Visual Studio provides its own implementation of a C# analyzer with its own set of rules. But as it turns out, based on my case study, those rules are not the same ones as the ones implemented and enforced in Sonar for instance. The default Visual Studio analyzer and the default Sonar analyzer are not chasing after the same things. In fact either of this tool might report as a "warning", things that the other does not report at all. I believe that the same thing applies to NDepend.

This means that tools like *Sonar* and *NDepend* are NOT just GUIs to a well established set of rules. Each tool comes with its own philosophy and system of beliefs about what is good or bad practice.

You might then say: whatever then, who's better than Microsoft for setting rules about the language they created, right? Maybe. And maybe not.

In practice, different analyzers are complementary. The analyzer provided by Visual Studio seems better at picking up edge cases related to the language, whereas Sonar seems to operate at a higher (logical) level.



EXAMPLE #1:

Example of a problem picked up by the the Visual Studio analyzer but not by by the Sonar analyzer :

the following code



Stream data = webclient.OpenRead(url);
StreamReader reader = new StreamReader(data);
xmlstring = reader.ReadToEnd();
data.Close();
reader.Close();




supposedly will cause Dispose() to be called twice on the 'data' object...

The following code removes the warnings:



using (StreamReader reader = new StreamReader(webclient.OpenRead(url)))
    xmlstring = reader.ReadToEnd();




Like I said, this was not picked up by Sonar.




EXAMPLE #2:

Example of a problem picked up by the the Sonar analyzer but not by by the Visual Studio analyzer :
"Comparing to itself always returns true."







FYI, I've turned on all info and warnings and made them all visible. Visual Studio just does not see the pb with `listPrevious.SequenceEqual(listPrevious)`  :stuck_out_tongue:  Which is a shame, because that is a real bug in production code (a typo, or a bad copy-paste), it's not something I just made up. And Sonar's set of rule was able to detect this.


So in conclusion, my feeling is that Visual Studio's set of rules is better at detecting the "edge cases" related to the actual syntax features of the language and the .NET APIs, (which is only natural since both are Microsoft's creations). Whereas Sonar, being 10 years old, and being born in another world (Java) and supporting many languages, is more capable when it comes to reasoning on the semantic and logical levels.



CONCLUSION:



If I had to rephrase, I think that Sonar just doesn't bother with the flavor of the language; it cares about the logic and the semantics. Whereas Visual Studio tries to make it hard to shoot yourself in the foot with this one particular language; but on the other hand, it will let you write silly code if you want to, as long as you respect the internal constructs and overall code design.




READ MORE:


To close on this matter, a final quantitative analysis gives us:

SONAR:

  • Number of active C# rules in Sonar, by default = 216
  • Maximum number of available C# rules in Sonar = 355


VISUAL:

  • Number of active C# rules in Visual, by default = 62
  • Maximum number of available C# rules in Visual = 455


RulesCount-inSonar:


RulesCount-inVisual:


RulesCount-inVisual+ALL:





REMARK 1: A shared server is the preferred way to use Sonar, because it is very easy to create projects (one – or more – per developer) and use individual tokens to upload results before checking code in (and browsing results anonymously, in read-only mode, within the company's LAN/VPN). [However, if really wanted, an individual, private localhost instance setup, is possible too, in about 20 minutes when you have a concise documentation.]

REMARK 2: There seems to be a Visual Studio plugin that allows to run Sonar's rule on the fly
SonarLint for Visual Studio 2017: https://marketplace.visualstudio.com/items?itemName=SonarSource.SonarLintforVisualStudio2017
SonarLint for Visual Studio 2019 : https://marketplace.visualstudio.com/items?itemName=SonarSource.SonarLintforVisualStudio2019
From the website:

SonarLint spots bugs and quality issues as fast as you code.

  • 5 languages supported: C#, VB .Net, C, C++ and Javascript.
  • Open source, Roslyn based code analyzers.
  • Deep code analysis algorithms using pattern matching and dataflow analysis
  • Hundreds of rules, and growing.
  • Comes with explanations to resolve detected issues.



2018-07-26

Install both Chocolatey and OpenSSH with SSHD in one Copy-Paste in Powershell




TL;DR



Start a PowerShell console with Administrator privileges and run the following :


[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {[bool]1}; set-executionpolicy RemoteSigned -Force -EA 'SilentlyContinue'; iex ((new-object net.webclient).DownloadString('https://gist.githubusercontent.com/deskobj/f135af9b5404c594ee041c1688bc6f0a/raw')) 


After the command has exited, we can expect the following to be true:
  • CHOCO command available by default via PATH environment variable.
  • SSH command available by default via PATH environment variable.
  • SSHD service is running.






HISTORY OF THE ONE-LINER COMMAND
AND ITS BACK-END SCRIPT



The original command (from DarwinJS/ChocoPackages) reads as follows:
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {[bool]1};set-executionpolicy RemoteSigned -Force -EA 'SilentlyContinue';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/DarwinJS/ChocoPackages/master/openssh/InstallChoco_and_win32-openssh_with_server.ps1'))
Additionally:
  • JUL 26, 2018: Despite the recommendation "Not To", a cached (and modified) version of the script is made available.
  • AUG 28, 2018: Enforced TLS 1.2 security protocol use.
  • MAY 05, 2019: Added information about how to install Chocolatey on its own, using just a command line.




WHAT ABOUT INSTALLING CHOCOLATEY ONLY ?
(WITHOUT THE SSHD SERVICE)



To simply install Chocolatey, without SSH support, run the following PowerShell command, as Administrator:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; set-executionpolicy RemoteSigned -Force -EA 'SilentlyContinue'; iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))

If you wish to install SSH later, you can still run the original command even if Chocolatey is already installed (the Choco installation step will just be skipped).





PREVENT SYSTEMATIC CONFIRMATIONS
(WHEN YOU KNOW WHAT YOU ARE DOING)



Chocolatey always asks if you are sure about installing a piece of software.

One way to address this problem is to always specify the `-y` switch when invoking `choco install`. For instance:

  • `choco install -y git`,
  • or the even shorter version being `cinst -y git`


But you can also disable this behavior altogether, on a global scale, forever, by running the following command:

choco feature enable -n allowGlobalConfirmation




It's probably a dangerous thing to set up, but it's really nice when you are familiar with the tool and use it repeatedly.




MORE SOFTWARE INSTALL SUGGESTIONS



Chocolatey is like a package manager, but for Windows; a bit like the famous `apt-get` or `aptitude` for some GNU/Linux distros (`dpkg` for Debian, `yum` for Fedora/RHEL/CentOS or `dnf` for RPM-based distros in general, `yast2` or `zypper` for OpenSuse, `emerge` for Gentoo, `pacman` for Arch). So it allows you to install software easily and effortlessly and the catalog of supported installs is growing.

I have created a curated list of my favorite ones; the ones I would install right away on a new computer, whether it is for work or even for home computing.

Read more:



Other, ready to paste, multi-line commands such as the one above, can be found on this page:


2018-06-27

Populate the "Tools" menu entry in Git GUI - Github gist


Please find GitGui-InstallTools.sh as a public Gist on Github.


It is designed to add utilities to the default Git GUI.





You might also want to configure Notepad++ to be your default editor ?

git config --global core.editor "'C:\Program Files\Notepad++\notepad++.exe' -multiInst -nosession -notabbar"

2016-07-09

The (default) generated homestead VM does not have an IPv4 address and how to fix this

When I first went on installing a Homestead VM, it did not get an IPv4 address. And there was nothing that indicated a failure:

  • neither when the VM is booting (no errors, all appears "OK")
  • using the "ifconfig" command, we can see that our adapters do not have an IPv4 address (whereas we were expecting 192.168.10.10 to be used)
  • the “lspci” command allows us to see what devices are used. We can see the Ethernet controllers there.

tl;dr

I have written a much longer article about the analysis of the problem and all the possibilities offered by Virtual Box in terms of virtual ethernet adapters, and how to configure the Vagrant NIC Types, and you can read it here:


But a long story short:

Finally


Configuring the adapter type through the Vagrant file did not work as it created a third adapter and was ineffective.


But changing manually the NIC adapters in the VirtualBox VM setting and using Paravirtualized network adapter (virtio-net) finally gave the best results












2016-07-07

A word about false-positive and false-negative test-results, and why having a 'negative test-result' means 'passing the test'



Both “false-positive” and “false-negative” test-results exist.


1/ Positive and Negative tests-results


First, notice that the usual phrasing is “one is taking a test”, or “one is being tested for something”. One is “positive” for anomalies just like one is “positive” for alcohol, narcotics, drugs, disease, pregnancy, driving speed limit or amounts of goods at the customs: ie. typically some output values are above or below average. In everyday life, tests usually measure the concentration of a given chemical compound, or goods, or speeds; it’s the same for software: except that instead of chemical compounds or goods, we have file system objects, and we also have durations, speeds, loads, etc.



So, when software is taking a test, software is tested “for” regressions. Just like a chemical-test might reveal the presence of a molecule in your blood, a regression-test might reveal some incoherent or wrong behavior coming from the system-under-test. Therefore a “positive” test-result is a test-result that causes the test to appears, in first instance, and without further investigation, as “failed”.

By symmetry, a “negative” test-result is a result that did not detect any anomalies; the test is then usually considered as “passed”.


2/ False test-results


A “false-positive” test is a test that first appeared as “failed” but was later proven to be insignificant (eg. just like you would be first tested positive for something after saliva, or urine test, and later dismissed upon running more precise, blood tests).

Finally, “false-negative” tests are much more rare in practice: those are tests that did not catch an anomaly but should have. One can tell a test is a false-negative whenever one finds a problem that was not reported in the test covering the use-case.


In a nutshell:


Positive test-result = Anomaly detected = Failed test
Negative test-result = No anomaly detected = Passed test
False-positive test-result = Anomaly detected but no problem found after further investigation.
False-negative test-result = No anomaly detected and yet there was a bug.



2016-02-12

Print system information on top of your desktop background upon startup using BGInfo.exe (Sysinternals)



Executable with custom template:




https://onedrive.live.com/redir?resid=C213C8B09441DCD7!48680&authkey=!AEUBtQwOZXCSUto&ithint=file%2czip

Drop the the ".exe" and the ".bgi" files in C:\Windows, and schedule task to run at user logon :



    Bginfo.exe BGInfoConf-v160205.1.bgi /nolicprompt /timer:0



Default template:







My template:




Scheduled: