development, csharp comments edit

Conclusion and List of Posts

General consensus is that the new features are just small increments to improve productivity. They will help to clean up existing code. Less code is helpful to focus on the actual business logic instead of the clutter caused by the language.

For easy navigation I listed the links for all the previous posts:

Table of contents

  1. C# 6.0 New Features - Introduction
  2. Auto-Properties with Initializers
  3. Using statements for static classes
  4. Expression-bodied methods
  5. String interpolation
  6. Index initializers
  7. Null-conditional operators
  8. nameof operator
  9. Exception-handling improvements


development, csharp comments edit

There are 2 improvements on exception handling:

  1. Exception filters
  2. Using await in catch and finally blocks

Exception Filters

Visual Basic and F# already have this feature and now C# has it too! the way it works is basically defining a condition for the catch block (example taken from Channel 9 video):


catch(ConfigurationException e) if (e.IsSevere)


I think it can make exception handling more modular. Also it’s better than catching and rethrowing in terms of we don’t lose information about the original exception.

Using await in catch and finally blocks

Like most people I hadn’t noticed we couldn’t do that already! Apparently it was just a flaw in the current implementation and they closed that gap with this version


catch(ConfigurationException e) if (e.IsSevere)
	await LogAsync(e);
	await CloseAsync();

development, csharp comments edit

Personally I think this one is a bit trivial. So the argument is it eliminates the need for using hard-coded strings in the code.

For instance:

public class NameofOperator
    public void Run(SomeClass someClass)
        if (someClass == null)
            throw new ArgumentNullException("someClass");

public class SomeClass

Say you refactored the code and changed the parameter name in this example. It is likely to forget changing the name in the exception throwing line since it has no reference to the actual parameter.

By using nameof operator we can avoid such mistakes:

public class NameofOperator
    public void Run(SomeClass refactoredName)
        if (refactoredName == null)
            throw new ArgumentNullException(nameof(refactoredName));

public class SomeClass

The results are identical but this way when we change a parameter name all references to that object will be updated automatically.

development, csharp comments edit

This is another handy feature. Checking for null values before accessing them can quickly become cumbersome and yields a lot of boilerplate code. With this new operator checking for nulls and coalescing becomes really short and easy to read.

For example:

public class NullConditionalOperators
    public void Run()
        Person person = GetPerson();

        // Current C#
        if (person != null && person.Country != null)

    private Person GetPerson()
        return new Person() { Firstname = "Volkan", Lastname = "Paksoy" };

public class Person
    public string Firstname { get; set; } = "Unknown";
    public string Lastname { get; set; } = "Unknown";
    public Country Country { get; set; }

public class Country
    public string Name { get; set; }
    public string IsoCode { get; set; }

In the example above if you need to print the name of the country first you need to ensure both the Person and Country objects are not null. The if block aobe can be reduced to a one-liner with 6.0:

	Console.WriteLine(person?.Country?.Name ?? "Undefined");

They both produce the same results. The more complex the object hierarchy becomes the more useful this feature would be.

development, csharp comments edit

In current C# a collection initialization can be done like this:

var result = new Dictionary<string, string>();
result.Add("index1", "value1");
result.Add("index2", "value2");

or key - value pairs can be added during initialization

var result = new Dictionary<string, string>() 
	{"index1", "value1"},
	{"index2", "value2"}

With C# 6.0 values at specific indices can be initialized like this:

var result = new Dictionary<string, string>() 
	["index1"] = "value1",
	["index2"] = "value2"

It’s a shorthand but not so much! I don’t see much value in this notation but I’m sure in time it will prove itself. I don’t think the guys in the language team are just adding random features!

development, csharp comments edit

One of favorite features is the new string formatting using String Interpolation. In the past I encountered a lot of errors while formatting strings especially when preparing log messages. You may need lots of small pieces of data that so after a few iterations you may forget to add new parameters.

For example in the imaginary Log method below only 3 parameters are supplied whereas the string expects 4. It compiles successfully because the string is generated at run-time and it doesn’t check the number curly braces against the number of parameters supplied.

Argument count mismatch error

Using the new feature such errors can be avoided as we can put the values directly in their places in the string:

public class StringInterpolation
    public string Log(string timestamp, string application, string error, string status)
        return string.Format("[Timestamp: \{timestamp}], Application: [\{application}], Error: [\{error}], Status [\{status}]");

No more parameter mismatch errors!

development, csharp comments edit

It’s a shorthand for writing methods. The body now can be written just like a Lambda expression as shown in Log2 method below:

public string Log(string timestamp, string application, string error, string status)
    return string.Format("[Timestamp: \{timestamp}], Application: [\{application}], Error: [\{error}], Status [\{status}]");

public string Log2(string timestamp, string application, string error, string status) => string.Format("[Timestamp: \{timestamp}], Application: [\{application}], Error: [\{error}], Status [\{status}]");

It may come in handy for helper methods. The only benefit I can see is getting rid of opening and closing curly braces which generally don’t bother me much. But I know lots of people trying to avoid curly braces as much as possible. I’m sure this feature will be popular among them.

development, csharp comments edit

Currently using statements are for namespaces only. With this new feature they can used for static classes as well. Like this:

using System.IO;
using System.IO.File;

namespace CSharp6Features
    class UsingStaticClass
        public class StaticUsing
            public StaticUsing()
                File.WriteAllText("C:\test.txt", "test");
                WriteAllText("C:\test.txt", "test");

I don’t think I liked this new feature. If you see a direct method call it feels like it’s a member of that method. But now it’s possible that method can be defined inside a static class somewhere else. I think it would just cause confusion and doesn’t add any benefit.

development, csharp comments edit

Currently, in Visual Studio 2013, if you have a line like this

public int MyProperty { get;  }

you’d get a compilation error like this:

Getter-only auto-property error

But the same code in VS 2015 compiles happily. The reason to add this feature is to not get in the way of immutable data types.

Another new feature about auto-properties is initializers. For example the following code would compile and run with new C#:

public class AutoInit
    public string FirstName { get; } = "Unknown";
    public string LastName { get; } = "Unknown";

    public AutoInit()
        Console.WriteLine(string.Format("{0} {1}", FirstName, LastName));
        FirstName = "Volkan";
        LastName = "Paksoy";
        Console.WriteLine(string.Format("{0} {1}", FirstName, LastName));

and the output is unsurprisingly looks like this:

Auto-property initializer output

When I first ran this code successfully I was surprised how I managed to set values without a setter. Looks like under the covers it’s generating a read-only backing field for the property and just assignning the value to the field instead of calling the setter method. It can easily be seen using a decompiler:

Just Decompile output

As it’s a read-only value it can only be set inside the constructor. So if you add the following method it wouldn’t compile:

public void SetValue()
    FirstName = "another name";

Auto-property set error

It’s a small improvement providing an alternative way to write the same code in less lines.

development, csharp comments edit

A new Microsoft

These are exciting times to work with Microsoft technologies as the company seems to be changing their approach drastically. They are open-sourcing a ton of projects including the .NET Framework itself. Maybe the best of it all is the next version of ASP.NET will be cross-platform. There are already some proof of concept projects that run a ASP.NET vNext application on a Raspberry Pi. I like the direction they are taking so I think it’s a good time to catch up with these new instalments of my favorite IDE and programming language.

New features in a nutshell

Looking at the new features it feels like they are all about improving productivity and reducing the clutter with shorthands and less code overall. (It’s also confirmed by Mads Torgersen in his video on Channel 9)

If you check out the resources at the end of the this post you’ll notice that there is quite a flux in the features mentioned in various sources. I’ll use Channel 9 video as my primary source. It features a PM in the language team and it’s the most recent source so sounds like the most credible among all.

Here’s the list of new features:

  1. Auto-Properties with Initializers
  2. Using statements for static classes
  3. String interpolation
  4. Expression-bodied methods
  5. Index initializers
  6. Null-conditional operators
  7. nameof operator
  8. Exception-handling improvements

I was planning to go over all of these features in this post but with sample code and outputs it quickly became quite lengthy so I decided to create a separate post for each of them. Watch this space for the posts about each feature.


tip of the day, aws s3, windows powershell comments edit

Cloud computing is a relatively new concept, especially when compared to FTP which dates back to 70s (History of FTP server). So not every device supports S3 uploads. If you cannot force a device to upload directly to S3 and have control over the FTP server machine (and assuming it’s running Windows) you can create a simple PowerShell script to upload files to S3.

FTP to S3

First you need to install AWS Tools for Windows. I tested on a couple of machines and the results were dramatically different. My main development machine is running Windows 8.1 and has PowerShell v4 on it. I had no issues with using AWS commandlets in this environment. The VM I tested has PS v2 on it and I had to make some changes first.

v2 vs. v4

The problem is AWS module is not loaded and you have to do it yourself with this command

import-module "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1"

After this command you can use AWS commandlets but when you close and open another shell it will be completely oblivious and will deny knowing what you’re talking about! To automate this process you need to add it to your profile. AWS documentation tells you to edit your profile straight away but the profile did not exist in my case. So first check if the profile exists:

Test-Path $profile

If you get “False” like I did then you need to create a new profile first.

To create the profile run the following command:

New-Item -path $profile -type file –force

then you can edit the profile by simply running

notepad $profile

Add the import-module command above and save the file. From now on every time you run PowerShell it will be ready to run AWS commandlets.

Time to upload

Now that we got over with troubleshooting we can finally upload our files. The commandlet we need is called Write-S3Object. The parameters it requires are the target bucket name, source file, target path, and the credentials.

Write-S3Object -BucketName my-bucket -File file.txt -Key subfolder/remote-file.txt -CannedACLName Private -AccessKey accesskey -SecretKey secretKey

Most likely you would like to upload a bunch of files under a folder. In order to accomplish that you can create a simple PowerShell script like this one:

$results = Get-ChildItem .\path\to\files -Recurse -Include "*.pdf" 
foreach ($path in $results) {
	Write-Host $path
	$filename = [System.IO.Path]::GetFileName($path)
	Write-S3Object -BucketName my-bucket -File $path -Key subfolder/$filename -CannedACLName Private -AccessKey accessKey -SecretKey secretKey


jekyll, site news comments edit

As you probably know I’ve migrated to GitHub Pages from WordPress as I blogged here.

It was a fairly easy migration but migrating the actual content proved to be trickier. There are lots of resources on using Jekyll’s importers. I found this one useful. Just export everything to an XML and run the converter to get the posts in markdown. The problem is the YAML Front Matter it generates is a bit messy:

layout: post
title: Blind Password Masking
date: 2011-06-14 03:46:18.000000000 +00:00
- Off the Top of My Head
tags: []
status: publish
type: post
published: true
  _edit_last: '1'
  login: blogadmin
  display_name: Volkan
  first_name: ''
  last_name: ''

I don’t want or need most of this stuff anyway!. Also I had two main issues:

  • Images didn’t work as it didn’t get the full path. I use S3 to host all images but the imported posts were converted to use a local assets folder. There may be a configuration setting for that but in my case I decided to convert all my posts to markdown from HTML anyway (which was a great way to practice Markdown)
  • Main issue was with Disqus. It’s not like people are racing to submit comments to my ramblings but still I’d like to have Disqus enabled on all my posts. Apparently to enable comments you need to specify it in the front matter like this:
comments: true

Manual vs. programmatical

First I resisted the temptation to write a small application to convert the layouts but manual conversion soon proved to be very time consuming even with 100+ posts. So I developed the simple console application below. It scans the folder you specify (filters *.markdown files) and reads the existing layout and converts it to the format I wanted:

layout: post
title: @TITLE
date: @DATE
categories: [@CATEGORIES]
comments: true

I wanted to keep it simple and clean. Also as all my posts are now in pure markdown I can easily loop through and update the elements (like converting H3 to H2 or adding tags to layout etc)

Source Code


It probably won’t apply to most situations but helped me out so why not publish it just in case, right? To use it you have to change the ROOT_FOLDER value in Program class at the bottom (Do NOT forget to backup your posts first!)

As I wanted to revisit all my posts I wanted to mark them instead of replacing automatically with the original one. So when you run the program it deletes the original post and creates the updated one with “.output” appended. So you can easily find which files are modified by checking the extension. If you want it to replace the original post you can uncomment this line at the end of the ConvertFile method

 // File.Move(outputFilePath, inputFilePath);


leisure, travel comments edit

Last Saturday, I went to Palace of Westminster for the first time. I had been around it a lot of times while playing Ingress and chasing portals but never been inside it.

I bought an audio tour ticket here and it did not disappoint.

Palace of Westminster

The building looks glorious from the outside but from the inside it’s absolutely amazing. Definitely the most beautiful and impressive building I have ever seen in my life.


Events comments edit

On Wednesday I attended this meetup. It was fairly informative. There is a bit uncertainty about the new features of Windows 10, Visual Studio 2015 and C# 6.0 but it was still good to cover most of them in a few hours.

It was divided into two main sections: Windows 10 and VS 2015/C# 6.0. I’m planning to review these myself and blog about them separately but here are the highlights of the events:

Windows 10

When they first announced the name I immediately thought about Winamp skipping version 4. We all know how that story ended so I hope Windows 10 fares better than that!

A few items discussed in the event about Windows 10:

  • First demonstration was sending a feedback which was painfully slow and it took forever to send a simple feedback message.
  • Some enterprise features are coming like like having store and custom company portals
  • There was a rather long discussion about what the 4 device from the left was in the image below: One Windows

I don’t think it makes any difference though but the idea is having one code base and one store to deploy apps to various devices with different form factors. Sounds cool but I’m a bit cautious about it for the time being. If it sounds to good to be true, it generally isn’t!

  • Looks like they are going to use hamburger icons everywhere which they initially opposed to.
  • There seems to be back buttons in a few screens which is a bit unusual so they may have to deal with some lash back from people like they did for their brilliant(!) charms invention.

Visual Studio 2015

Preparing for Windows 10 Event

  • There will be a free version of VS 2015 and there is already a free version for VS 2013 called “Community Edition”. It’s said to be Professional equivalent so it sounds cool to have it for free.
  • Like all Microsoft products versioning is a bit off and confusing here as well. There was a discussion about the version number vs. release year. So VS 2013 actually is version 12 but VS 2015 is version 14 even though there is no other VS in the middle!
  • A research project called Pex used to generate unit tests made its way to VS 2015 under Smart Unit Tests. It should help to create a lot boilerplate test code.

C# 6.0

  • Not a C# feature but one of the most impressive developments nowadays is that .NET Framework has become open source.
  • New version is coming with a much faster 64-bit compiler called .net RyuJIT
  • .net Native Project N is coming which is supposedly make the applications run faster
  • The compiler has been completely rewritten and its name is now Roslyn. It’s open sources and it exposes APIs that can be consumed by any application. So the compiler doesn’t have be a black box anymore.


A lot of exciting and revolutionary developments are going on in the .NET world these days. Taking a more open-source and multi-platform based approach will definitely help the platform in the future. It’s thrilling to be a developer and experience them first hand as these news come along. I have my virtual machine running Windows 10 and VS 2015 so I’ll play around more and blog about these specific features in detail in the near future.


Site news comments edit

On the road again…

Using WordPress for my blog had been bugging me for quite some time. So I’ve started using the popular static site generator Jekyll and host my blog on GitHub pages. Main reasons for this were:

  • Security: Over time you install a lot of plugins and any number of them can come with vulnerabilities. Granted they are optional and they are installed because they provide nice functionality but it would be much better to delegate the security of the system to GitHub.
  • Maintenance: I used to host my blog on AWS which is relatively easy to maintain but still I was responsible for keeping that machine up and running at all times.
  • Database: Using a database is overkill when all I’m doing is generating some static content. Database comes with performance impact, maintenance and backup requirements.
  • Scalability: No need to worry about scaling as GitHub takes care of it all for free!
  • Versioning: Just like any project on GitHub you have full control over the content and you can rollback to a previous version anytime.
  • Performance: All content is served in static pages. So compared to retrieving it from the database and generating the page on the fly it’s obviously much faster and scalable.

Beautifying the content

Compared to HTML, markdown is so elegant and concise. No more pesky attributes and ugly tags mingled with text. Granted WordPress has plugins for writing posts in Markdown but in GitHub it’s a first-class citizen and supported from the get-go.


  • WordPress has its own merits like having a gazillion of plugins and themes. GitHub Pages supports a limited number of plugins due to security reasons.
  • SEO must be taken care of manually whereas WordPress already has lots of plugins for that purpose too


csharp comments edit

yield keyword has been added to C# long time ago but I never made a habit of using it. Basically what it does is create an iterator and allows you to return an IEnumerable one item at a time.

For example in the example below (from MSDN) Power returns a single int. But the return type of the method is IEnumerable. This is because of the _yield_ usage. Every time it's called it returns the next value it calculates.

public class PowersOf2
    static void Main()
        // Display powers of 2 up to the exponent of 8: 
        foreach (int i in Power(2, 8))
            Console.Write("{0} ", i);

    public static IEnumerable<int> Power(int number, int exponent)
        int result = 1;

        for (int i = 0; i < exponent; i++)
            result = result * number;
            yield return result;

    // Output: 2 4 8 16 32 64 128 256

I developed a small Fibonacci calculator using yield.

Notice the first two occurences:

yield return f0;
yield return f1;

When it’s first called it returns f0 (0) and on second call it omits that return and returns f1 (1) and on subsequent calls it loops until the desired numbers and returns the series up until that point.

And the output looks like this:

Fibonacci console output


  • [MSDN Reference] (

Site news comments edit

I know I’m late to the game but better late than never, right? Right? Anyway, I’ve decided to use markdown syntax in my blog from now on. So if I migrate it some day it would be easier as Markdown’s supported in many platforms.

I know at the end of the day it all boils down to HTML but I think it’s about time to force myself practice more Markdown and integrate it into my daily routines. Let’s see how it goes with the next posts!


Gadget Raspberry Pi comments edit

I never cared for building a media centre before as I’m front of my desktop computer all day long and it has everything I need! But I was always curious about what the whole thing is about. As I was already looking for an excuse to buy myself one of those new Raspberry Pi B+ models it didn’t take too long before I decided to build a shiny little media centre for myself!


First of all before I engaged with this world they’ve already changed the name of the software! What’s formerly known as XBMC is now called Kodi. It has releases for Windows, Mac, Linux, Raspberry Pi etc. so no wonder why it’s so ubiquitous. For Raspberry Pi there are two popular distros: Raspbmc and OpeElec. When you are a complete noob choosing the right distro might be a hassle. After a quick search I found a a nice comparison here. Turns out Raspbmc comes with a full OS and running XBMC on top of it. That’s why I decided to go with it as it would give me full control over the Raspberry Pi and I could use it for other purposes as well.


Raspberry Pi B+

I mentioned the Raspberry Pi already but I needed a few accessories too.

Component Price Where to buy?
Raspberry Pi + Case £31 Amazon
32GB microSD Card £13 Amazon
Power adaptor £5 Amazon
Remote control £4 eBay
Audio splitter £8 Amazon
Monitor / TV £0  
Keyboard & Mouse £0  
Wi-Fi Adaptor £0  
Wireless headphones £0  
Speakers £0  

£0 doesn’t, unfortunately, mean they were free. It just means I used my existing gadgets lying around idly so it’s a win-win situation anyway. It felt good to utilize them even though that meant spending extra 60 quids!


Alright, now that we know what to install and where to install, let’s get cracking! Installation is dead simple as with all Raspberry Pi projects. All we have to do is download the latest build from Raspbmc website and prepare an SD card using a tool like Win32 Disk Imager. Insert it into the Pi and you’re good to go. When you plug in the pi and connect to your monitor/TV you get to the home screen:

XBMC Home screen


So it’s almost ready to kick back and enjoy podcasts, TV shows and movies but we need to tweak it a little first.


If you can use wired network, do so as it would be much faster. Unfortunately I have to use a wireless adaptor because of the location of my switch and me not wanting a long Ethernet cable crossing the room! To switch to Wi-Fi go to Program –> Raspbmc Settings. In the Network Configuration tab change  Network Mode to “Wireless (WIFI) Network”

XBMC Network Settings


For audio I use my speakers and wireless headset which are both connected via 3.5mm audio jack. The default audio output is HDMI so I needed to change it to Analogue in System –> System Settings –> System –> Audio Output

XBMC Audio Settings

Stuff to watch!

Almost there! Now we need to add stuff. To add an online source just hover Videos and select “Add ons”. Then you can install scripts for your favourite video/audio sources. My all-time favourite podcast network is TWiT so I was relieved to see there was an add-on for it.

XBMC Video AddOn

Also it is possible to add RSS feeds manually as explained in this nice article.

What’s Missing

  • I added sources from my desktop computer for TV shows and movies but ideally they should be put on a NAS on the network so it doesn’t rely on desktop up and running all the time (even though it is!)
  • To enjoy it fully it would be nice to plug it to a nice big TV. An 18.5” monitor is barely good enough for video podcasts but definitely not a viable option to watch movies.


It feels nice to watch my favourite podcast shows on a cheap, remote-controlled small computer. It was absolutely hassle free to build it which left more time to play with fun stuff, like installing a Twitter add-on (which unfortunately failed to run because of incompatibility issues!) I’ll definitely keep on playing with it. After adding more stuff and streamlining the process (like adding new favourite feeds to a playlist automatically) I’m sure I’ll enjoy it a lot more.


Off the Top of My Head, Site news, Tip of the Day, Tips & Tricks comments edit

One of the sites I like is Coderwall. It’s a nice place to check out quick tips from different developers. Also it has a voting system which you feel a bit validated when people find your tips helpful. I have 6 “protips” in their site and some of them had a few upvotes. I was motivated to post more tips which are especially too short for a blog post.

Your upvotes are no good here!

A few backs I logged in to check if I had any new upvotes. To my surprise, not only I didn’t get anything new, all my previous hard-earned upvotes were deleted as well! I contacted their support and 2 weeks later they said they could have been deleted because of spam concerns. If a tip is online for about a year and it was viewed by hundreds of people and got 3-4 upvotes in the process I think it’s safe to think that there’s not a scam going on here. Even if you think something is fishy you should give them benefit of the doubt just because the numbers are very small and very plausible. Luckily, I have better things to do than scam Coderwall and a few measly upvotes have no meaning at all.

Time to pack and leave

A week later I decided to publish all my posts n my blog. I went to my account to list my tips but the link wasn’t working. So I couldn’t even get the tips I had created. At least they provide a way to search by username. That’s how I could find my own tips. That was the straw that broke the camel’s back! So the lesson learned here is that always take control of your own content. Publish it on your own site/blog or whatever platform you control then propagate your content elsewhere if you choose to do so.

Goodbye, Coderwall!

I know this idea sounds very natural and obvious to some people. I think I should have thought of it before this incident but at least I recovered my content without any loss and learned a valuable lesson. I may still post to Coderwall but after deleting my votes and treating me like a scammer I’ve lost interest to their site. Looking at the quality of their support I don’t think they will be around for a long time anyway!

From now on I will post suck quick tips on this blog under “Tip of the Day” category.

Tip of the Day, Tips & Tricks comments edit

In some cases you may want objects in a bucket be deleted automatically, for example for log files or surveillance footage you may want to keep only latest n days. You can run scripts to delete them manually but it can also be done by setting the expiration date on the bucket.

AWS S3 Object Lifecycle