Windows 8 Developer Event – LA

On Monday, May 23rd, I had the chance to talk about Interknowlogy and some of our latest Developments at Microsofts Windows 8 Developer Event in Los Angeles.
In particular, I spoke about our “Personal Rehab Trainer” which enables patients to practice their rehab exercises at home instead of having to go to rehab sessions. If you want to find out how this Rehab Trainer cuts costs, how it provides patients with better service and what all this has to do with WinRT and Windows 8, make sure to check out the recorded event at Windows 8 Developer Event. My presentation can be found between 1h:44m and 1h:51m.

I met a ton of great and really inspiring Microsoft Developer Evangelists who spoke about the following topics:

  • Windows 8 from the Consumer’s Perspective
    (by Jerry Nixon)
  • Windows 8 Store and Developer Opportunity
    (by Michael Johnson)
  • Windows 8 Hello World
    (by Alice Pang (Make sure to register for her Windows 8 Developer Camp))
  • Visual Studio 11
    (by Jeremy Foster)
  • Windows 8 Core Capabilities & Interactions
    (by Matt Harrington)
  • Metro Design Language
    (by Jeremy Foster)
  • Building Metro Apps with JavaScript
    (by Michael Palermo)
  • Building Metro Apps with XAML
    (by Jerry Nixon)
Thanks to the pictures Justine Li took from the event I can provide you with a few impressions of the event!

MS Evangelists

The Audience

The Audience the day before

Me speaking

Me giving autographs ;-)

The demo on the demo table

Our VIP booth

Thank you, Microsoft, for this great event!

WP Simplified: CoreApplicationService (Lifecycle)

In my post Simplyfying the Windows Phone Development Experience! Codename: LionHeart I explain that LionHeart is a demo app that I’m using to prove out a few lessons we’ve learned here at IK from our last Windows Phone project. In this post I will start to get into the meat of the app starting in a class named CoreApplicationService (CAS).

What is CoreApplicationService’s Purpose?

Event Forwarding

One of the purposes of the CoreApplicationService (CAS) is to expose events from across the app to ViewModels (VMs) or any other class that is not instantiated by App.xaml. This class acts, in a very simplified way, as an event aggregator. It is not, however, an event aggregator as found in Prism. Instead it’s more of a one to one event forwarding class. For example, in App.xaml there are two events named Deactivated and Closing. Therefore, in the CAS there are two identical events named Deactivated and Closing. When the event is handled in App.xaml.cs we simply forward the handling onto the CAS as show in this example:

public partial class App : Application
{
   private void ApplicationDeactivated(object sender, DeactivatedEventArgs e)
   {
       CoreApplicationService.Instance.OnDeactivated(e);
   }
}

Currently the events handled in the CAS are:

From App.xaml

  • Deactivated
  • Closing
  • Obscured
  • Unobscured
  • NavigationFailed
  • UnhandledException

From PhoneApplicationFrame

  • Navigating
  • Navigated

In all cases, the CAS acts as a forwarding system for any object the desires to subscribe to these events. In LionHeart those objects are usually VMs. This pattern allows the VM to be responsible for knowing when and what to do during these events. This pattern has made more and more sense as we’ve discussed possible solutions to our problem of telling VMs when to Deactivate (prepare for tombstoning) etc.

Error Reporting

Another responsibility of CAS is to prompt the consumer of the app to send error data to the developer. We found Little Watson created by Andy Pennell at Microsoft which simply collects unhandled exception information and stores it in a file in IsolatedStorage before the app closes. The next time the consumer launches the app they are prompted to send the error file to the developer, which they can choose to not send it if they desire. The error file is then deleted and the application will not prompt again until an error file exists again. This is so helpful I cannot even begin to express how many bugs we have been able to track down because of this tool. I want to start buffing this helper class out with logging since the error information we receive on the phone is not as helpful as it could be. Adding a logging feature that began each time the application was launched would be of even greater benefit.

Navigation

This purpose is what originally drove us to create the CAS. In fact we had originally named the CAS as NavigationService, but as it’s functionality increased and purpose morphed we decided that name was to specific and did not convey what we wanted. Navigation will be covered in greater detail in another post. In simple terms we use a dictionary of object to string mappings. Each string represents the Uri to a page. These mappings are set immediately after initializing the CAS as shown in the section below “How to use CoreApplicationService.”

public partial class App : Application
{
   private void InitializeNavigationMappings()
   {
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.HOME_VIEW_KEY, "/Views/HomeView.xaml");
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.MY_VIEW_KEY, "/Views/MyView.xaml");
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.ALL_CLIENTS_VIEW_KEY, "/Views/AllClientsView.xaml");
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.CLIENT_VIEW_KEY, "/Views/ClientView.xaml");
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.MY_REPORTS_VIEW_KEY, "/Views/MyReportsView.xaml");
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.REPORT_VIEW_KEY, "/Views/ReportView.xaml");
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.ALL_SESSIONS_VIEW_KEY, "/Views/AllSessionsView.xaml");
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.MY_SESSIONS_VIEW_KEY, "/Views/MySessionsView.xaml");
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.SESSION_VIEW_KEY, "/Views/SessionView.xaml");
       CoreApplicationService.Instance.Mappings.Add(ViewKeys.SETTINGS_VIEW_KEY, "/Views/SettingsView.xaml");
   }
}

In the example code above you will notice the use of ViewKeys which is a struct that contains string values that we use as keys. The key does not need to be a string instead it can be any object. Sometimes we will use typeof(object) for views that represent specific types. We found that strings were required for some views and decided to go with all strings for consistency. Remembering that VMs will be requesting navigation most of the time we did not use typeof(Page) as the key, because VMs should not have access to those types.

How to use CoreApplicationService

The CAS is provided via a static property of itself named Instance as a singleton. There are two times the CAS will need to be instantiated. The first is when the application is Launching. The second case is when the application is being Activated, but only if there is no application state. In both cases no VMs exist yet, therefore the CAS will not forward the Launching and Activating events because no object would or could receive them. Instead we use the events to initialize the CAS.

public class CoreApplicationService
{
   private static CoreApplicationService _instance;
   public static CoreApplicationService Instance
   {
       get { return _instance ?? (_instance = new CoreApplicationService()); }
   }
}

public partial class App : Application
{
   private void Initialize(bool isLaunching)
   {
       CoreApplicationService.Instance.Initialize(RootFrame, isLaunching);
       InitializeNavigationMappings(); //As shown in above section “What is CoreApplicationService’s Purpose?” and subsection “Navigation”.
   }

   private void ApplicationLaunching(object sender, LaunchingEventArgs e)
   {
       Initialize(true);
   }

   private void ApplicationActivated(object sender, ActivatedEventArgs e)
   {
       if (!e.IsApplicationInstancePreserved)
       {
           Initialize(false);
       }
   }
}

Initialize accepts two parameters: the PhoneApplicationFrame which is used for navigation, and a boolean indicating if the application is launching.

public class CoreApplicationService
{
   public void Initialize(PhoneApplicationFrame frame, bool isLaunching)
   {
       LittleWatson.CheckForPreviousException();

       _frame = frame;
       _frame.Navigated += FrameNavigatedHandler;
       _frame.Navigating += FrameNavigatingHandler;

       PersistTombstoningValue(IS_LAUNCHING_KEY, isLaunching);
   }
}

The reason for the boolean is for VM initialization. This will be explained in much greater detail later on, but for those curious minds out there during Activating (without state) when VMs initialize there are no navigation parameters. This is used as an indication that the application was tombstoned. Because this same state exists during Launching we must differentiate the two somehow. We got around this by adding a boolean to the tombstoning values that is checked for when no navigation parameters exist and indicates the application is Launching not Activating. As I stated before I will cover this in later posts in greater detail.

Conclusion

This concludes the introduction into the CoreApplicationService and how it plays into the lifecycle of the phone app. This service is the backbone to LionHeart and all phone apps that use it. As we cover navigation and how VMs integrate with this service you’ll understand why it is so important and why it is so helpful. As always if you have any suggestions for improvement, comments, or questions please post them. This is not meant to be a one man show, but rather a starting point for phone app architecture.

More than you ever wanted to know about AES Crypto in .NET

First, before I begin anything, I want to point out that cryptography is hard. REALLY hard. There are so many possible points of failure, and those points of failure and methods of attack can change depending on what the purpose of encrypting the data is. If you do it wrong, you get lawsuits, and/or you end up on the front pages of major news organizations for data security breaches. Or a rival nation gets your top-secret plans to rule the world. You get the idea. I’ll touch on some of the technical points of failure briefly; I’m mainly going to be exploring this topic through a fairly simple scenario: A password vault file, encrypted with a password, and stored locally on my computer (potentially synced to other computers through some syncing service).

As with any good crypto, the first line of defense is always preventing an attacker from gaining access to the encrypted data in the first place. If data is going over a network, encryption should be part of that as well, and that brings in a whole new host of issues that are outside of the scope of this article. Since I’m planning on storing the data locally on my hard drive, the first line of defense is me and my computer: Lock my computer when I walk away. Make sure there’s no spyware or malware on my computer, no keyloggers or other devices that could steal my password, etc… Going back to my original point about crypto being hard, it’s hard not only because writing the code is hard, it’s difficult because of all the ancillary ways someone could potentially get access to my data that I have to account for.

If I leave my computer unlocked, someone could steal data off of it. Install a keylogger. If I leave this password app open someone could just go in and look at my passwords after I’ve decrypted them. If they have physical access someone could install a HARDWARE keylogger between my keyboard and computer. Pull out my hard drive and clone it. Hack into the company Wi-Fi network and remote access my computer. Or even STEAL my computer. Or TSA could confiscate it. And/or force / legally compel me to reveal my password. You get the idea. There is no such thing as absolute security or secrecy.

However, let’s assume for a moment that an attacker DOES somehow manage to get access to my vault file. (Maybe by getting access to my computer when the vault program is closed and the data encrypted, or a folder syncing program has a hiccup and spams a public link to it on the Internet) My password file is in the hands of someone actively trying to get at my data, and the only thing protecting the data is my password and good cryptography. So. How do I use good cryptographic practices to secure my data?

Since we want to use the latest and greatest, we pick AES (Advanced Encryption Standard, successor to Date Encryption Standard and Triple Data Encryption Standard or Triple DES), Rijndael 256 to be specific (It’s good enough for government work…). In the System.Security.Cryptography namespace, Microsoft has kindly supplied us with the RijndaelManaged class and a pre-provided implementation of the AES standard. I ALWAYS recommend using a pre provided class instead of attempting to roll your own. The ones from Microsoft have gone through EXTENSIVE testing, code, and security review to verify the correctness of the algorithms and code. Frankly, if you write your own, yours will probably have bugs. Bad ones. Bugs that might get you put on the front page of major news organizations for data security breaches if you do it wrong. Warning given, point made, moving on.

Now, there are a couple of things you’ll need in order to do symmetric encryption when we crack open the RijndaelManaged class and try to create an encryption transform:

  • A Key
  • An Initialization Vector or IV
  • Your Data

The Key

First, the key, which is represented as a byte array of some fixed size. The size of your key is important, the number of bits has to match what the algorithm supports, in the case of Rijndael, it supports key sizes of 128, 192, and 256. In our case, we’ll be using a key size of 256. The number of bytes we need is 256 divided by 8 (remember, the key size for the algorithm is specified in bits, but our code mainly works with bytes). So if I’m declaring a byte array for the key for AES 256, it would be new byte[32].

Derive your Key

Now wait, how the heck to I remember a 32 number combination? I can’t. You probably can’t, and unless you’re a brainiac with an eidetic memory I wouldn’t suggest trying with any reasonable hope of success. So, since I have now come to this sad conclusion about my memory, I need some way to take a password or key that I can memorize and turn it into a 32 byte key. Fortunately, there’s a way to do just that by way of a password based key derivation function called PBKDF2. It’s also a standard (RFC 2898, which is only important because the code uses the name of the spec for the class name and not PBKDF2 like I would expect… go figure). Essentially, PBKDF2 is a piece of code that hashes an arbitrary length of text into a pseudo random key. Now, we could use something like MD5 to do something similar, but PBKDF2is designed with cryptography in mind, and to be slow on purpose. Why does it need to be slow? Simply this, cryptography is a big huge lever that makes it easy to go one way, and hard to go another. MD5 is FAST to compute, and someone trying to break into your encrypted data wants to be able to test as many passwords as possible as fast as possible. PBKDF2is slow and more difficult to compute, and the harder it is, the longer it takes to generate a hash, which dramatically reduces the number of passwords a hacker trying to attack your vault can try per second. (There’s a really good article by Jeff Atwood here: http://www.codinghorror.com/blog/2012/04/speed-hashing.html on hashing algorithms in security, rainbow tables, speed hashing, why it’s important to have a slow hash for security, and so on. If you’re interested on reading more about it)

How do we create this hashed key with PBKDF2? The constructor takes 3 things, a string password, an iteration count, and a byte array for something called a salt (Not in that order). The Password is easy, it’s a string or byte array and it’s whatever you choose to use as your “uB3rAw3$omeP@assw0rd!“. iteration count is pretty self-explanatory too, it defaults to 1000, and the bigger the number, the more calculation rounds it does and the longer it takes to calculate the hash. But what about this salt thing? What is it, and why is it important? Do I even care? So here we go.

Salt your Vault

If you’ve heard about salt or salting passwords before, it was probably in reference to a website or service, usually some piece of code that you controlled that sat between your users (or a supposed attacker) and the hashed passwords in your database so that an attacker couldn’t just *make up* a password like zn3lzl that would hash to the same value as the users password like mycoolpassword2 and allow them to log in. If we assume that the attacker has access to your password vault, we can probably assume he has access to your program as well, and it won’t be very hard to figure out some static salt value you’ve stored in your code. So it’s useless right? In some ways yes, in some ways no. IF it’s JUST you, or the attacker is targeting JUST YOUR vault, then yes, it doesn’t matter. However, if for some reason your password vault app becomes popular, and an attacker gains access to, lets say 5000 different peoples vault files, it’s much much easier to check the same passwords across ALL the vaults at once if the salt values are the same. That is again assuming he is not targeting just one particular vault. If they’re all different, the time required to check a password across all the vaults goes up by a factor of 5000, making it less viable to quickly crack multiple vaults. My thought is to simply store the salt along with the vault, since if an attacker has access to your vault, he probably has access to wherever I’d store the salt anyways, and it at least requires him to compute a separate hash for each vault. So, I’ll generate and store a separate, cryptographically random generated salt with my vault file.

Something like this:

var salt = new byte[256];

using (var rnd = RandomNumberGenerator.Create())
{
     rnd.GetBytes(salt);
}

As an aside, realize that no amount of encryption can save your data from a bad password. Good hackers are GOING to use huge word lists and fantastic substitution / transposition / combination rules before they even attempt to use a brute force attack. ‘MyL1ttl3P0ny‘ is not a good password. ‘abc123‘ is arguably much worse; but then you’re probably not reading this if abc123 is something you’d use for a password.

Now that we have our password, the salt (loaded from our vault file) and the number of iterations, we can derive a key with the correct size:

var deriveBytes = new Rfc2898DeriveBytes(myPassword, mySalt, 10000);
var aes256Key = deriveBytes.GetBytes(32);

Tada! magic. We now have a byte key from the password that we supplied earlier. Ok, now that we have our key, we can see that when you try to create our encryption or decryption transform that it is requiring something called an initialization vector (IV). I know when I was going through all this that I was thinking “what the heck is an initialization vector?” Since I had to teach myself what it was and why it was important, I’m going to assume somebody also doesn’t know and brain dump what I’ve learned on you all as well.

Block Ciphers, Chaining, and Initialization Vectors

First, we have to understand a few things, how a block ciphers works, how cipher block chaining works, how the IV plays in, and why it’s all important. To begin with, block ciphers. Most computer ciphers these days are done using cipher blocks of a given bit size, usually in round multiples of 2, for example 128 bit or 16 bytes chunks (this is actually the size AES uses). Our clear text gets chunked up into these small, manageable blocks of data. Then encryption transform is then run multiple times on each block, and the resulting blocks are all concatenated together to form the final encrypted output.

Because encrypted blocks are computed independently, changes somewhere in the original unencrypted data might only change the encrypted data for a few blocks of the resulting encrypted output. Furthermore, if you happened to have the same 16 byte chunk repeated again such that it aligned with a different blocks, you will get the exact same block of encrypted output. On one hand, this could be useful if you want to send delta updates to an encrypted file, it also means that attacks against individual blocks are feasibly be easier or useful information could be obtained by comparing one version of the vault to another or even patterns might still exist even within the encrypted date. A really awesome example of why it’s important to apply some additional steps during the encryption process with block ciphers are these three images below: (Courtesy of Wikipedia):

Original | No Block Chaining | Proper Cipher Block Chaining

This is where CBC or cipher block chaining comes in. CBC fixes this problem by taking the previously encrypted block and performing a bitwise XOR between it and the raw bytes of the plain text of the next block to be encrypted. Effectively, this means that a one byte change in the first block will change EVERY OTHER block in the resulting ciphertext. However, there’s one last piece. If the first couple of blocks are NOT changed in any way, you can still leek some information about changes that were made by way of the first changed block. So if I have blocks A B C D E and block C gets changed, CBC will cause the resulting ciphertext for blocks D and E to change. It will NOT affect blocks A and B. So, at last, we finally get to the purpose of the initialization vector. The IV is essentially a completely random block to start off the cipher chain. Makes sense now doesn’t it? If I have a completely random block that I create and pass along, it guarantees that even if the plain text doesn’t change at all, the ciphertext will be completely different each time, assuming I generate a new IV each time I change the cipher text. In practice, encrypted data should be statistically indistinguishable from random noise.

Illustration of the process of a block cipher with CBC for Encryption:

Illustration of the process of a block cipher with CBC for Decryption:

Now that we know why we need an initialization vector, we also know, or can guess, what size it should be without having to look at the documentation (16 bytes, because that’s the block size for AES, and our IV is essentially a known random starting block). Since we should generate a new block and also store it with our vault, I’m going to declare our IV and initialize it the same way we initialized our salt:

var iv = new byte[16];

using (var rnd = RandomNumberGenerator.Create())
{
   rnd.GetBytes(mySalt);
   rnd.GetBytes(iv);
}

The CryptoStream

Now that we have all the pieces we can put it all together and encrypt our data to a MemoryStream (the memory stream could be anything, including a FileStream, but this is easier for demo and console output):

using(var ms = new MemoryStream())
{
   using (var cryptoStream = new CryptoStream(ms, transform.CreateEncryptor(aes256Key, iv), CryptoStreamMode.Write))
   {
      cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Count());
      cryptoStream.FlushFinalBlock();
   }

   cipherTextBytes = ms.ToArray();
}

And now the code snippet for decrypting the cypherTextBytes:

using (var ms = new MemoryStream(cipherTextBytes))
{
   using (var cryptoStream = new CryptoStream(ms, transform.CreateDecryptor(aes256Key, iv), CryptoStreamMode.Read))
   {
      var decryptedBytes = new byte[cipherTextBytes.Length];
      var length = cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);

      var decryptedText = Encoding.UTF8.GetString(decryptedBytes.Take(length).ToArray());
   }
}

Padding under the covers

Some final notes block cipher padding: You’ll notice that when I’m reading the stream I have the following line of code: decryptedBytes.Take(length).ToArray() When you’re using a block cipher like AES, just like the key has to be exactly a certain size, each block of initial data ALSO has to be a certain size. This means you ARE going to get some extra data tacked on the end of your stream that you weren’t anticipating. There’s a couple of ways this can be handled, RijndaelManaged has a couple of padding modes that it can use ranging from filling all the additional slots of data with zeros, or filling them with completely random data, but by default it uses PaddingMode.PKCS7 which fills each extra bytes needed to make the length of the data an even multiple of 16 bytes with the number that represents the number of padded bytes added to fill the empty space. If you have the exact amount of data to exactly to fill the number of blocks, the padding algorithm will add an extra block to ensure that the last byte in the last block that is read represents the amount of padding. Otherwise, depending on whatever data you’re storing, you could accidentally lose some of your data if it was misinterpreted as padding. The crypto stream is aware of the padding and will return the correct length of the original data on the last read call. I simplified the stream reading process for simplicity of demonstrating the use of the crypto stream and how it handles padding, it just reads everything and trims the result with decryptedBytes.Take(length).ToArray(). In real life, you should use or make a ‘real’ stream reader that reads data out of the stream in chunks and aggregates them together, or just serialize / deserialize your objects directly to and from the crypto stream.

Finally:

The Full Demo

using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

public class CryptoDemo
{
    public static void Main(string[] args)
    {
        TestEncryptionAndDecryption();

        Console.ReadLine();
    }

    public static void TestEncryptionAndDecryption()
    {
        const string myPassword = "uB3rAw3$omeP@assw0rd!";
        const string myData = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                              "Morbi rutrum pulvinar purus, nec ornare neque cursus id. " +
                              "Nunc non tortor est. Morbi laoreet commodo tellus, et suscipit neque elementum eu. " +
                              "Sed velit lorem, ultricies id varius vitae, eleifend eget massa. " +
                              "Curabitur dignissim eleifend quam, sit amet interdum velit rutrum vel. " +
                              "Nulla nec enim tortor.";
        var plainTextBytes = Encoding.UTF8.GetBytes(myData);

        Console.WriteLine("Password ({0} bytes): ", Encoding.UTF8.GetBytes(myPassword).Length);
        Console.WriteLine(myPassword);
        Console.WriteLine();

        Console.WriteLine("Plain Text ({0} bytes): ", plainTextBytes.Length);
        Console.WriteLine(myData);
        Console.WriteLine();

        var mySalt = new byte[256];
        var iv = new byte[16];

        using (var rnd = RandomNumberGenerator.Create())
        {
            rnd.GetBytes(mySalt);
            rnd.GetBytes(iv);
        }

        var transform = new RijndaelManaged();

        Console.WriteLine("Salt ({0} bytes): ", mySalt.Length);
        Console.WriteLine(Convert.ToBase64String(mySalt));
        Console.WriteLine();
        Console.WriteLine("Initilization Vector ({0} bytes): ", iv.Length);
        Console.WriteLine(Convert.ToBase64String(iv));
        Console.WriteLine();

        // Derive the passkey from a hash of the password plus salt with the number of hashing rounds.
        var deriveBytes = new Rfc2898DeriveBytes(myPassword, mySalt, 10000);

        // This gives us a derived byte key from our password.
        var aes256Key = deriveBytes.GetBytes(32);

        Console.WriteLine("Derived Key ({0} bytes): ", aes256Key.Length);
        Console.WriteLine(Convert.ToBase64String(aes256Key));
        Console.WriteLine();

        byte[] cipherTextBytes;

        using (var ms = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(ms, transform.CreateEncryptor(aes256Key, iv), CryptoStreamMode.Write))
            {
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Count());
                cryptoStream.FlushFinalBlock();
            }

            cipherTextBytes = ms.ToArray();

            Console.WriteLine("Encrypted Text ({0} bytes): ", cipherTextBytes.Length);
            Console.WriteLine(Convert.ToBase64String(cipherTextBytes));
            Console.WriteLine();
        }

        // this resets the algorithm. Normally, if we have a seperate encrypt / decrypt method
        // we would create a new instance of
        transform.Clear();

        using (var ms = new MemoryStream(cipherTextBytes))
        {
            using (var cryptoStream = new CryptoStream(ms, transform.CreateDecryptor(aes256Key, iv), CryptoStreamMode.Read))
            {
                var decryptedBytes = new byte[cipherTextBytes.Length];
                var length = cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);

                var decryptedText = Encoding.UTF8.GetString(decryptedBytes.Take(length).ToArray());

                Console.WriteLine("Decrypted Text ({0} bytes): ", decryptedText.Length);
                Console.Write(decryptedText);
                Console.WriteLine();
            }
        }
    }
}

Sample Output

Password (21 bytes):
uB3rAw3$omeP@assw0rd!

Plain Text (355 bytes):
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi rutrum pulvinar p
urus, nec ornare neque cursus id. Nunc non tortor est. Morbi laoreet commodo tel
lus, et suscipit neque elementum eu. Sed velit lorem, ultricies id varius vitae,
 eleifend eget massa. Curabitur dignissim eleifend quam, sit amet interdum velit
 rutrum vel. Nulla nec enim tortor.

Salt (256 bytes):
EA0wFLH3/VvAjh72dGmzd9taoFkPFymo5jKjONW5sozvPaHSuNFJdRE46pG7oc8JrvFIxfsyoNl+FSD9
iSM+jkVLLCpUB5Dr+JczPh9ZQIeLcFdk9mSP1hlekQhZOJu+Hs4+AGvkQNtxWTjlHZsQBU/uiSoDBAaB
4UyVKpv2ziHUePvWA+A9+pQLQ9YPYNQYYo+thfPOVAZMPejkPkIaBjEZBIeKVfLTN2339FJwWfVCz28H
edurTTVmuhysreMnSGWSuhijYkdNloOY4dam7pAg2sJhPAJonZ8UiBQ0VmPjNJsWclidaR/JB9reLPXz
AVoZgpVbcIJ3ntXzmYyIpg==

Initilization Vector (16 bytes):
JDkX+NZLCjW1IXaV8qHmFA==

Derived Key (32 bytes):
JJN8Ms4s4On7sSHpDGm+TZkEbJPUhV2WJ2RxhWUpjus=

Encrypted Text (368 bytes):
7invqU61t5YP6R5ZzLo80jhEUBDAnu3MT/PoRgPc0plM+XyTH/vVNy9Vs6wwaamBPRhW0i6mWHrs2UxV
M65DuBFB3WLGyUfPEuJO2q37NWhWshkozMnY/fRM6reKQbVv8r5fLNPaDpf/JrJnRQfbK573yIBLOAN6
1xNUkXRH0xamUBMV1M4orQ1aa/6Z00ziHKTNKilsDJ9S5AwP5qMpYk9clnQd6UgSPEC+w1vv58Ca7Zkf
6KTXTnUGWIDK0mmJIU0/vJeeijPrcvgo1IJj2CCJfMLXhrmCCX4VZw5ahMZr+3d2YzYO6qfpoaMFIoJn
h52Qs0KzgYaNR1tUIHrqGJPAEiBabtW8NnmsnzTRdZtrGpTe+aZddztpXyqNhsqxsxmvxHNPKjWIxAAx
SWRyFQsWVs9uvCadS8dus3og5pU10HxfGL8WNGVtzy+hJ30bROJ73DyukxWtlX1kzeUc7lOUCh8kZKkG
KOArExGY2JY=

Decrypted Text (355 bytes):
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi rutrum pulvinar p
urus, nec ornare neque cursus id. Nunc non tortor est. Morbi laoreet commodo tel
lus, et suscipit neque elementum eu. Sed velit lorem, ultricies id varius vitae,
 eleifend eget massa. Curabitur dignissim eleifend quam, sit amet interdum velit
 rutrum vel. Nulla nec enim tortor.

That concludes my epic tour de AES in .NET. It’s like writing papers in college all over again. Hope somebody finds it useful.

Using PhoneGap to Access Native iPad APIs

I’m working on a project that required an iPad “application”, which we ended up writing as an HTML site that is accessed in Safari.  Later, that same app had a requirement to access the camera roll on an iPad.  Thanks to Chris Rudy here at IK for introducing us to PhoneGap – a way to wrap your HTML web page(s) in a framework that is then compiled into a native application for the OS you’re targeting (iPad, Android, WinPhone7, etc).  Chris blogged about it here and here.

Unexpected Error

The PhoneGap framework exposes a handful of APIs to access the native hardware on the device (such as camera, accelerometer, compass, contacts, etc).  This all sounded great.  I sat down to write the code, following the examples in the API docs.  I could access the camera roll no problem – the user is shown the photos, they choose one, and you wake up in an event handler in your code.  Next I would try to post that image to a simple REST API running on my Windows machine. No matter what I did, I would get an “Unexpected Error” from the post.  I tried the PhoneGap FileTransfer API and then some more low level AJAX post methods.  All resulted in errors.

I let the code sit for a week until the next RECESS, when I dug a little deeper.  I finally found that I was running into a KNOWN BUG in the Camera API, and that it was fixed and released THAT DAY.  So now with PhoneGap version 1.6.1, the Camera.getPicture( ) method will properly return the BYTES of the image chosen from the camera roll instead of the URL to the local file.  These base64-encoded bytes are obviously what I want to post to my web server.  The code as posted everywhere around the web now works fine (notice I gave up on the FileTransfer object and just post the bytes using AJAX):

function browseCameraRoll()
{
	navigator.camera.getPicture( onPhotoLoadSuccess, onFail,
		{
		quality: 50,
		destinationType: Camera.DestinationType.DATA_URL,
		sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
		encodingType: Camera.EncodingType.PNG,
		} );
}

function onPhotoLoadSuccess( imageData )
{
	var url = 'http://myserver.com/UploadImage2';
	var params = { base64Image: imageData };

	$.ajax({
		   type: "POST",
		   url: url,
		   data: params,
		   success: function (returndata)
		   {
			//alert( 'back from POST: ' + returndata.Status );
			grayscaleImage.src = "data:image/png;base64," + returndata.GrayscaleVersion
		   }} );
}

File Access APIs

Today I continued by learning the file access APIs.  I simply want to write a configuration file in isolated storage the first time the application runs, and then read it on each subsequent startup.  This is super simple, and from what I can tell, does not even require using PhoneGap.  The HTML5 File System APIs can be used to read and write files, create directories, etc. Here is a good write-up on the available APIs.  I thought since the FileWriter and FileReader objects are listed in Cordova’s PhoneGap API documentation, that I was getting an instance of the file through the HTML5 APIs, and then using PhoneGap APIs to read and write the file.  This doesn’t seem to be the case.  FileWriter and FileReader are HTML5 APIs.  Still a bit confused on why Cordova claims them as theirs (assuming just for the convenience of having all the docs in one place).

In any case, file access was a piece of cake – just followed the example here.

 


 

WP Simplified: Wireframes and Information Map

In architecture a blueprint must exist before a house or office complex can be built. Without the blueprint there would be mass confusion and little if anything would ever happen. The final product would be disaster. The same concept applies to software especially on the phone. If you just start coding the resulting app would struggle to be coherent or usable to the consumer. In order to prevent this we need some kind of software blueprint to help the developer stay focused and deliver what is desired and intended. Over the last 3 years here at InterKnowlogy I’ve come across a variety of ways to represent the flow and design of an application. I have gone from paper to whiteboards to Visio to combinations of all of the above and more. What I’ve discovered is the digital formats take too long to accomplish anything so they are more of a final design asset rather than the means to get to the desired result. Whiteboards are my preferred medium for sketching wireframes and information flow. Microsoft has one of the coolest examples of wireframes participating in the flow of information called an Information Map. The example image on the aforementioned site is not the highest quality, but it demonstrates the intended purpose.

Information Map

As I mentioned earlier I don’t like going to a digital medium because I feel it takes too long to make it worth while. But I am a huge fan of the whiteboard so I’m including am image of the information map of LionHeart that I created on a whiteboard. Thus, digitizing my whiteboard information map. It’s not beautiful but it conveys the idea clear enough that I feel little to no need to rework it using Visio or some other pretty digital designer.

There are just a few important items to mention here. First, the Windows Phone platform has some strict navigation rules namely the back button always goes back to the previous page. There are times this rule can be ignored such as when going to a settings screen and selecting save. Hitting the back button after selecting save should not return to the settings screen in most cases. Essentially any screen that is treated more like a modal dialog should not be returned to via the back button. These cases should be called out in the information map. Second, certain UI aspects should be called out such as multi-select lists, pivot or panorama control, or other controls using none intuitive interactions (based on a static drawing). Finally, remember that these information maps only take the UI aspect of the application into account. Do show the layout to some of your colleges or potential consumers and make sure the flow of the app cuts down on as many touches as possible to accomplish what is important. Once the information map is complete then it’s time to move on to the project structure and start coding!

Code Architecture

This is an entire different beast. I will not be covering this topic now. Perhaps at a future time. Admittedly, code architecture is one of those religious wars that I absolutely LOVE to discuss. For now I will only say that after you have an information map completed decide on what models exist and what VMs exist. Remember if commands will be used for buttons such as with the BindableApplicationBar that VMs should be used. Also, take into account if you will be using IsolatedStorage or the local application database. LionHeart is designed around IsolatedStorage for purpose of its demo.

Monotouch and iOS Storyboard limitations

Recently I’ve been doing MonoTouch research for iOS development.  While doing so I ran into a limitation when using MonoTouch and the new iOS Storyboards.  What I’ve found is that in general, MonoTouch and Storyboards play along really well together.  However, I found they only play nicely if you don’t need to create any custom controls that manage ViewControllers and navigation.  If you are just creating a simple application that has very straightforward navigation and uses only the standard iOS controls or subclassed controls, Storyboards are the way to go.  If you decide that you want custom controls that manage ViewControllers and want finer control over navigation, Storyboards are not for you.  What brought this about was I decided I wanted a neat UITabBar that would have an action button in the middle (similar to Instagram and other photo sharing applications).  I quickly realized this isn’t possible by subclassing the UITabBar without a lot of hackish techniques.  I decided I was going to create my own UITabBar.  In order to do this I needed to create a custom view to act as the tab bar and to manage the active ViewController.  This meant instantiating and managing the ViewControllers in code.  Now here is where Storyboards fail.  The problem I ran into was that the code generated by MonoTouch for my ViewControllers did not contain the proper constructors/bindings needed to instantiate them from code nor could I wire them up myself.  MonoTouch had generated some code to bind the ViewControllers’ classes to the Storyboard but it doesn’t allow access to it.  Now, sure, I know I could create a method to open the xib and search for the resource to bind to but that seems nasty to me and kludgy.  I wanted nice clean binding between my code behind and my xibs.  I found that the way to have clean bindings and be able to dynamically instantiate and manage ViewControllers from code was to keep them separate in their independent xibs.  Going this route allowed me  to use those ViewControllers in both ways, via code and via Interface Builder.  In short, if you plan on using MonoTouch to create an app that needs to be able to instantiate and show ViewControllers via code, do not use Storyboards.  Otherwise, go for it because Storyboards really simplify navigation and also give you an overview of your application flow.

Simplifying the Windows Phone development experience! Codename: LionHeart

Each time you start a new project one of the first things most of us developers do is pull in code we want to reuse. If we don’t have any existing code then we try to figure out how to leverage concepts and theories from past experiences and platforms. The latter is exactly what we did during the development of my last project, a Windows Phone project. We have a ton of XAML and MVVM experience here at Interknowlogy, and a few of us had done small RECESS phone apps. None of us had done a full blown app from scratch on the phone before, but today I can say we did an awesome job! What I want to focus on are the lessons we learned from that project and how to apply them to future phone projects to help simplify the process. My coworker Tim Askins and I spent a few RECESS discussing what we could improve on and and what we thought went well. The result is what I call LionHeart.

Introduction to LionHeart

LionHeart is a demo phone app that I am working on that is applying the code lessons learned. These lessons include application lifecycle, navigation, tombstoning, MVVM on the phone, how to provide mock data vs. real data, styling, and many more. The project it self is a demo based on work my wife does as a Behavior Interventionist (BI) for children with autism. We got talking about what could potentially simplify her line of work as well as provide a compelling demo app for the phone. The resulting app will allow for BIs to create reports that are currently done on paper, then transferred to another paper and placed in a binder, then that binder is driven to the main office once a month, and then driven back to the client’s home where BIs go when then work with the children. Wow, that was a mouth full. The app will also allow BIs to view their schedule of sessions for the day/week/month/etc. from within the application. The schedule will also be integrated into the normal phone calendar from Windows Live as well. Individual client information will also be available including previous reports, charts showing progress, and whether there will be a supervisor attending the session as well. Sound like a full blown app? I’m really excited to bring this app to life. I just wish it wasn’t just a demo app.

Components of LionHeart

Let’s remind ourselves again that the reason we are am creating LionHeart is to help solidify patterns and practices on the phone that will help simplify and speed up the development process of future phone apps. Since there are so many components to LionHeart I wanted to give a brief overview of what I think some of those components will be over the next few weeks.

Framework Components

Application Components

  • HomeVM
  • Navigating to Pages with a Pivot Control and to a Specific PivotItem
  • Calendar Integration
  • Styling

With that said as I complete each post I’ll update the list with links.

Final Thoughts

When all is said and done these components should provide a solid foundation for developing on the Windows Phone platform. If you have any questions or thoughts about how to improve on our design please let me know. Happy Coding!

How to create a WinRT WRL C++ Component from scratch that can be consumed by .NET components

If you have to develop Hybrid WinRT Components that expose both COM and WinRT components you have to either write bare metal C++ or use the new Windows Runtime Template Library, which supports you in dealing with COM. More about WRL can be found at http://msdn.microsoft.com/en-us/library/hh438466(v=vs.110).aspx

Microsoft provided a few sample WRL C++ Projects. However they did not include a WRL C++ Project Template in the Visual Studio 2011 Consumer Preview. I reverse-engineered the Sample Projects to find out what is necessary in order to develop a WRL Component from scratch as I didn’t want to use the available Sample Projects as my Project foundation. I also modified the Project in a way that the resulting DLL contains not only the COM component itself but also the proxy/stub implementation.

These are the steps I came up with:

  1. Create a new “Visual Studio C++ – Windows Metro Style – WinRT Component DLL” Project. I called it “WRLTemplate”.
    (Please make sure that the solution folder does not contain any white spaces.)
  2. Delete the automatically created WinRTComponent.cpp/h files.
  3. Add Module-Definition File “WRLTemplate.def”

    Set the content to the following, describing all exported methods of the DLL

    EXPORTS
    DllCanUnloadNow         PRIVATE
    DllGetActivationFactory PRIVATE
    DllGetClassObject       PRIVATE
    
  4. Add the MIDL File “WRLTemplate.idl”. The content will be added later, when we define the modules’ functionality.
  5. Open the Project Settings from the Solution Exporer and adjust the following settings
  6. C/C++ General Tab
     
    • Additional Include Directories: $(IntermediateOutputPath);$(ProjectDir);$(OutDir);%(AdditionalIncludeDirectories)
    • Consume Windows Runtime Extension: No
  7. C/C++ Preprocessor Tab

    • Preprocessor Definitions:
      ENTRY_PREFIX=Prx;REGISTER_PROXY_DLL;PROXY_CLSID_IS={ 0x24352b56, 0xa2ea, 0x4327, { 0xba, 0xcb, 0xe9, 0xea, 0x33, 0x8d, 0xb3, 0x9d } };_WINRT_DLL;WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)

      Those are mainly necessary for the Proxy/Stub, which will be part of the same component. ENTRY_PREFIX defines the Prefix of the generated exported DLL entry methods of the Proxy/Stub and is necessary to avoid naming conflicts

  8. Linker – Input Tab.
    Add rpcrt4.lib as an Additional Dependency
  9. MIDL General Tab
    • Additional Include Directories: $(LibraryWPath);$(ProjectDir);%(AdditionalIncludeDirectories)
    • Additional Metadata Directories: $(LibraryWPath);%(AdditionalMedataDirectories)
  10. MIDL Output Tab
    • Metadata File:$(OutDir)%(Filename).winmd
    • Header File:%(Filename).h
    • IID File:%(Filename)_i.c
    • Proxy File:%(Filename)_p.c
  11. MIDL Command Line
    • Additional Options: /ns_prefix
      This will add the “ABI” Prefix to the generated namespaces in the proxy/stub files.
  12. Custom Build Step General Tab

    • Command Line: mdmerge -partial -i “$(OutDir).” -o “$(OutDir)Output” -metadata_dir “$(WindowsSDK_MetadataPath)” && copy /y $(OutDir)Output\* $(OutDir)
    • Outputs: $(OutDir)%(TargetName).winmd
    • Execute After: Midl
  13. Add common includes to the generated pch.h file
    #pragma once
    
    #include <SDKDDKVer.h>
    
    #define WIN32_LEAN_AND_MEAN
    
    //Windows Header Files:
    #include <windows.h>
    #include <assert.h>
    #include <tchar.h>
    #include <Strsafe.h>
    
    //WRL
    #include <wrl\client.h>
    #include <wrl\implements.h>
    #include <wrl\ftm.h>
    #include <wrl\event.h>
    #include <wrl\wrappers\corewrappers.h>
    #include <wrl\module.h>
    
  14. Set the WRLTemplate.idl content, which describes what functionality your Component will expose
    import "Windows.Foundation.idl";
    
    #include <sdkddkver.h>
    
    namespace WRLTemplate
    {
    	runtimeclass MyComponent;
    
    	[version(NTDDI_WIN8), uuid(9789F754-FF6E-4AB5-9868-C1430D294A1B)]
    	interface IMyCallbackProvider : IInspectable
    	{
    		HRESULT Call([in] HSTRING callbackValue);
    	}
    
    	[version(NTDDI_WIN8), uuid(1589F754-FF6E-4AB5-9868-C1430D294A1B), exclusiveto(MyComponent)]
    	interface IMyComponent : IInspectable
    	{
    		HRESULT Foo([in] HSTRING someString, [in]IMyCallbackProvider* myCallback);
    	}
    
    	[version(NTDDI_WIN8), activatable(NTDDI_WIN8)]
    	runtimeclass MyComponent
    	{
    		[default] interface IMyComponent;
    	}
    }
    
  15. Add MyComponent.h
    #include "pch.h"
    #include "WRLTemplate.h" //Generated by the MIDL compiler
    
    using namespace Microsoft::WRL;
    using namespace ABI::WRLTemplate;
    
    namespace WRLTemplate
    {
    	class DECLSPEC_UUID("A23CF192-F869-4DFE-9477-4045A73CA2AB") MyComponent :
    		public RuntimeClass<
    			// WRL
    			RuntimeClassFlags<RuntimeClassType::WinRtClassicComMix>,
    			FtmBase	,
    			// Custom
    			IMyComponent>
    	{
    		InspectableClass(RuntimeClass_WRLTemplate_MyComponent, TrustLevel::BaseTrust);
    
    	public:
    		// IMyComponent
    		IFACEMETHOD (Foo)(HSTRING someString, IMyCallbackProvider* myCallback);
    	};
    }
    
  16. Add MyComponent.cpp
    #include "pch.h"
    #include "MyComponent.h"
    
    namespace WRLTemplate
    {
    	IFACEMETHODIMP MyComponent::Foo (HSTRING someString, IMyCallbackProvider* myCallback)
    	{
    		myCallback->Call(someString);
    
    		return S_OK;
    	}
    }
    
  17. Add WRLTemplate.cpp
    #include "pch.h"
    #include "MyComponent.h"
    
    // COM proxy/stubs
    extern "C" HRESULT WINAPI PrxDllGetClassObject(REFCLSID, REFIID, _Deref_out_ LPVOID*);
    extern "C" BOOL WINAPI PrxDllMain(_In_opt_ HINSTANCE, DWORD, _In_opt_ LPVOID);
    extern "C" HRESULT WINAPI PrxDllCanUnloadNow();
    
    BOOL WINAPI DllMain( __in_opt HINSTANCE hInstance, __in DWORD dwReason, __in_opt LPVOID lpReserved )
    {
        if( DLL_PROCESS_ATTACH == dwReason )
        {
    
            //
            //  Don't need per-thread callbacks
            //
            DisableThreadLibraryCalls( hInstance );
    
            Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule().Create();
        }
        else if( DLL_PROCESS_DETACH == dwReason )
        {
            Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule().Terminate();
        }
    
        PrxDllMain( hInstance, dwReason, lpReserved );
    
        return TRUE;
    }
    
    STDAPI DllGetActivationFactory(_In_ HSTRING activatibleClassId, _COM_Outptr_ IActivationFactory** factory)
    {
        auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
        return module.GetActivationFactory(activatibleClassId, factory);
    }
    
    STDAPI DllCanUnloadNow()
    {
        auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
        return module.Terminate() ? S_OK : S_FALSE;
    }
    
    STDAPI DllGetClassObject( __in REFCLSID rclsid, __in REFIID riid, __deref_out LPVOID FAR* ppv )
    {
        auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
        HRESULT hr = module.GetClassObject( rclsid, riid, ppv );
        if (FAILED(hr))
        {
            hr = PrxDllGetClassObject( rclsid, riid, ppv );
        }
        return hr;
    }
    
    namespace WRLTemplate {
    	ActivatableClass(MyComponent)
    }
    
  18. Try to compile. It will fail.
  19. Add the Proxy Stub files to the solution: Select “Show all files” in the Solution explorer and include dlldata.c + WRLTemplate_i.c, WRLTemplate_p.c to the solution
  20. Deactivate the usage of Precompiled Headers on these 3 files by going to their properties (right click and select Properties) and changing the Precompiled Header to Not Using Precompiled Headers
  21. Recompile – should work fine. Now use the Component from a C# project
  22. Create a new C# project

  23. Add Reference to the winmd file. Make sure you do NOT select WRLTemplate.winmd from the Output folder. Although they are binary equal you will get an exception at runtime, telling you that the Type is not registered.
  24. Instantiate the COM component and use it for example in your BlanPages’ OnNavigatedTo-Method
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                var comp = new MyComponent();
                var callback = new Callback();
    
                const string testString = "Test";
                comp.Foo(testString, callback);
    
                Debug.Assert(callback.ReceivedValue == testString);
            }
    
            class Callback : IMyCallbackProvider
            {
                public string ReceivedValue { get; set; }
    
                public void Call(string callbackValue)
                {
                    ReceivedValue = callbackValue;
                }
            }
    
  25.  If you followed all steps correctly, the solution should compile and work as expected :-)

If you have specific questions regarding any of these settings please post a comment and I will get back to you.
I attached the example solution (WRLTemplate). Please note that you will have to compile the project “WRLTemplate” and again reference its WRLTemplate.winmd afterwards in the ConsumerApp project.

Presentation Materials for New England Code Camp 17

Thanks to everyone for coming!

What’s new in Visual Studio 11: Slides | Code
Check the slides for the list of all of the new Visual Studio features we looked at.

Easy Async in .NET 4.5: Slides | Code (for VS11 Beta)
The only code demo we didn’t get to look at can be found in the AddingAsync page, which shows a progression of converting a more complex 2 step data loading process from fully synchronous to fully asynchronous including cancellation and exception handling.

How to REALLY consume a WinRT object with the WRL

Microsoft published an example that supposedly demonstrates how to consume a WinRT object with the WRL at How to Create and Consume an Object.

However, if you’ve tried that example you probably noticed that it simply does not work as the following snippet returns E_INVALIDARG.

ComPtr<IActivationFactory> uriActivationFactory;
HRESULT hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Foundation_Uri).Get(), &uriActivationFactory);

The problem is, that HString::MakeReference(RuntimeClass_Windows_Foundation_Uri) does not return a valid HStringReference-instance.

Instead, you should create a HStringReference-object using its constructor and pass that instance to the GetActivationFactory call:

ComPtr<IActivationFactory> uriActivationFactory;
HStringReference runtimeClassUri(RuntimeClass_Windows_Foundation_Uri);
HRESULT hr = GetActivationFactory(runtimeClassUri.Get(), &uriActivationFactory);

Now, the call should return S_OK and you’ll have a valid uriActivationFactory that you can work with.