Passing a ‘Method’ as parameter in C#

This is actually nothing new but sometimes you might still need a quick reference for to remember how to do this quickly… Say you have a generic class that does something like generating a report and display it somehow (or save or whatever the class do) and want all the ‘calling classes’ to just pass the ‘Method’ that it must ‘run’ in order to generate the report. Yes there are probably nice and fancy tools these days that could also do it if you have the mulla for it…

A solution is to use Anonymous methods that has been with C# (.Net) since version 3 of something.

Reporter r = new Reporter();
r.Report = delegate
{
string stuff = "example report yada yada yada";
return stuff;
}
r.Show();

The generic class that provides the ‘generic’ functionality can then look something like this using a defined delegate so it knows what output it will receive when ‘running’ the method.

public delegate string RefreshActionDelegate();
class Reporter
{
    public RefreshActionDelegate Report { get; set; }

    public Show()
    {
       if (Report != null)
       {
          string theContent = Report();
          DoSomethingWithContent(theContent);
       }
    }
}

This is just a quick example but it shows how you can use the main ‘generic’ class from multiple places each time just passing a different ‘Method’ with its own functionality.

GenDB

I’v been involved for many years with helping, developing, working with an uncle of mine’s genealogical research – at least the ‘IT’ side of things. Over this time I developed more than one solution to house a database for storing all the relevant data gathered – first an Access database and later stand-alone application using either the old Access database or newer sql express. Lately I’ve been trying to find a way to get away from the clumsiness of having a separate piece of software installed to get a database. It just makes setting up and maintaining an application so much more difficult – since the type of person using these applications are usually very close to ‘computer-illiterate’ or just doesn’t care ‘how it it works’ but rather just ‘that it to works’.

So I’ve been working to create something that does not require a traditional database but is still easy to maintain and troubleshoot if needs be. I choose to use a plain and simple xml file. You might start to think that this is bad idea because of various reasons like loosing all the features built into professional database systems. But you would be wrong for the ‘wrong’ reasons 🙂 . Let me explain. For the purpose of this system the requirements are different from what you would expect when using a ‘traditional’ database. Consider this – for this little ‘system’ the following are applicable:

  • Single user, single machine use only
  • The volume of data is ‘low’. I can’t imagine someone want to put millions of persons’s information in this little application. I have an actual working example with the information of 11000+ people and the performance is really good.
  • No need for fancy transactionality, relational integrity and other jargon users don’t understand anyway (at the database/file level). The app itself (dal/object level) takes care of it.
  • backups are as easy as simply copying a singe file to some other location
  • although xml is well structured and for ‘computer’ use even a normal user can open the file and view it as text to read it. Of course, they can also easily break it by editing it manually…
  • Fewer components to maintain. No security fixes/service packs of sub components of which most parts are not even used at all. That is the ‘price’ you pay for using a technology that has to cater for lots of different possible ways to use it.
So the little application I created is a plain and simple C# Windows application. All it requires is the ‘client-side’ .Net 4 framework (not even the full thing) which is relatively small these days. It is still really a ‘proof-of-concept’ application but is fully functional and usable.
Summary of the features:
  • Enter/view details of persons (like names, surnames, dates and places of birth/christening/death, parents and children, marriages, history, photos and even unlimited separate notes)
  • View a family tree for a person – both predecessors and descendants  plus a summary of each person (birth/death/marriages). Up to 7 generations (up and down) are allowed but for practical reasons it is better to specify less.
  • There are several built-in reports (too many to name now). Since they are all html based they are easy to export and share with others.
  • Searching for persons (of course)
  • Comparing details of multiple persons (even a graphical view of living-years so you can see who lived around the same time)
  • Mark selected persons as ‘favourites’ so you can more easily find them again.
  • You can have multiple ‘databases’ (files) – simple got to settings and select another file.
  • the .gfdb file extension is associated with the application meaning you can simply double-click  such a file in Windows Explorer/Desktop and it will be opened with the application.
  • Since we mostly use the ‘de Villiers/Pama System‘ genealogical numbering system in South Africa there is some support to automatically generate these numbers based on a person marked as the progenitor.
It also features bilingual ‘run-time’ support which is something you don’t find often in applications. At the moment it support both English and Afrikaans.
Data format
I did consider GEDCOM and even GEDXML at some time but both have ‘issues’ of their own. GEDCOM is a text flat file format that is not very user friendly and easy to ‘break’. It is very widely used though. GEDXML is not really a standard format at all. They started working on it and abandoned it after a while – not sure why.
‘My’ format is not really a standard on its own – I’m not claiming it to be super or fantastic. It is plain and simple and works for my purposes.
Installer

Grab a copy of the installer here and let me know what you think. The zip file contains an example gfdb file containing some (fictional) Star Wars character information to illustrate how the application work.

Update: Version 1.1 available here.

Another Update: Version 1.2 available here

Formatting C# code in WordPress post

If you are like me working with C# a lot and trying to post articles on your WordPress site you might like this: Alex Gorbatchev’s SyntaxHighlighter

Example source code listing

[ sourcecode language=”csharp” ]
void Stuff
{

int moreStuff = 0;

}
[ /sourcecode ]

Would look like this:

void Stuff
{
    int moreStuff = 0;
}

I haven’t tested it with all possible language features but at least it is a start!

Not a good day to be a chair…

Ok this could be hilarious if it was even more funny… Forbes named the top ‘worse’ CEO’s of all companies and Microsoft is at the top (or is that bottom…). I’m sure some investors would not be impressed.

Lets hope the chairs at Redmond have all their life cover up to date. This could be the end….

Too old to be a ‘software engineer’?

One of the newsletters (emails) I subscribe to recently had an entry about the issue ‘Is Software Engineering Dead?’ – by Steve Jones. This is so true…

Let me ‘copy’ the editorial here:

Is Software Engineering dead? It’s a premise that’s in this article from Bloomberg. It calls the job a career dead end where job prospects decline after one reaches 35 years of age. I think that’s a naive view of the industry, despite the quotes from Craig Barrett and Mark Zuckerberg. While the best of the best might peak in their careers at the same age as many athletes, that doesn’t imply that the career choice is a poor one.

There’s a discussion on Slashdot as well, and I was struck by a few of the comments, which seem to suggest that if you are still just a “software engineer” at age 40, you aren’t very good at your job. It seems that some people seem to think that everyone in this business is constantly looking to move to a new job and advance into management or they aren’t successful . I saw analogies with other industries thinking that same thing, that experienced people would not still be doing the same job after 20 years.

That seems crazy to me. So many people in various industries continue to improve at their jobs, and do the same work for decades. Carpenters, doctors, accountants, all continue to improve their skills over time, and while some may more into management or open their own firms, many will continue to do their same jobs until they retire. And they’ll enjoy their careers.

I don’t deny that ageism exists, and that older programmers often can’t, or won’t, work as many hours as younger ones, but that doesn’t mean they aren’t worth their salaries. Good, experienced programmers produce better code, with fewer bugs. Once managers learn that working more hours doesn’t equal better code, or even more code, the entire industry will start producing better applications.

Steve Jones from SQLServerCentral.com

Well now, without giving away my age too easily.. (cough cough) I’m afraid I’m this piece is very relevant to me too. I’ve been in the software/development/computer/IT industry for many many years (~16+ year) and I still enjoy the basics of software development – but I’ll admit I’m not doing as much as I use to and definitely not as many different things, including new stuff all the time. So is it possible to go on as a ‘software engineer for ages over (say) 35? The perception out there seems to be you have to move into ‘management’ or so in order to ‘progress’ in your career. Trouble is I’m not a ‘peoples’ person and I don’t like managing them either. Is that wrong? Should I be forced to do something I don’t like and probably won’t be good at? Flip-side – Is it wrong to stay with something you like for your whole career? Certainly the market don’t appreciate you – since it doesn’t count how many years experience you have, at a certain point you just don’t get paid any more than before. Personally I think that is an insult and that ‘we’ are worth more not just because of the years of good experiences we have but also the bad things we learned ‘not to’ do. Perhaps there is a place for a more ‘mentoring’ role – which is different from managing a person.

I must admit that lately in my ‘day job’ I’ve been more into ‘administrating’ (BizTalk) than actually developing. This too is sort of just another part of software engineering as it requires me to find clever and original ideas to do my job as other ‘developers’ keep on finding interesting ways of breaking the things I have to administrate. In my personal time in non working hours I still work on ‘pet’ projects mostly around genealogy projects. Some things in life do get better with age – like red wine…

Lets drink to that… (responsibly of course) 😉

Linq – group by multiple fields

Seems this is an issue that multiple people have asked around at several occasions.

The question is how to use a Linq query where you want to group on more than one ‘field’

Turns out it is really not that hard. Thanks to ‘Anonymous’ methods that was also introduced ‘yay back’ it is as simple as the following example. Lets say you have a list of values like these:

Person 1: Age = 25, Gender = M, HighScore = 123
Person 2: Age = 21, Gender = F, HighScore = 99
Person 3: Age = 27, Gender = M, HighScore = 140
Person 4: Age = 19, Gender = M, HighScore = 131
Person 5: Age = 25, Gender = M, HighScore = 119
Person 6: Age = 22, Gender = M, HighScore = 108
Person 7: Age = 27, Gender = M, HighScore = 152
Person 8: Age = 21, Gender = M, HighScore = 98
Person 9: Age = 22, Gender = M, HighScore = 101
Person 10: Age = 25, Gender = M, HighScore = 167
Person 11: Age = 22, Gender = F, HighScore = 105
… etc

To get a simple report on average high score by Age and Gender you’ll have to use a query like this:

foreach(var entry in (from p in Persons
group p by new {  Age = p.Age, Gender = p.Gender } into g
orderby g.Key.Age, g.Key.Gender
select new
{
Age = g.Key.Age,
Gender = g.Key.Gender,
Avg = g.Average(pavg=>p.HighScore)
} ))

{

Console.WriteLine(“Age: {0}, Gender: {1}, Avg: {2}”, entry.Age, entry.Gender, entry.Avg);

}

Perhaps it might have simpler if you could simply have stated : “group p by p.Age, p.Gender” but unfortunately this is not supported. Then again this allows you to be more creative in defining the anonymous type so you can manipulate the data even more. Perhaps in the next version of Linq… if there is ever one…

 

Fun in the sandpit.. or not

Just a few comments (just my thoughts) about the whole ARM version of Windows 8 that won’t allow 3rd part browsers (desktop apps).

In  a way this is not Microsoft’s fault as the underlying architecture (processor) is totally different meaning applications (the actual binaries) need to be written to support this – and that is up to the developers of the app. Then again, Microsoft is creating the operating system which ‘host’ the applications and provide the API’s that the applications should use. It all depends on ‘how’ the applications are written how tightly they are tied to the underlying infrastructure. In an ideal world the OS should provide ‘ALL’ the API’s that any applications might need so they never need to be even aware of the actual hardware they are running on. I’m not sure is that is the case for Firefox or Chrome (they might have their own optimized code to better make use of specific hardware… but I don’t know).

The other problem is that Microsoft is trying to move away from the whole Windows API (at least the i386/Win32 stuff) which is a problem for ‘real’ applications (a I would have called them). Microsoft has been busy for years to try and create a new ‘middleware’ layer they call ‘.Net framework’ that should ‘shield’ applications from hardware details. Unfortunately very few of the larger application providers has ever taken .Net seriously (including some MS departments themselves).

Perhaps a simpler metaphor could explain this ‘issue’ better. Say we see the ‘OS’ as a sandbox (like a real one kids play in…). The applications are the toys. The users are the children playing in/with the sand (and yes, kids sometimes through their toys out the… you know…). Now MS is trying to make a new sandbox with a different type of sand but the toys weren’t made to work with that kind of sand (ye ye its fictional). The guys making the ‘toys’ are now complaining that their ‘toys’ won’t work in that sandbox which mean the kids there won’t be able to play with them. Big deal! So what? Perhaps the toy makers must just make their own damn sandbox (which they already have/or are in the process of making). As things look now there won’t be too many kids in this new sandbox anyway (my opinion) and it will fail miserably (since that other fruit company already has a new BIG and exciting sandpit where all the new ‘cool’ and ‘hip’ kids hang out…

Seems to me there will be a whole lot of toys and sand being thrown around soon with a lot of kids ending up with sand in their faces/mouths so no one is gona be ending on a happy note. Perhaps its time someone clean out their own sandpit of all the ‘bad’ stuff in there already before they think of getting a new one… hehe Jus saying….

Portal editor

No, this has nothing to do with real programming (those SharePoint guys…) 😉 Rather, it’s about the Valve game Portal 2 that now has a editor to create your own levels. See this.

This started me thinking… What if… other publishers can catch a hint and provide an editor to say… Mass Effect 3 Multiplayer. Just think…. You will of course have to share your maps to all the players that want to join in and so on but that would be obvious (unless you want to surprise everyone with hidden dangers and stuff hehe).

What would be needed? First a terrain editor (think of the old Sim City games), then buildings (think of the The Sims like games) and finally something like the Portal editor (though Sims editor also contain loose items inside buildings…). They can of course provide a series of ‘default’ terrain maps as well. If someone ever created something like this it could start a new game creation craze and perhaps some fun for a few million people (gamers). Perhaps better yet – what if you can ‘string up’ some maps in a sequence and you have the building blocks to create your own game/world. Of course, creating a fully functional game on its own would be a lot more complex than this. I’ve been thinking/dreaming of something like this for year actually. If only I had the time/skills/tools to do it…

Is someone out there taking notes? (throwing hints in BioWare’s/Valve’s direction hehe)

ME3 war assets

Well, I started a second play-through of the game to try and ‘max’ out everything I could or do it as best possible. In the process I discovered a few ‘mistakes’ I made during the first attempt – like loosing Miranda (don’t ask me how I managed to to that).

As far as alien assets I got all the possible fleets including both Quarian and Geth fleets. Previously I could not for the life of me get both – had to choose between them. It turns out you have to leave the Rannoch missions until the very end so your Paragon/Renegate is high enough to choose one of the ‘overriding’ dialogue options. In the first iteration I even managed to get Tali to commit suicide… ouch!

Another thing I discovered that I didn’t know before was that the Omega missions are not accessible if you have Mordin and the Genophase cure saved since Maelon isn’t required to get the possible cure anymore. I happened to have both so I missed the Omega mission(s) again. Then there was the pleasant surprise to have Miranda survive her Horizon mission. Again I managed to miss the critical dialogue decision the first time that managed to ‘save’ her.

So in the end I managed to gather a war asset strength of just below 8000 (7978). I promoted a couple of multiplayer ‘squads’ as well that helped and I could have tried to add some more if I wanted.

Of course to actually make use of all those assets you must play the multiplayer (each day to keep it 100%). I’ve started to really like it but there are a couple of things I could suggest they add to the multiplayer ‘experience’ – like having the ability to invite friends from in the game (say on the lobby screen or just after finishing a good game where you were impressed by someone).

I also like the new multiplayer manifest pages they added (e.g. mine). They should also add stats on your kills as well as kill count per weapon/power. This could make it useful to see what weapons/powers you do the best with so you can enhance it or improve how you play. Of course, this is also useful to see how your friends are doing and how you all can compliment each other.

A couple of screenshots of the war:

The fleets arrive!

This sequence really is the epic high-point of the whole ‘Mass Effect’ series. The moment you/Shepard worked to hard to achieved. Pitty it turned out to be all for nothing…

And starts to move towards Earth…

Open fire!

Engaging the Reapers

Fighters enter the battle…

Fighters start to move around

The Reapers starts returning fire!

Alliance ship gets blown to hell (and back)

Chaos, blood and guts and more chaos!

This is not war – this is carnage and the Reapers are feasting…

Update: Well I’ve finished the game again – this time with fleet strength maxed out so that when I chose the ‘destroy’ option (don’t get me started about the bad ending again…) that hidden/secret video clip plays hinting that Shepard may still be alive. To be honest – that is more like I would have liked the game should have ended… Alternatively, a clip of Shepard and Garrus meeting at the bar (in heaven) should have been played… (ok but Garrus is not dead yet in ‘my’ game’s ending…).

Loading custom resources

The idea to use ‘custom’ resources in a .Net app might not make sense for all – and there may be times when it does not make sense at all since .Net apps (using VS.Net) have a built-in editor to manage embedded resources for an app. But… {here it comes} there could be some more flexibility to do it yourself like the ‘resource files’ does not have to be all located in the same directory (from a source point of view) and you can choose whether you want to include the files separately from the main executable when distributing the app.

First off, to you have to add a file (the resource) to the project – either by using the ‘Add new Item’  or ‘Add Existing Item’ context menus. Then under ‘Properties’ of the file ‘Build Action’ to ‘Embedded Resource’. Optionally you can set the ‘Copy to Output Directory’ but for this blog entry it won’t be used. Take note of the relative directory name (to the project’s root) since that will become part of the name of the resource – including the exact ‘case’ of the letters. For example, adding a text file named ‘CreateTables.sql‘ under a project directory ‘SQL‘ would result in a resource name ‘<Default namespace>.SQL.CreateTables.sql‘. Yes that is correct, the default namespace of the project is prepended to the full resource name.

Now to use the resource file (actually only the content since the file name has no use inside the project) you can use the following code:

public static string GetResourceByName(string name)
{

Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(name);
System.IO.StreamReader sr = new StreamReader(s);

return sr.ReadToEnd();

}

…

string sql = GetResourceByName(‘myNamespace.SQL.CreateTables.sql‘);

One small note: this example code does no error checking.

You can make the resource name a constant inside the project or create an enum using something like a string value attribute to match the enum entries to a string or something. Also, this example assumes the content is a text file but you can use the same principle of any type of content (like images, audio, video or whatever).