Category Archives: Everyday coding

.NET compiler platform (Roslyn) analyzer packages

The greatest new feature in Visual Studio 2015 is the .NET compiler platform previously known as Roslyn. The .NET Compiler Platform is an open source compiler for C# and VB with rich code analysis APIs. It enables developers to build code analysis tool like code analyzers, fixes and refactorings.

The community has built a number of packages containing great analyzers, fixes and refactorings. These can be installed either as a Visual Studio 2015 Extension or at project level as NuGet packages.

Refactoring Essentials

Refactoring Essentials contains approx. 200 code analyzers, fixes and refactorings
Simple defensive code analyzers like parameter checking.

Roslyn_CheckDictionaryKeyValueCodeRefactoring

Simplyfing code by converting conditional ternary to null coalescing.

Roslyn_ConvertConditionalTernaryToNullCoalescingAnalyzer

CSharp Essentials

CSharp Essentials focuses on the new features in C# 6 such as the nameof operator, string interpolation, auto-properties and expression-bodied methods.

Roslyn_StringInterpolation

Code Cracker

Code Cracker is a smaller package for C# and VB with analyzers e.g. for empty catch blocks and if a disposable object is disposed.

Roslyn_Disposable

SonarLint

SonarLint for C# has great analyzers too as Christiaan Rakowski points out in the comments. One of them warns about logical paths that will never be reached or simplified.

Roslyn_conditionalstructurePlatform Specific Analyzer

With Windows 10 and the new Universal Windows Platform you as the developer need to make sure that the Windows App does not use an API not supported on the platform you are targeting. This is exactly what the Platform Specific Analyzer package does for both C# and VB.

Roslyn_PlatformSpecific

If you know any other great packages – let me know.

Automatic Retry and Circuit Breaker made easy

Polly library logoIf you do not know Polly, you are missing out! I did not know about it until a couple of days ago and you properly never heard about it either, as this wonderful little library only has 63 downloads on NuGet at the time of writing.

Polly is an easy to use retry and circuit breaker pattern implementation for .Net – let me show you.
Start by specifying the policy – what should happen when an exception thrown:

  var policy = Policy
    .Handle<SqlException(e => e.Number == 1205) // Handling deadlock victim
    .Or<OtherException>()
    .Retry(3, (exception, retyCount, context) =>
    {
      // Log...
    });

The above policy specifies a SqlExeption with number 1205 or OtherException should be retried three times – if it still fails log and bobble the original exception up the call stack.

  var result = policy.Execute(() => FetchData(p1, p2));

It is also possible to specify the time between retries – e.g. exponential back off:

  var policy = Policy
    .Handle<MyException>()
    .WaitAndRetry(5, retryAttempt =>
      TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)
    );

Or the circuit breaker safeguarding against the same error occurs again and again if an external system is temporarily unavailable:

  var policy = Policy
    .Handle<TimeoutException>()
    .CircuitBreaker(2, TimeSpan.FromMinutes(1));

Go get it – I’m already using it 🙂

Levels of reuse in Software Development

One of the promises of object-orientation is reuse. Developing new software systems is expensive, and maintaining them is even more expensive. Reuse is therefore sensible in both business and technology perspectives.

With assistance of Erich Gamma, I have identified four levels of reuse.

First level of reuse: Copy/paste

Duplicating code or functionality makes it easy to reuse it. It’s a real timesaver at first, but keeping all the duplicates up-to-date and maintaining them is horrifying task. Not to mention the problems when forgetting to update one or more duplicates…

“Copy and paste programming is a pejorative term to describe highly repetitive computer programming code apparently produced by copy and paste operations. It is frequently symptomatic of a lack of programming competence, or an insufficiently expressive development environment, as subroutines or libraries would normally be used instead. In certain contexts it has legitimate value, if used with care.” Wikipedia

Second level of reuse: Class libraries

Reuse at class level or a set of classes in a software library is common and also fairly easy with object-oriented languages.

“Libraries contain code and data that provide services to independent programs. This allows the sharing and changing of code and data in a modular fashion. Some executables are both standalone programs and libraries, but most libraries are not executables …” Wikipedia

Third level of reuse: Design Patterns

Patterns allow you to reuse design ideas and concepts independent of concrete code.

“In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.” Wikipedia

Fourth level of reuse: Frameworks

An object-oriented abstract design to solve a specific problem – often very specialized, like Unit Testing frameworks and Object-Relational Mapping frameworks, but can be large, complex or domain specific.

“A software framework … is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined API, yet they contain some key distinguishing features that separate them from normal libraries.” Wikipedia

It’s all about being pragmatic – not all software will reach fourth level of reuse and will be structured as frameworks – frankly it shouldn’t. That said; copy/past style development is unquestionably a wrong path.

What level is your company at?

Visual Studio 2010 keyboard shortcuts

I am fond of keyboard shortcuts and wish I was a keyboard-shortcut-ninja and didn’t have to rely on the mouse all the time.

Using keyboard shortcuts boosts productivity and ergonomically a better choice, as the risk of getting a tennis elbow/mouse elbow diminish.

Source of keyboard shortcuts for Visual Studio 2010:

Removing SVN folders with PowerShell


I need to remove.svn folders from an existing Visual Studio Solution a customer email me, so I could commit it to another SVN repository.

If I had access to the original SVN repository, I could have used the export function, as it does not include the .svn folders – but no, it should not be that easy.

What the heck, I have been putting it off way too long to start working with PowerShell. It should be a familiar environment as it is object-oriented with a C# like syntax with full access to the .Net Framework Base Class Libraries (BCL).

Here it goes – my first PowerShell script…

function RemoveSvnFolders([string]$path)
{
    Write-Host "Removing .svn folders in path $path recursive"

	Get-ChildItem $path -Include ".svn" -Force -Recurse |
		Where {$_.psIsContainer -eq $true} |
		Foreach ($_)
		{
			Remove-Item $_.Fullname -Force -Recurse
		}
}

The Write-Host Cmdlet just writes the content to console window.

If you are like me, a PowerShell novice – start with the Getting Started with Windows PowerShell article and use the free tool PowerGUI from Quest Software. It’s PowerShell IDE with an integrated syntax highlighter editor and debugger.

In line 5 the Get-ChildItem Cmdlet iterates the path recursively and filtering the result to include only “.svn” files and folders. The force parameter allows the cmdlet to get items that cannot otherwise be accessed by the user, such as hidden or system files. Get-ChildItem Cmdlet can also iterate the registry.

Afterwards the result from Get-ChildItem Cmdlet is piped to the Where-Object Cmdlet (Where is an alias for Where-Object). The psIsContainer is a property on a folder. If it is equal to true pass it to the next pipe. I could have written the following instead:

Where {$_.mode -match "d"}

Use the below statement to list all properties for the files and folders in the current folder:

Get-ChildItem | format-list -property *

The foreach statement iterates every item and deletes the folder with the Remove-Item Cmdlet.

Calling the method is as simple as:

RemoveSvnFolders("c:svnMy Solution")

On TechNet there is a myriad of articles with the root Windows PowerShell Core and more task oriented like A Task-Based Guide to Windows PowerShell Cmdlets and Piping and the Pipeline in Windows PowerShell.

Remove SVN folders PowerShell Script.

Happy PowerShelling… 🙂