Category Archives: C#

Refactoring XAML ResourceDictionaries

Code reuse of any kind is a priority for all developers. Design elements and UI resources are no exception.
In this tutorial you will learn how to correctly organize your resources for maximum reuse.

Considering the following scenario:
You have two apps: App1 and App2 int which you want to use the same resource but with slightly different properties.
App1 needs a style for a TextBlock

<Style x:Name="myTextBlockStyle" TargetType="TextBlock" >
    <Setter Property="Foreground" Value="Green"/>
    <Setter Property="FontSize" Value="24"/>
</Style>

while App2 needs a very similar style

<Style x:Name="myTextBlockStyle" TargetType="TextBlock" >
    <Setter Property="Foreground" Value="Orange"/>
    <Setter Property="FontSize" Value="24"/>
</Style>

Notice that the only different thing about the two styles is the color used as Foreground, the rest is similar. For the sake of simplicity I kept the myTextBlockStyle quite small, with only two properties.

For maximizing our code reuse we can try to refactor the two styles into a separate style as follows:

<Style x:Name="commonTextBlockStyle" TargetType="TextBlock" >
    <Setter Property="Foreground" Value="Green/Orange"/>
    <Setter Property="FontSize" Value="24"/>
</Style>

Now, the magical part!

If you use a common ClassLibrary you can move the style into a dictionary which both apps reference.

The style definition becomes:

<Style x:Name="commonTextBlockStyle" TargetType="TextBlock" >
    <Setter Property="Foreground" Value="{StaticResource brush1}"/>
    <Setter Property="FontSize" Value="24"/>
</Style>

Notice how the Foreground value is not longer set to either Green or Orange, but it references another resource named brush1.

In order for the whole setup to work this resource has to be defined in the ClassLibrary as follows:

<SolidColorBrush x:Key="brush1" Color="Red" />

And overriden in App1:

<SolidColorBrush x:Key="brush1" Color="Green" />

and in App2:

<SolidColorBrush x:Key="brush1" Color="Orange" />

At runtime, each app will have to reference the dictionary file where commonTextBlockStyle using an absolute path

The dictionary file that defines commonTextBlockStyle will in turn have to reference another dictionary path that contains the definition of brush1 using a relative path.

The following diagrams illustrate the setup in greater detail:

Project structure

ClassLibrary1 structure

StandardStyles in the ClassLibrary referenes a Common style referenced in the same project

App1 at runtime

App1 references StandardStyles and overrides Common with the desired color Green

App2 at runtime

App2 references StandardStyles and overrides Common with the desired color Orange.

This project structure and reference mechanism should greatly reduce your dictionary size while giving you all the flexibility you need for using your styles in whatever way you need.

Coming soon to Windows Store: Quiz for Geeks

  • Who played ‘Rachel Green’ in the TV Show Friends?
  • 19+16=…
  • What is the decimal value of the roman numeral LXIII?
  • What is the local currency in Laos called?
  • What is the name of the element “Cl”?

Can you answer any of these questions in 10 seconds or less? If the answers is YES then Quiz for Geeks is the game for you!

Quiz for Geeks is a fast paced game that tests your knowledge on a variety of topics from geography and history to mathematics and literature as well as entertainment and current events.

Thousands of dynamic questions structured in 5 levels of difficulty will challenge you as you progress in the game.

Quiz for Geeks

The game is days away from being launched, stick around and like our Facebook page, we’ll let you know when it reaches Windows Store.

How much code can you really place in your Portable Library?

Recently, Jevgeni asked me how much code I was able to share between my projects by using a Portable Library. He is contemplating building a Windows Phone and a Windows Store app and wants to create a Portable Library for sharing common code.

So I decided to get some numbers based on my new app code which is going to (hopefully) reach Windows Store soon.

Code Sharing between a Portable Library and a Windows Store app

Code sharing between a Portable Library and a Windows Store app

The app is not 100% ready yet, so I might add few lines of code but at the moment it turns out I placed more than 70% of my code in a Portable Library.

However, I invested quite a lot into having such a structure as I plan to release a Windows Phone app around the same core.

While you are waiting for my new app to be released :), go ahead and try my other apps already in the Windows Store: Puzzle Frenzy (download link) and Puzzle Frenzy Kids (download link).

Ensuring Data Integrity Using Digital Signatures in WinRT

The data stored in Windows Storage  for Win8 Apps (equivalent of IsolatedStorage for WP8) can be accessed by users directly, even by using Windows Explorer.

The files are stored under C:\Users\<User>\AppData\Local\Packages\<AppName>\LocalState and even if <AppName> is actually a combination of publisher name, app name and another sequence of letters, it is pretty easy to tell which app is which.

If you are going to store data and you want to keep your users from modifying it, you have to make sure you have the right mechanisms in place for doing so.

Luckily, WinRT has some useful libraries for helping you accomplish file signing in Windows.Security.Cryptography namespace.

The classes in this namespace can help you ensure the integrity of a file by creating a digital signature whenever you save it, and by verifying the signature whenever you read the file.

Wikipedia is a good starting point for finding out more about Digital Signatures and RSA.

Here is how you initialize the all the variables needed for signing and signature verification:

var hashAlgorithmName = HashAlgorithmNames.Sha1;
var asymmetricKeyAlgorithmName = AsymmetricAlgorithmNames.RsaPkcs1;

hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(hashAlgorithmName);
asymmetricKeyAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(asymmetricKeyAlgorithmName);

var privateKeyBuffer = Convert.FromBase64String(privateKeyString).AsBuffer();
privateKey = asymmetricKeyAlgorithm.ImportKeyPair(privateKeyBuffer, CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey);

Here is how you create a signature:

public IBuffer Sign(IBuffer byteArrayBuffer)
{
var hashBuffer = hashAlgorithm.HashData(byteArrayBuffer);
var encryptedBuffer = CryptographicEngine.Encrypt(privateKey, hashBuffer, null);

var hashString = CryptographicBuffer.EncodeToBase64String(hashBuffer);
Debug.WriteLine("This is the hash:" + hashString);

var encryptedHashString = CryptographicBuffer.EncodeToBase64String(encryptedBuffer);
Debug.WriteLine("This is the encrypted hash:" + encryptedHashString);

return encryptedBuffer;
}

Here is how you verify a signature:

public bool VerifySign(IBuffer originalBuffer, IBuffer encodedHashBuffer)
{
var originalHashBuffer = hashAlgorithm.HashData(originalBuffer);
var decriptedHashBuffer = CryptographicEngine.Decrypt(privateKey, encodedHashBuffer, null);

byte[] originalHashArray;
byte[] decriptedHashArray;

CryptographicBuffer.CopyToByteArray(originalHashBuffer, out originalHashArray);
var originalHashString = Convert.ToBase64String(originalHashArray);
Debug.WriteLine("Original hash:" + originalHashString);

CryptographicBuffer.CopyToByteArray(decriptedHashBuffer, out decriptedHashArray);
var decryptedHashString = Convert.ToBase64String(decriptedHashArray);
Debug.WriteLine("Decrypted hash:" + decryptedHashString);

return originalHashString == decryptedHashString;
}

Notes:

  • In order to make it work, you need a private key which you can generate using:
var key = asym.CreateKeyPair(512);
  • For the sake of simplicity, I keep the private file as a resource inside the app, which is not necessarily a good idea. The only reason I do it in this way is because I want to prevent anyone from easily changing the content of the saved files. However, this approach can easily be improved by storing the private key into a secure location and retrieving it over a secure channel.

Remember! Signing a file won’t keep your users from seeing its content, it will only prevent them from modifying it, or let you know if they they did.

Good luck!

Puzzle Frenzy Update 1 is now live in Windows Store!

I’m pleased to announce that Puzzle Frenzy Update 1 has passed certification and is now live and ready for download in Windows Store.

The new update brings a lot of visual and performance improvements like:

  • Game ended popup that displays the rating for the current game
  • Pause game button and Game paused popup windows that shows a preview of the puzzle being solved
  • Pieces animation during sorting and shuffling as well as when the user finishes the game
  • Memory consumption improvements
  • Home page images loading time improvements
  • Piece animation when moving to the next puzzle
  • Image size decreased for screen resolutions matching the image format to leave room for unsolved pieces
  • The ability to go to App’s blog, Facebook page and Rate and review page from withing the app by bringing up the bottom app bar on the home page
  • Several minor bugfixes

As a consequence the app feels and is faster, more responsive, consumes less memory and delights the users with more animations.

Check it out in the Windows Store!

http://apps.microsoft.com/windows/en-GB/app/puzzle-frenzy/28238e98-ac0f-4a6b-81ea-a31a24a15acf

Puzzle Frenzy home page

Puzzle Frenzy home page

Building Jigsaw Puzzle Frenzy: sharing code between WP and WinRT

When I first started working on Puzzle Frenzy I wanted to maintain both the original WP app and also to create a new WinRT app by reusing and sharing as much code as possible.

My plan was based on the presentations at Build which promised  which promised up to 70% code share between  WP and WinRT. In particular check out Create Cross-platform Apps using Portable Class Libraries.

During different stages of the project I tried several approaches for achieving this goal:

Share physical source files between WP and WinRT projects

I initially started building the WinRT app adding new projects to the solution containing the same files as the WP.

The problem

While a low of classes in the WP and WinRT are “identical” in functionality, they are often not in the same  namespace.  On top of that, using the same source files in more then one project is by itself problematic.

Direct consequences:

1.Trying to use the same source files for both WP and WinRT resulted in files like this one:

#if WINDOWS_PHONE
using System.Windows.Media;
#else
using Windows.UI.Xaml.Media;
#endif

Furthermore, for some special cases I was forced to have constructions like this one:

#if WINDOWS_PHONE
//Do something
#else
//Do something else
#endif

2.Having the physical same file referenced by two projects in Visual Studio is a lot of work. Whenever something breaks for one project (90% of the time due to a usings declaration change) the file containing the error has to be opened from the context of the failing project. If the file is opened in the other project the error won’t be highlighted in the code and the solution won’t compile.

For few files, this setup can be maintained even if it is inconvenient. However, as the file count grows, keeping up with the changes is a too complicated task.

Using Portable Libraries

For the appropriate scenarios Portable Libraries are awesome. It eliminates the need for duplicated files altogether as the library can be referenced by both the WP and WinRT. In my case however I wasn’t able to use them because I use Point and Size classes throughout my project. These classes are not available in Portable Libraries. I could have created my own implementation of Point and Size to overcome this limitation, but given the scale of the changes I preferred not to do it: a simple search reveals that I use these classes in more than 100 places in my code.

From what I’ve experienced so far, Portable Libraries offer limited classes to work with. My ViewModels layer which I was planning to keep there needs far to many things which are not available.

Conclusion

Sharing code between WP8 and WinRT can prove to be troublesome.

Both duplicate projects and Portable Libraries have limitations, making it in my case are quite challenging to use.

If sharing the code between the two apps is really your goal, I am fairly confident it can be achieved. However, in my case, for this particular app, attempting to share the code only slowed me down. In the end I kept using duplicated projects but I am not maintaining them at the same time.

I take turns in development cycles implementing features and adjusting the code to work on the other platform. While doing so I introduce bugs in the project not being maintained at the time, but the amount of work needed to fix it is far less than implementing new features at once on both platforms.

Closing argument

If you start developing a new app and want to target WP and WinRT consider using Portable Libraries from the start. It will have some limitations but will also force you to place the code in the right place in order to be shared.

If you already have an WP app and want to migrate it to WinRT you might want to start by maintaining duplicated projects in order to limit the size of the changes needed. Once you reach a stable state you can of course look into  moving towards Portable Libraries if code sharing is your goal.

Have a look and see how it turned out.

Jigsaw Puzzle Frenzy is available in Windows Store, check it out and tell me what you think: http://apps.microsoft.com/windows/en-GB/app/puzzle-frenzy/28238e98-ac0f-4a6b-81ea-a31a24a15acf.

You can also give your feedback on app’s review page or on app’s Facebook page http://www.facebook.com/PuzzleFrenzyApp.

Happy codding!

Puzzle Frenzy home page

Building Puzzle Frenzy: using small source code files

As I told you before, Puzzle Frenzy was build starting from an old app I wrote for WP7. A lot of things changed since then, and most importantly I got to read Uncle Bob’s Clean Code as well as watch some of his Clean Code episodes.

Based on what I learned by reading the book I started refactoring the code. One of the thing that bothered me the most in the old code was the big source files, where I kept big classes and long methods.

Over time I managed to decrease the classes size quite a lot which helps me when it comes to testing, fixing bugs or adding new features.

Here is a comparison of the file size numbers:

Before After
Total line count 4114 6514
Source files count 45 118
Average file line count 91 55

meaning that

  • I increased the total amount of code with 58%
  • I increased the number of files with 162%
  • I reduced the average file size by 39%.

Here is how the file line count looks like:

Before: WP app source files line count

Before: WP app source files line count

After: Puzzle Frenzy source files line count

After: Puzzle Frenzy source files line count

As you can observe I still have some old large classes, but with constant refactoring I’m pretty confident that I will manage to decrease their size over time.

I’m more then excited with these changes: now the code reads better, I can understand easier what it does, and I have more confidence in it.

I strongly recommend the above-mentioned Clean Code book, it contains some priceless advice.

Happy coding!