Falling in Love with Metro

Lots of things have happened since I wrote my last entry about Windows Phone programming nearly a month ago. I didn’t use this time to finish of my first simple app but to delve into all kinds of technologies available on Windows Phone platform. Today I ported my old audio generation library to WP environment and got self-generated, high-precision beeps out of my HTC. Having seen my algorithms run smoothly it is very likely that my first app on Marketplace will have something to do with audio.

One thing that happened during this month was that I practically fell in love with Metro, the design language and principles of Windows Phone. A major event for me was the Metro UX sessions by Albert Shum, Corrina Black and Arturo Toledo at MS TechNet 2011 in Helsinki. These guys really knew how to convey the great ideas behind Metro to designers and developers. I’ve been quite excited about Metro since then and craving to design for Metro and Windows 8 at my daytime job, too.

So now I know how to design and how to code for Windows Phone. The only thing I must still find is time to write my first apps, but I hope Santa will bring me some peaceful days during the next few weeks :)

My First App on My HTC

I just ran my first homebrewn application on my HTC 7 Trophy. It was easy! I started on this app several months ago when Mango was not available yet. At that time there were problems joining the Windows Phone Marketplace developer program from Finland so I could only run the app on the phone emulator. If an application is supposed to send SMS’s, it’s not very useful when running on the emulator that only mocks sending an SMS.

After Mango was out, I managed to join the Marketplace, and today I finally had the time to register my phone as a development and debugging device. In just a minute I had the application running on my phone, picking phone numbers from my contacts and sending real SMS’s. Painless, I would say!

My application is very simple, but it’s genuinely useful. It is very likely it will be available on the Windows Phone Marketplace after some polishing. I’ll drop a note here when you will be able to enjoy it, too :)

The Sweet Taste of Mango

Yesterday was my lucky day: I got Spotify on my HTC 7 Trophy. This was the final point to convince me that Windows Phone 7.5 will be *the* platform I’m going to use in my daily mobile life.

I have been using Windows Phone 7.5 aka Mango for more than a month now. When I bought my HTC in last December, I was a bit disappointed with the features Windows Phone 7.1 had. Mango made a big difference and placed Microsoft into the lead of the competition. Mango is elegant, responsive, and packed with creative usability ideas.

What I especially like in Mango is the People Hub. Updating my Facebook status and checking my friends’ status updates goes in a snap and is even easier than using the dedicated Facebook application. The idea of integration goes through all the PIM apps including the Linked Inbox and combined Calendar.

And yes, I just love the Office suite and how it integrates with SkyDrive, the cloud data storage of Windows Live. For instance, I can write a shopping list on my home or work PC using OneNote and then open it on my phone checkmarking bought items, adding new items etc. Or I can start a Word document on my phone and finish it off on my PC without having to take any additional steps to synchronize or copy it from one platform to another.

Before I got Mango I was using another HTC phone, namely HTC Desire running Android. I kind of liked Android, but it hasn’t got the style and simplicity of Windows Phone. I have been saying that Android is for geeks but Windows Phone is for people, and even if I sometimes count myself a geek, I prefer the Windows approach where functionality and ease matter more than the abundance of options.

So Mango fulfills all my mobile communication needs – almost. What I miss is the ability to share the Internet connection with my laptop which would mean USB tethering or setting up a WiFi hotspot. I know that Mango has got this feature, but the phone manufacturer has to support it, presumably with some kind of hardware solution. Having this feature on Desire, it’s too bad HTC doesn’t support it on Trophy, but things will be even worse if none of the Nokia Lumia models won’t support it – I have not seen any mention of this feature in Nokia’s pre-release material yet. I was planning to buy a Lumia 800 when it’s available, but maybe I’ll have to keep my Trophy and buy a 3G dongle with a cheap data plan in stead.

Anyway, providing an Internet connection for my laptop is not a major issue compared to what I find most exciting with Windows Phone, and that is, of course, programming for it. Being quite fluent with Microsoft programming tools I’m looking forward to being able to produce innovative solutions with reasonable pain, but that should be the subject of another post or rather a series of posts. Stay tuned!

Life without ‘if’s

A terrible week behind! After being privileged to work with WPF, I had to concentrate on fixing nasty bugs and adding requested new features to a “nearly finished” project we have been coding with six other developers. I felt *so* guilty because all I could do last week was to add more code lines and if statements to these sources my colleagues already have decorated with myriads of ifs. Sometimes it saves my day if I manage to reduce a prolix code passage into one line of just-to-the-point code. Last week there was no such day.

Every if statement we write makes our future life more miserable. The more ifs your code contains, the harder it is to grasp and maintain. If a logical inference doesn’t fit on one screenful of code, it is likely that a colleague that is going to maintain your code will not get your idea and only makes it worse with new ifs.

Ever had this feeling that the world would be a better place without if statements? When you write an if, your code “depends”, it’s contingent. Sometimes you can never be sure which branch of your code will actually execute. On the other hand, a code passage with no ifs can be thought of as necessary – it is always executed just the way you wrote it. The worst if is the one you write “just in case” when you have no idea what the actual situation will be when your code executes.

There are religions and even actual people that believe everything in the world was predestined – God needs no ifs. Being a mere mortal I must admit that I don’t know everything in advance and hence need to adapt to alternate situations with ifs. But there are things we know, and based on these things we must try to comprehend the world around us and express it as clearly and plainly as possible in our code. If you want to obscure the idea behind your code, write as many if statements as possible!

Let’s take an example! This is actual code I found on a project a few years ago. Based on a given sum value, it calculates the check digit of a Finnish bank reference number:

CheckDigit_a

Unaware of the existence of this code, I wrote my version like this:

CheckDigit_b

Look Ma, no ifs! To be honest, one if statement doesn’t make the whole difference here, and the first code line already shows that the author of CheckDigit_a has not comprehended the real idea behind this calculation. At the end of the code, it is not Destiny that decides whether the value of sum is 10 or not. It is something that can be calculated, and whatever the value is, it is necessarily what it is, not contingently. Once we are given a value for sum, the return value is implied and fixed – there is no room for hesitation, no ifs left!

Now we come to the point: Using an if statement is OK and even necessary when the condition is genuinely contingent, i.e. it comes from sources like user input, a value in a database column etc. When not, you should first consider saving one if and think whether the situation could be handled otherwise.

Since we cannot totally live without if statements, I would like to suggest that in order to keep the total number of ifs as low as possible, programmers should pay a fine for every if they write. If you want to have something left for the payday, consider the following:

  • Use arithmetics, character functions etc. where possible!
  • Try to reduce the amount of nested ifs by making an analysis of your conditions. Using a pencil, a piece of paper, and truth tables is a good method when the situation seems too complex to grasp. This way you will probably be able to combine several if statements into one and perhaps even find a branch that will never execute.
  • Use the ?: conditional operator for atomary conditional situations. Logically it is equivalent with if, but compact as is it, it is easier to perceive as one logical unit so that it does not blur the larger if construct it might be part of.
  • Use the switch statement instead of if .. else if statements where possible.
  • Don’t use if like duct tape! It might look like an easy solution to add just one little if, but analyzing the code a bit further might produce the real solution to the problem.

If your project shows a tendency towards an ever-growing number of if statements, there must have been something wrong at the very outset. Use cases might have been forgotten or all possible situations were not taken into account in class design. Or maybe the design was too complicated because it didn’t hit the target: You needed a nail file but you designed a Leatherman.

“Well planned is half done” goes the common saying, which we could turn into “Badly planned needs more and more ifs”. When your code is becoming bloated with ifs, it could be still possible to save in the total amount of work by redesigning your application. In real life this is hardly possible because somebody would have to admit that there was something wrong with the initial design, so all you can do is to learn from your mistakes, try to get rid of the project, and to be wiser at the next project, if there is going to be a next project!

Final Countdown for GDI

After writing my previous post, I happened to pass by my archival bookshelf, and an opus caught my eye: Programming Windows by Charles Petzold from 1988. It has been ages since I last opened this classic, and yet, if I narrow my eyes a bit, it looks like it was written yesterday. What we call Win32 API today was just Windows API in 1988, but the 16-bit ancestor is amazingly similar to its 32-bit offspring. Even if we program in a high-level language like C# and use the .NET Framework, this ancient API dictates a lot we do with managed classes. Especially this goes for GDI (in Windows API) and GD I+ (in .NET Framework).

When Graphics Device Interface (GDI) was introduced, there were no hardware-accelerated display adapters. All the grunt work of calculating logical coordinates to physical pixels had to be done by the main processor, either in the application program or in Windows (i.e. GDI). Because performance was rationed, optimizing graphics performance was a joint venture between Windows and the application. Windows tried to be as helpful as possible, but the decisions were left to the application that knew what had to be done and was able to choose the right strategy.

This strategy was known as the “mapping mode” that is still present in GDI+ as the GraphicsUnit property of the Graphics class. In fact all major structures and functions in GDI find their counterparts in GDI+ as properties and methods of Graphics: hDC -> Graphics, SetViewportExt() -> PageScale, SetViewportOrg() -> TranslateTransform(), MoveTo()/LineTo() -> DrawLine(), Ellipse() -> DrawEllipse(), etc. to name just a few. This is all logical because GDI+ has to call GDI to get the pixels all the way to the display device.

Now enter Windows Presentation Foundation! WPF is different because it does not use GDI but gets its message to the display surface through DirectX. Game developers and enthusiasts have known for years that DirectX can use hardware acceleration, which GDI can’t. The mapping mode is gone: WPF uses device-independent pixels, each of which is defined to be 1/96th of an inch. Mapping to physical pixels is done by DirectX assisted by display adapter hardware, which the application can be totally agnostic of.

Drawing methods like DrawEllipse() are also gone – you just place graphic elements like Ellipse or LinearGradientBrush inside other graphic elements, and WPF gets them painted. I would see this as a significant move from imperative to declarative programming, which becomes more obvious if you create these elements in markup (XAML) rather than code (C#). In plain English this means that you tell WPF what you want, not how to do it. I like declarative programming!

I now place Programming Windows back in my shelf next to Kernighan & Ritchie and The MS-DOS Encyclopedia. Sleep well, my friend!

WPF Rules!

I have seen the future, and it works! I just completed my first WPF project and was positively surprised. WPF has been blamed for poor performance, but the result of my work runs fast even on plain-vanilla displays, and it isn’t such a resource hog as blamed, either.

My project was a user control to be seated in a Windows Forms environment – a window into the new world, so to say. The control displays a scrolling structured document that responds to many mouse and keyboard events. The reason it was developed was to replace a document viewer control based on the Windows Forms WebBrowser control that caused a lot of problems. The new control displays a XAML FlowDocument instead of HTML, and, best of all, it doesn’t use any COM.

Struggling with HTML to make the document interactive was a chore and demanded a lot of JavaScript and DOM. Now every single element in the FlowDocument is a C# object and directly accessible. Boy, I like that!

Somebody might say that the future I’ve seen a glimpse of was planned by the Evil Empire. Evil or not, none else but Microsoft has put forward such an innovation to GUI programming. I have nothing against Open Source, but no player on the Open Source field has had the muscle for such an undertaking. Maybe some day WPF will be implemented on Mono, which might happen through experience obtained in the Moonlight project.

I have only scratched the surface of WPF, but so far I’ve seen solid gold only. Craving for new WPF projects!

Migrating Delphi Applications to .NET

I just came by a fairly new set of Delphi tools by CodeGear and RemObjecs, and being an ex Delphi programmer, my mind was flooded with intriguing ideas. How easy would it be to port old Delphi applications into this century, i.e. the .NET world, without the need of a complete rewrite? This would not be the first time it is attempted, but would it be easier now with these brand new tools?

If you have read so far, you probably already know what Delphi is. What you might not know is that CodeGear (now owned by Embarcadero Technologies) released a new .NET version of Delphi just a few months ago. Called Delphi Prism (just Prism here from now on), this MS Visual Studio plug-in is based on Oxygene CLR compiler licensed from RemObjects and fully compliant with the .NET Framework. Both Delphi and Prism compile their own dialect of the Pascal language, of course.

The first attempt towards .NET by Borland/CodeGear was Delphi.NET that first appeared as Delphi 8 in 2003. At first it aroused some enthusiasm, but after all it was no success and was never updated to .NET Framework 2.0. Oxygene/Prism, on the other hand, is not based on Delphi.NET and supports the whole .NET Framework up to version 3.5 and probably beyond.

Porting Delphi Code to .NET

Now, thanks to Prism, you might think that in order to get a .NET application all you would have to do is compile the Pascal sources with Prism, with minor syntax adjustments, perhaps. Well, for your disappointment I have to tell you that there is much more to it than just recompiling the source code. Let’s take a look at a minimal Windows application written in Delphi and Prism!

All this application does is stuff the current date and time into a label that was placed on the main form of the application. The Delphi version looks like this:

Delphi sample

And here’s the Prism version:

Prism sample

Because it’s also written in Pascal, this code bears some structural resemblance to Delphi, but the single line of functional code in our application looks quite different in these two cases: label1.Caption := FormatDateTime(‘c’, Now) vs. label1.Text := DateTime.Now.ToString().

For comparison, let’s have a look at the same application in C#:

C# code sample

The key thing here is the library, namely VCL in Delphi vs. .NET Framework in Prism (or C#). Yes, there is a Label control in both environments, but the most important property bearing the text content is named differently. And to get the current date and time, you would access the Now static property of the DateTime .NET class in Prism whereas in Delphi you would call the Now function that is not part of any class – to say nothing of the formatting of this DateTime value into a string. And this is just the beginning!

Delphi.NET tried to cloak the .NET Framework with VCL.NET, a VCL look-alike that acted as a wrapper around the .NET Framework and implemented the essentials of VCL as calls to .NET. It must have been quite a job to create VCL.NET, and porting it to .NET Framework 2.0 seems to have been even a harder one because it was never really attempted. Moreover, VCL.NET was a dead end because it did not provide a migration path to pure .NET Framework – if you started using VCL.NET, you would be stuck with the VCL object model for the rest of your career!

A more recent undertaking to create a VCL-topping on .NET Framework is ShineOn, an Open Source project initiated by CodeGear. The current version, sorry to say, is just a skeleton that has barely anything implemented. Knowing what happened to VCL.NET, one cannot expect very much from this project. It would be a daunting task to develop a comprehensive VCL replacement that perfectly maps VCL to .NET and does it with no performance penalty.

If these problems with libraries are not enough, look at the Delphi and Prism code samples above! Starting with the word Namespace, there are differences in structure and syntax that originate from the fact that Prism is a .NET language. To alleviate this problem, RemObjecs is developing a tool named Oxidizer that promises to “take care of a lot of the grunt work” that is needed when porting code with manual tools such as search and replace. When it works, Oxidizer can be a great help, but in the end reviewing and finishing the Prism code is something you will always have to do manually in the code editor.

Converting Visual Layouts

You may have noticed that the code samples above were not complete Windows programs – the visual form layouts were missing. We know that VCL forms store they layouts in .dfm files whereas the .NET form designer writes normal program code (Windows Forms) or XAML (WPF). Translating text-based .dfm code to C#, Pascal or XAML is basically something a translator program could do provided it knows the mapping between the UI controls and their properties in VCL and Windows Forms or WPF. Such a tool does not exist yet, but building one is the least of our problems. Even if the tool cannot find a 100 % mapping between the libraries, the amount of manual work is essentially smaller than porting general-purpose program code.

Best of Both Worlds: Running Side by Side

Another option to migrate to .NET would be keep your old native Delphi code as it is and link it with new managed code written in Prism. Calling unmanaged code from Prism or C# is no big deal, but the opposite is also possible. Although linking managed assemblies to Delphi is not as straightforward as linking native Delphi units, it can be done using one of a few routine methods that developers use every day when they move from C, C++ or Visual Basic 6 to C#.

The most common method is to use COM. Assemblies written with Prism or C# can be registered as COM objects that Delphi is able to call, and vice versa. The downside of COM is those woes that made .NET so welcome: the necessity to register all COM objects and the notorious DLL Hell. Were your application anything but trivial, very soon you would have to register and maintain several COM interfaces between Delphi and .NET.

Another method is to use mixed-mode DLL’s that have interfaces to both .NET and native WIN32 code. Unfortunately, they must be written in C++ so you would have to add a third programming language in the mixture.

But luckily there’s still another method, from RemObjects, again! They are selling a tool named Hydra that is based on the concept of plugins. Both plugins and plugin hosts can be written using Delphi or a .NET language (Prism, C# etc.), and thus Delphi applications can host .NET plugins, and .NET applications can host Delphi plugins. Plugins can be visual (kind of user controls) and non-visual (e.g. business components).

Hydra provides a set of wizards and helper components that open windows to the other world through interfaces. Calling the other side through an interface requires some typecasting or late binding, but it seems to work. The best thing is that Hydra does not use COM.

Which Way to Go?

As we have seen, porting Delphi code through Prism to the .NET world is not as easy as it would seem at first glance. If your code interacts with the user interface or relies heavily on VCL components such as datasets, there will be lots of manual work ahead. Only if your code mainly deals with your own classes and barely touches the run-time library, the porting solution would be feasible, but because we are porting a RAD solution, such a situation should not be very frequent. After all, the idea behind RAD has been to rely on smart components and controls, not to write everything from scratch.

What I would recommend is to start in a step-by-step fashion and implement new features and modules as .NET plugins. Depending on the structure of your application, a whole application layer, say the data access layer, could also be implemented as a .NET plugin. A VCL ClientDataSet fed by an ADO.NET plugin sounds quite realistic.

Over time, more and more modules would be migrated, and one day you could translate your form layouts from DFM to XAML, run a raw code translation to Prism with Oxidizer and hand-tune the rest. Personally, I would translate the code all the way to C#, but it’s your choice which .NET language you like to use.

If you are planning to stick with Delphi and completely ignore the evolving .NET world around you, don’t do that for long now! There are .NET technologies such as WCF that are likely to become a must on any line of business, and failing to support them makes your application hopelessly outdated. Delphi was a great tool that opened new perspectives for application development and influenced .NET and C# more than is generally known. The best way to pay homage to Delphi is to give Delphi applications an honorable old age and a chance to be reborn as .NET applications.

Scalable Windows Forms

Consider an application that should be able to adapt its font and form size to various needs: for users with weak eyesight, for viewing from different distances etc. You might think you need WPF to do that, but in fact also plain old Windows Forms has got mechanisms that automatically scale fonts and form layouts to different screen resolutions and font sizes. With a minimal amount of code you will be able to utilize this mechanism in your own application to make a fully scalable UI.

Scaling Support in Windows Forms

Today a Windows application might have to run in environments with several screen resolutions and system font sizes. As a programmer, what should you do to ensure your application would keep its layout and be consistent with the rest of the environment whatever the screen resolution might be? Well, you don’t have to do anything! Just leave your form’s AutoScaleMode property to Font for text-based forms (with labels, text boxes and buttons) or set it to Dpi for graphics-based forms, and Windows and the .NET Framework will scale your UI to fit the current environment. You can test your application by running it in different DPI settings. To change the DPI setting of your system, open Control Panel -> Display -> Settings -> Advanced -> General in XP or Control Panel -> Personalization -> Adjust font size (DPI) in Vista.

Scaling Your Own Application

Changing the DPI setting requires restarting the system so it isn’t very handy if your user just temporarily wants to see the application in a magnified or reduced view. This is why you might consider having individual UI scaling in your application. Thanks to the automatic scaling support in Windows Forms it will be quite easy and straightforward.

When you change the Font property of a Form (programmatically or in Designer) to a larger or smaller font, form dimensions and control layout will scale automatically provided that the AutoScaleMode property is set to Font. If you try this, you will notice that controls on this form might also have their font size changed. The problem is that the general font change only applies to those controls whose Font property has not been set explicitly. These controls assume the font of their parents (Form, GroupBox, Panel etc.), and automatic font change works only as far as this chain from form to controls is not broken.

To spread the relative font change to all controls you just need to add a few lines of code that goes through all controls on the form and changes the font of those who don’t share a font with their parent. This can be done by overriding the OnFontChanged method or implementing a FontChanged event handler. And that’s it!

The Sample Application

A tiny Visual Studio 2005 project with a launcher/control form and two scalable forms can be found in http://www.sysgen.fi/source/scalableforms. For your convenience it is available both as a ZIP archive and as separate files. The first scalable form isn’t fully scalable since the label “This form has got nothing special in it” does not scale because it does not share the font with the form. The second one scales nicely thanks to the OnFontChanged override.

When running the application, you may open any number of the two forms and see the effect of dragging the track bar slider. Please enjoy!

Sharing Status between Forms

A typical Windows Forms application might have several forms open at one time. Often these forms share an entity, e.g. they might all be documents related to one customer. Attaching the forms to a customer at creation time is trivial, but making all the forms reflect changes in customer state in real time isn’t. In this example I’ll show a simple mechanism how to bind any number of forms to a set of shared live data.

The Scenario

Let’s assume we have an application where we first select a customer an then create or open any number of invoices (or other documents) related to this customer. A dedicated customer form is used for updating customer details, but in addition to that, any document form might also be used to keep customer data (e.g. the mailing address) up to date. Once a form updates the customer details, all the other forms should reflect the change immediately. The customer might also have calculated characteristics that are not saved as customer data but calculated from documents.

To accomplish this task, we would typically create a network of methods, delegates and events that spreads the signal of data changes between forms. Luckily we don’t have to do that because we already have a mechanism that is easy to use and encapsulates all the methods, delegates and events needed for signaling data changes, namely data binding

The Solution

We create a component class named CustomerSource that inherits from BindingSource. Thanks to its parent class, this component can be dropped on a form, and data controls can be bound to it visually. CustomerSource is internally bound to a typed DataSet, or, to be exact, to a DataTable within that DataSet.

What makes this BindingSource special is that the DataSet is contained in a static member:

private static CustomerDataSet DS = new CustomerDataSet();

This means that a single copy of CustomerDataSet is created when the code for CustomerSource is first loaded. The copy is kept in memory as long as the application runs. Because this single copy is shared by all instances of the class, all the forms that contain a CustomerSource have access to this shared data.

CustomerSource has a double role both as a data model and a controller. It has methods for retrieving, saving and refreshing customer data. These methods are documented in source code.

The Sample Code

You can download the Visual Studio 2005 solution at http://www.sysgen.fi/source/interformcomm. For your convenience it is available both as a ZIP archive and as separate files.

The solution is structured as three Visual Studio projects mainly to demonstrate that static data is not bound to one assembly.

Customer data access uses Microsoft’s Northwind sample SQL Server database. Please open CustomerDataAccess.cs and make sure that sqlConnection1.ConnectionString points to your copy of Northwind if you have got one. If you haven’t got SQL Server or this database, you can run the solution by commenting out an in a few lines in CustomerDataAccess.cs – see source code for instructions! The data access implementation is intentionally simplified: you won’t find any data validation or error handling there.

Enjoy!

Real Programmers Write Code

Back in the 80′s there were a breed of satiric texts titled like Real Programmers Don’t Use Pascal circulating around Usenet and photocopiers (see Wikipedia or do a web search on this title). Since then, things like OOP, CORBA, COM, and AJAX have been among the major issues that Real Programmers do or don’t use. What remains, however, is that programmers are supposed to write code – right?

So if you are a programmer, you should write as much code as you can because that’s what you are paid for. The more code you write, the better a programmer you will be. The plenitude of your code lines ensures your place in the Programmers’ Hall of Fame!

Not quite so, or, rather, not at all so! In fact, what you are paid for is implementing functionality, not writing code, which is just the necessary evil to accomplish your primary mission. Believe me, even you could write bugs sometimes, and the more code there is, the more bugs there will be. And because nothing is invariable in this world, somebody has to maintain your code after you have finished with it. Whether it is yourself or somebody else, maintaining 10,000 lines of code cannot be easier than maintaining 1,000 lines of code however beautiful those 10,000 lines might ever be.

So how to become a better programmer and write less code? That’s what this blog is trying to figure out. In forthcoming posts I will share my recipes how to utilize the .NET Framework to implement more functionality with less code. And even if you are not a .NET programmer, you might find some posts in this A Craft and an Art category at least intriguing if not downright interesting.

Be my guest!