C++: Using the Luhn Algorithm to Validate the CheckSum in the Personnummer Supplied in User Input

The Swedish Personnummer uses a variant of the Luhn Algorithm to generate a checksum (technically, a check digit) value that is is appended to the end of the personnummer. So, forexample, the nine-digit number YYMMDD-SSS would become YYMMDD-SSSC with the tenth digit being the checksum.

The model for generating the checksum is created by multiplying the alternating digits by a 2 or a 1 and, then, adding the sum of the products. In the nine-digit series, this means 212121212. So, for example, the number 010214-010 would become (0x2) + (1×1) + (0x2) + (2×1) + (1×2) + (4×1) + (0x2) + (1×1) + (0x2). When the product is greater than nine, the sum of those numbers is added. So, for example, 2×7 = 14 –> 1 + 4 = 5 and, thus, our result would be five for that single instance of digit.

The last number in the sum is then subtracted from 10 to create the checksum number. So, for example, 46 –> 6 and 10-6 = 4, and 4 becomes our checksum value.

Below is an C++ program to validate the checksum for the provided personnumer, given in the user-input. PersonnummerSet is merely a struct of ints that I’ve created in a header file, so that it can be referenced by other libraries (either by direct assignment to type or pointer). StringMagic is another header file that uses std::string.erase/std::remove to remove the ‘-‘ character from the input (Swedish Personnummers are always written as YYMMDD-SSSC.)

#include <cstring> // Replacing the old and busted with the new hotness.
#include <iomanip>
#include <iostream>
#include <cstdio> // Replacing the old and busted with the new hotness.
#include "Personnummerset.h"
#include "StringMagic.h"

class Personnummer
{
public:
    /**
     *  The PersonNumber is a property of type PersonnnummerSet, which is used to process the digits
     *  from the personnummer provided.
     */
    PersonnummerSet PersonNumber {};

    /**
     *  Initializes a new instance of the <see cref="Personnummer" /> class.
     * @param number - The converted long from the user's input.
     */
    explicit Personnummer(long number)
    {
        // We separate the three digit serial to future-proof for deriving sex of the individual in future checks.
        this->PersonNumber.Year = static_cast<int>(number / 100000000 % 100);   // First 2 integers     (0&1)
        this->PersonNumber.Month = static_cast<int>(number / 1000000 % 100);    // Second 2 integers    (2&3)
        this->PersonNumber.Day = static_cast<int>(number / 10000 % 100);        // Third 2 integers     (4&5)
        this->PersonNumber.SerialNumber = static_cast<int>(number / 100 % 100); // Fourth 2 integers    (6&7)
        this->PersonNumber.Sex = static_cast<int>(number / 10 % 10);            // First 1 integer      (8)
        this->PersonNumber.CheckSum = static_cast<int>(number % 10);            // Second 1 integer     (9)
    }

public:
    /**
     *  Generates the Luhn Algorithm checksum and compares that from the checksum given from the user's input.
     * @return A boolean indicating of the calculated checksum matches the provided checksum.
     */
    bool ValidateCheckSum()
    {
        return this->PersonNumber.CheckSum == this->GenerateChecksum();
    }

private:
    /**
     * This is a variation of the Luhn Algorithm, which is used to generate the checksum from the
     * first nine digits of the personnummer. Each value in the first nine digits is multiplied by
     * either a 2 or a 1. See: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2773709/figure/Fig1/
    */
    int GenerateChecksum()
    {
        int firstCheck;
        int fifthCheck;
        int seventhCheck;
        int ninthCheck;
        int firstYear = PersonNumber.Year > 9 ? PersonNumber.Year / 10 % 10 : 0;
        int secondYear = PersonNumber.Year%10;
        int firstMonth = PersonNumber.Month > 9 ? PersonNumber.Month / 10 % 10 : 0;
        int secondMonth = PersonNumber.Month%10;
        int firstDay = PersonNumber.Day > 9 ? PersonNumber.Day / 10 % 10 : 0;
        int secondDay = PersonNumber.Day%10;
        int firstSerial = PersonNumber.SerialNumber/10%10;
        int secondSerial = PersonNumber.SerialNumber%10;

        int firstYearDigit = firstYear * 2;
        if (firstYearDigit > 9)
        {
            int firstSum = firstYearDigit/10%10;
            int secondSum = firstYearDigit%10;
            firstCheck = firstSum + secondSum;
        }
        else
        {
            firstCheck = firstYearDigit;
        }

        int secondCheck = secondYear * 1;
        int thirdCheck = firstMonth * 2;
        int fourthCheck = secondMonth * 1;
        int firstDayCheck = firstDay * 2;
        if(firstDayCheck > 9)
        {
            int firstSum = firstDayCheck/10%10;
            int secondSum = firstDayCheck%10;
            fifthCheck = firstSum + secondSum;
        }
        else
        {
            fifthCheck = firstDayCheck;
        }

        int sixthCheck = secondDay * 1;
        int firstDigitRandom = firstSerial * 2;
        if (firstDigitRandom > 9)
        {
            int firstSum = firstDigitRandom/10%10;
            int secondSum = firstDigitRandom%10;
            seventhCheck = firstSum + secondSum;
        }
        else
        {
            seventhCheck = firstDigitRandom;
        }

        int eighthCheck = secondSerial * 1;
        int sexCheck = PersonNumber.Sex * 2;
        if(sexCheck > 9)
        {
            int firstSum = sexCheck/10%10;
            int secondSum = sexCheck%10;
            ninthCheck = firstSum + secondSum;
        }
        else
        {
            ninthCheck = sexCheck;
        }

        int sum = firstCheck + secondCheck + thirdCheck + fourthCheck + fifthCheck + sixthCheck + seventhCheck + eighthCheck + ninthCheck;
        int lastOfSum = sum%10;
        int checkSum = 10 - lastOfSum;
        return checkSum;

    }
};

int main()
{
    std::string user_input;
    std::cout << "Enter Personnummer (YYMMDD-SSSC): " << std::endl;
    std::cin >> user_input;

    // Necessary or the long conversion treats '-' or '+' as a delimiter.
    // NOTE: People aged over 99 will always have '+' in their personnummer.
    if(user_input.find('-') != std::string::npos)
    {
        StringMagic::RemoveDashFromString(user_input);
    }
    else if (user_input.find('+') != std::string::npos)
    {
        StringMagic::RemovePlusFromString(user_input);
    }

    // Smart-pointers are the future...
    std::unique_ptr<Personnummer> personNumber (new Personnummer(std::stol(user_input)));
    std::cout << std::boolalpha;
    std::cout << "CheckSum Passes: " << personNumber->ValidateCheckSum() << std::endl;

    personNumber.reset();
}

The above code can be used to validate almost any personnummer – save for those individuals whom are over 99 years of age, as the separator changes from ‘-‘ to ‘+’.

…and that’s about the extent of fun with Swedish Personnummers in C++ that this post will cover.

Thanks for coming to this NERDTalk™ and happy programming!

C++: Learning About Virtual Classes

Over the weekend, I was given something to learn for a potential job (in Sverige) and that was Virtual Classes in C++. If you’re familiar with Partial Classes the idea kind of related, only it’s better. I’m sure how much of a pain it will be to debug but that’s the next thing that I want to test.

Anyways, Virtual Classes work off of inheritence and just like inheritence, you’re “wrapping” one object around another but with virtual classes, the exposure is seemless.

Take these two classes for a principle example:

#include iostream
#include cstring // Replacing the old and busted with the new hotness.

class LabEquipment
{
    public:
        explicit LabEquipment(int number)
        {
            std::cout << "Lab Equipment: " << number << "\n";
        }

        virtual void LabWrite(std::string message)
        {
            std::cout << "Writing " << message << " from LabEquipment.\n";
        }
};

class Tubes : virtual public LabEquipment
{
    public:
        Tubes(int tubes, int number)
                : LabEquipment(number)
        {
            std::cout << "Tubes: " << tubes << "\n";
        }

        virtual void TubesWrite(std::string tubesMessage)
        {
            std::cout << "Writing " << tubesMessage.c_str() << " from Tubes.\n";
        }
};

I can then write the following to leverage both Tubes and LabEquipments classes:

// Object
Tubes tubes(2, 3);
tubes.TubesWrite("hello");
tubes.LabWrite("hello, again, ");

// Pointer
Tubes * pTubes = new Tubes(3,4);
pTubes->TubesWrite("hello");
pTubes->LabWrite("hello, again,");

If I debug this in CLion (on Ubuntu 18.04LTS), then I get what I would expect:

Lab Equipment: 3
Tubes: 2
Writing hello from Tubes.
Writing hello, again,  from LabEquipment.
Lab Equipment: 4
Tubes: 3
Writing hello from Tubes.
Writing hello, again, from LabEquipment.

Note that I didn’t have to do anything else but declare the class’ inheritence for the methods to be exposed. None of that this stuff is necessary for it for it to be exposed, as it’s purely abstracted from the child to the parent.

In this way, C++ affords more versatility that .NET, in that, if I truly need to change any part of a class, there needn’t be any further changes – save on the caller.

Now, suppose that I declare the same method twice:

class ShowMessage
{
    public:
        explicit ShowMessage{};
    
        void virtual OutMessage(std::string message)
        {
            std::cout << "Writing " << message << " from WriteMessage.";
        }
};

class DisplayMessage : virtual public ShowMessage
{
    public:
        DisplayMessage()
                : ShowMessage()
        {};
        
        void OutMessage(std::string message)
        {
            std::cout << "Writing " << message << " from DisplayMessage";
        }
};

Our compiler, if it’s anything worwhile, should immediately alert us that we hiding the method; which, in this case, happens.

Markering_027

The IDE telling us that we’ve errored and suggesting ways to fix it.

If we override the method we can just drive on, as if nothing ever happened. We can also delete the method in DisplayMessage (which is what we should really do, as it’s redundant code already accomplished from within the ShowMessage class).

Now, let’s suppose we look at properties. Here’s a basic set of classes with int properties:

class FirstCount
{
    public:
        int Forsta;

    public:
        explicit FirstCount(int count)
        {
            Forsta = count;
        };
};

class SecondCount : virtual public FirstCount
{
    public:
        int Andra;

    public:
        SecondCount(int secondCount, int firstCount)
                : FirstCount(firstCount)
        {
            Andra = secondCount + Forsta;
        };
};

We can then construct an object that references them.

SecondCount secondCount(240, 547);
int first = secondCount.Forsta;
int second = secondCount.Andra;

When we debug, we can see that the value is what we’d expect (without having to have had used this).

Markering_028

You can see that the vlaue for second/Andra is the sum of 240 and 547, the 547 having been passed through from the FirstCount class.

…And that’s about as far as I’ve gotten, really… There’s a whole diamond thing that we could get into but I can’t be arsed to get that complicated with it, yet.

Anyways, thanks for coming to this NERDTalk and happy programming!

C#: Returning an Object via System.Threading.Tasks.Task

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

In programming something (in EWS), discovered the joys of what I believe was ‘lock contention’. To explain, first we need to cover Tasks.

Async Tasks (which call ‘await’ against other tasks) will only perform the action requested, if you do not specify a managed object to handle. For example, if I call an async for a string and do not specify that I am expecting an object in return, this is what the code will look like (and will introduce our problem):

string noDataReturns = await System.Threading.Tasks.Task.Run(() => this.GetMeTheStringAsync().Result);

private async Task GetMeTheStringAsync()

{

return await System.Threading.Tasks.Task.Run(() => this.GetMeTheString());

}

private string GetMeTheString()

{

return “This is not the string you’re looking for.”;

}

If, instead, I tell the task what object I expect to get in return, when the task completes, the result will be object that is passed back – instead of the result of the task:

string dataReturns = await System.Threading.Tasks.Task<string>.Run(() => this.GetMeTheStringAsync().Result);

private async Task<string> GetMeTheStringAsync()

{

return await System.Threading.Tasks.Task<string>.Run(() => GetMeTheString());

}

private string GetMeTheString()

{

return “This is the string you’re looking for.”;

}

This is probably common-place parlance in the .NET developer’s world but I had discovered this when I was spawning a Task that would return a DataTable object but did not specify that I expecting an object in return. As such, the windows form was rendered useless/locked, as I placed the DataTable’s data source as the result of the Task but there was no data to put in the data table.

 

C#: Returning ADSI COM Properties of a User Object (Or Any Object, Really)

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

A few months ago, I was working on a project to query for specific AD properties of a user-object programmatically. I knew the properties I wanted to return and I had worked with returning properties in ExBPA/HRC. I hadn’t, however, found the joys of receiving a System.__COM object in any of my returns until now.

To explain this, you should familiarize yourself with ADSI (Active Directory Service Interfaces), if you’ve never been exposed to it, before. As the previous link points out, ADSI is a COM (Component Object Model), and – as such – we will get a return of ‘System.__COM’, if we fail to pull the data in the expected format.

So, how was I to return the data from the COM? Well, as it turns out, there’s ‘deprecated’ documentation which helped me farther than any blog, technical bulletin, or reference did. You can find it, here. (Apologies, apparently all of the English versions have been pulled because it was deprecated.)

Using some ingenuity and a little luck, I found the answer to my problem: return the value I’m querying for as ‘ActiveDs.IADsLargeInteger’.

So, armed with this knowledge, I could now pull the properties I wanted to return in usable context, like the following:

ActiveDs.IADsLargeInteger recipientTypeDetails = (ActiveDs.IADsLargeInteger)userResult.Properties[“msExchRecipientTypeDetails”].Value as ActiveDs.IADsLargeInteger;

Once I had the data ‘out’, as it were, I could try to manipulate it:

long recipTypeDetails = recipientTypeDetails.LowPart;

 

I realize this doesn’t mean much to some people (maybe a lot) but I figured if I could save one person the hours it took me to find the answer, then it was well worth the time in writing this.

Happy coding!