While creating a unit tests I tried to find code to generate Swedish personnumbers but couldent really find any copy paste pieces of code. So to remedy that here is a method which will generate a valid Swedish "Personnummer"

I tried to get it down to a single line but this is as close as I got before realising I have better things to do. If someone can make this into a single line of code I'd love to see that in a comment ;)

public string GeneratePersonNumber()
    // Create first numbers
    var pNum = (
                        (DateTime.UtcNow.AddYears(-10 - (new Random()).Next(0, 50))).ToString("yyyyMMdd")
                        + (new Random()).Next(100, 999).ToString()

    // get the control value sum
    var total = string.Join(string.Empty,
                        pNum.Substring(2, pNum.Length - 2)
                            .Select((value, i) =>
                                ((int)(value - '0')) * (2 - (i % 2)))
                            ).Sum(c => c - '0');

    // add the control value to the number
    return (pNum += (Math.Ceiling(total / 10d) *10) - total);


Update: Ok so I coulden't let it go and spent a few more minutes trying golf the code down in size. This is the shortest I managed, it's 189 characters long. Not very readable but it does generate a valid personnummer of a person between the ages of 10 and 60. Still coulden't manage to make it in one line of code though.

public string GenereatePersonNumber()
    var p = DateTime.Now.AddDays(-3650-new Random().Next(18250)).ToString("yyyyMMddfff");
    return p + (10 - string.Join("", p.Select((v, i) => i > 1 ? (v - '0') * (2 - i % 2):0)).Sum(c => c - '0') % 10);

Here are 3 sample personnummer/social security numbers generated by the above code: 

  1. 199307242652
  2. 197512275202
  3. 197611112835


Update 2: As per the request in the comment here is a version of the code where you can set the age of the person whom you are want the personnumber to be generated for. Also included the unit test I used as this code is a little trickier.

public string GenereatePersonNumber(int age)
    var r = new Random(DateTime.Now.Millisecond);
    var p = (new DateTime(DateTime.Now.AddYears(-age).Year, 1, 1, 0, 0, 1, DateTime.Now.Millisecond, DateTimeKind.Local))
                   .AddDays(1 + r.Next(0, (int) (DateTime.Now - new DateTime(DateTime.Now.Year, 1, 1)).TotalDays)).ToString("yyyyMMddfff");
    var ctr = (10 - string.Join("", p.Select((v, i) => i > 1 ? (v - 48) * (2 - i % 2) : 0)).Sum(c => c - 48) % 10);
    ctr = ctr == 10 ? 0 : ctr;
    return (p + ctr);

Also including the unit test for this code if you want to validate that it actully produces propper values.

public void GeneratePersonNummerTest()
    var pn = new List<string>();
    Parallel.ForEach(Enumerable.Range(0, 1000), x =>
        foreach (var r in Enumerable.Range(0, 80))
            var number = GenereatePersonNumber(r);
            var birthdate = new DateTime(int.Parse(number.Substring(0, 4)), int.Parse(number.Substring(4, 2)), int.Parse(number.Substring(6, 2)));
            var today = DateTime.Now;
            var age = today.Year - birthdate.Year;
            if (birthdate > today.AddYears(-age)) age--;

            Assert.IsTrue(age == r);

Some tags (in Swedish) which might help people searching for this: Generera personnummer med C# kod. Personnummer, Generera, Svenskt personnummer, Skapa personnummer för test, fejka personnummer. Generera personnummer i C#.

This is a function I find myself writing quite often, so I thought I would just post it here for future reference. It's purpose is simple, check if an array contains an element with a given key and value, if it does, return it other wise return a null value.

function FindObjectByKeyInArray(array, key, value){
   for(var i = 0; i < array.length; i++) {
      if (array[i][key] == value) {
         return array[i];
   return null;


I was recently asked how hard it would be to create a home network that is completely secure (as close as it gets anyways) from snooping ISPs or third parties so that the user can browse any site they want without risking anyone finding out about it. This means both tunneling all traffic through a VPN connection but also blocking any and all traffic that tries to get around the VPN. That is, no traffic should go directly to the ISP even if the VPN connection goes down.

There are several use cases for this, the most common probably being: 

  • Circumvent school or office firewalls.
  • Get around ISP blocks.
  • Peace of mind that no one can see what you are downloading.

The only downside to using a VPN is that your internet will be slightly slower, but if you use a good VPN provider you will only ever notice this if you are playing online action FPS games such as Counterstrike or Battlefield, for regular surfing or watching movies you will not notice any difference. 

What we are really doing is creating a secure tunnel through your ISP to the VPN redirecting all the traffic so that it seems to come from the VPN provider, leaving your ISP clueless to what you are doing and anyone on the internet only ever sees your VPN providers IP and never your real one.


Part 0: The requirements

To get this to work you need:

  1. A DD-WRT Mega compatible router (I am using a Asus RT-N16 that I had laying around).

  2. An account with a VPN provider that supports OpenVPN (don't use PPTP as it is not secure).
    I'm using Anonine, my favorite Swedish VPN provider. Heres a referal link if you want use them and support me: Anonine referal link.

  3. About 1 hour of your time.


Part 1: Configuring the VPN connection

I will assume that you have installed DD-WRT and are connected to the router at this point.

  1. Start by getting the Open VPN configuration files from your VPN provider. If you are using Anonine like me they are available here: https://anonine.com/en/account/server-info. Open the file you downloaded in wordpad or notepad (or whatever text editor you have handy).

    The file should look similar to this:


  2. Log into your router and Navigating to Services > VPN and Enable the OpenVPN Client.

  3. Using the configuration file from above configure the following OpenVPN settings. 

    • Copy IP/Name and Port (it is the part I have highlighted in my file above).
    • Check that your open VPN provider is using UDP as Tunneling Protocol (it should say "proto UDP" in the beginning of the file you downloaded, otherwise change it to TCP).
    • Enable NAT if it is not already enabled.
    • Set Hash Algorithm to SHA1

    This is what my OpenVPN client settings looked like after doing the above.


  4. Then, turn on Advanced options and enter the following in the Additional Config field.
    ns-cert-type server
    auth-user-pass "/tmp/auth.conf"
    persist-key persist-tun
    verb 2
  5. The next thing to do is to copy over the CA Certificate. In the configuration file you will have an area that looks similar to this, although the text between the Begin and end will be alot longer.


    Copy everything between the <ca></ca> tags including the begin and end text with their ---- lines and paste it into the CA Cert field.


  6. Click Save and Apply Settings at the botttom of the page

  7. Once this is done we need to create a file containing your username and password for the VPN service. Navigate to Administration > Commands and enter the following text, replacing username and password with your VPN providers username and password. Note that the newline between username and password is intentional.
    echo "username
    password" > /tmp/auth.conf 
    chmod 600 /tmp/auth.conf
  8. Click Save Startup 

  9. Next, navigate to Setup > Basic Setup and enter the DNS or (google DNS servers, or any other DNS you want) in the field Local DNS and Static DNS 1. You need to do this because once the VPN tunnel is up your local DNS will be blocked.


  10. Reboot your router using Administration > Management > Reboot Router button at the bottom of the page.

  11. Once the router has rebooted you can verify that the VPN connection is working by navigating to Status > OpenVPN. You should see something similar to this: 


  12. You can also verify that you are no longer disclosing your real ISP by browsing to http://whatismyipaddress.com/.


Part 2: Blocking all non VPN traffic

Once you have done all of the above steps you should be hidden behind a VPN. The VPN might however go down, and in such cases I wanted to make sure I am not leaking any information by accident. The solution for this is simple and called firewalls and iptables.

  1. Navigate to Administration > Commands on your router and paste the following code into the commands box.
    iptables -I FORWARD -i br0 -o tun0 -j ACCEPT
    iptables -I FORWARD -i tun0 -o br0 -j ACCEPT
    iptables -I FORWARD -i br0 -o vlan2 -j DROP
    iptables -I INPUT -i tun0 -j REJECT
    iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE

    This will allow all connections between tun0 (the VPN) and br0 (your LAN) and also block all traffic between br0 and vlan2 (the WAN port)

  2. Press Save Firewall. The commands tab should look similar to the below picture.


  3. Reboot the router using Administration > Management > Reboot Router button at the bottom of the page.

  4. You can verify that this works by going to Services > VPN and disabling OpenVPN (your settings will not be lost). If everything worked out correctly you should no longer be able to browse to any websites. Enabling (and possibly rebooting) the router should allow you to browse websites again.

Format Currency in C#

2017-01-04 17:00 

Two methods for formatting currency in C#. 

The purpose being that you can throw a string containging a number in it and get out a nicely formatted string containing something you can present to a user.

Example of output.

var amountParsed = FormatCurrency("3123", "USD", true, "Not Known");
> 3 123 USD

var amountParsed = FormatCurrency("31.3", "USD", true, "Not Known");
> 31.30 USD

var amountParsed = FormatCurrency("12343", "USD", false, "Not Known");
> 12 343 USD

var amountParsed = FormatCurrency("XXX", "USD", false, "Not Known");
> Not Known



private static string FormatCurrency(string decimalStringValue, string currency, bool includeDecimals, string emptyPlaceHolder)
    if (string.IsNullOrEmpty(decimalStringValue) == false)
        decimal decResult = 0;
            if (decimal.TryParse(decimalStringValue.Trim(), out decResult))
                string formatted = FormatCurrency(decResult, currency, includeDecimals);
                return formatted;
        catch (Exception) {}

    return emptyPlaceHolder;

private static string FormatCurrency(decimal decimalValue, string currency, bool includeDecimals)
    if (string.IsNullOrEmpty(currency))
        currency = "SEK";
    var decimalTemp = Math.Round(decimalValue, 2);
    var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
    nfi.NumberGroupSeparator = " ";
    string formatted = decimalTemp.ToString("#,0.00", nfi);
    if (includeDecimals == false)
        if (formatted.LastIndexOf('.') >= 0)
            formatted = formatted.Substring(0, formatted.LastIndexOf('.'));
    formatted = formatted.Trim() + " " + currency;
    return formatted.Trim();

Formatting numbers in general is something I disslike and if I have to do it I only want to do it once. So here is a small javascript function I wrote to format currencies with configurable thousand separator as well as number of decimals and what separator for decimals. It also lets you append a string to the end such as "SEK" if you wish to add some form of currency or symbol.

Here is an example of different outputs.

formatMoney('0', 2, '.', ' ', ' SEK')  > 0.00 SEK
formatMoney('', 2, '.', ' ', ' SEK')  > 0.00 SEK
formatMoney('1.23', 2, '.', ' ', ' SEK')  > 1.23 SEK
formatMoney('12345.009', 2, '.', ' ', ' SEK')  > 12 345.01 SEK
formatMoney('5234231.9', 2, '.', ',', ' USD')  > 5,234,231.90 USD

And the code itself.

var formatMoney = function(value, decimals, decimalSeparator, thousandSeparator, currencyString) {
   if (value == null || isNaN(value))
      return "";

   var decimals = isNaN(c = Math.abs(decimals)) ? 2 : decimals;
   var decimalSeparator = decimalSeparator == undefined ? "." : decimalSeparator;
   var thousandSeparator = thousandSeparator == undefined ? " " : thousandSeparator;

   var negativeSign = value < 0 ? "-" : "";

   var valueNoDecimals = String(parseInt(value = Math.abs(Number(value) || 0).toFixed(decimals)));

   var spacingStart = 0;
   if ((valueNoDecimals.length) > 3)
      spacingStart = valueNoDecimals.length % 3;

   var leadingNumber = (spacingStart ? valueNoDecimals.substr(0, spacingStart) + thousandSeparator : "");
   var separatedMiddle = valueNoDecimals.substr(spacingStart).replace(/(\d{3})(?=\d)/g, "$1" + thousandSeparator);
   var decimals = (decimals ? decimalSeparator + Math.abs(value - valueNoDecimals).toFixed(decimals).slice(2) : "");

   var result = negativeSign + leadingNumber + separatedMiddle + decimals + currencyString;
   return result.trim();

Here is also a fiddle with the examples above: https://jsfiddle.net/zdsv09wc/

If you're curious as to whom uses what decimal separator there is a nice chart here explaining how everyone except the EU is wrong: