TechEd Europe 2009 Day One

Today was my first day at TechEd Europe 2009 in Berlin, after having arrived to the hotel on sunday evening. I chose to drive to Berlin myself from Denmark, which went just fine, until I scratched a rim on the way down into a very narrow passage to the parking garage. Damn. The TechEd experience so far has been just great, although there was some queue for registration this morning. I guess it is hard to avoid when you have 7000+ people attending an event, and they all, more or less, arrive at the same time.

My first session at TechEd was titled "ADO.NET Entity Framework in Microsoft Visual Studio 2010 and Microsoft .NET Framework 4" and was about Entity Framework 4 with speaker Eric Nelson. Wait-a-minute, you might say, because last version of the EF was the initial release, 1.0. It seems that the EF has skipped a couple of versions so that it gets the same version number as the .NET Framework it ships with. That being said, the EF ships some of it's features as a separate download, but the core should be in .NET FX 4.

So what's to say about EF4 ? Well, it seems that Microsoft has fixed it. By that I mean that many of the problems that existed with the initial version has been eliminated or the experience has been improved. This includes better tooling and designer support. There is support for model-first development, where you drag-and-drop your model in a designer, and lets the framework generate the database for you (technically speaking, this also existed in v1, but it required you to do a lot of manual stuff, or as Eric Nelson put it, you would be in for a whole world of pain taking that route.

Something I am more excited about is the ability to control the generated code using T4 templates. This enables different scenarious such as POCO objects, which was missing from v1. There are some built-in templates so you don't need to write them from scratch. If you adhere to the "develop against an interface" to "do TDD" group of people (count me in), it would be quite easy to change the built in templates, so that you would get some nice interfaces to work against. Very nice.

Also, Eric demoed a Code-Only, or "persistance ignorance" support in EF4. With this, you can take some objects, and persist them to a database, and the framework will itself create a database, the schema, and do CRUD operations. While nice for demos, I really can't see the application of this for real-world projects larger than toy-size.

It seems that EF4 is now a serious contender in the ORM world, and I think I will try it out on a real project when I get the chance (of course, it probably needs to go out of beta first).

 

Next session was about ASP .NET 4 and Visual Studio 2010 improvements. This was a very interesting lap around a lot of small improvements and features, that will life better and easier for the web developer. This includes an inheritable viewstate setting, better controls for ClientID generation and better standards-compliant markup from the built in controls; as well as better control over the markup that is emitted. Also, a Code nugget syntax for emitting HTML encoded strings has been added, which will prove handy. One of the things that looks really good is the improved Publish dialog in 2010 and the support for Web.config merges, so that you can have one .config to rule them all, but keep transformations that you can apply automagically when deploying. Together this means, that you can click a button and get your website deployed. I didn't have the chance to ask if this is supported as MSBuild tasks as well, but I suspect it is. I'll have to track down someone who can answer this during the conference. Shouldn't be too hard :-)

 

The rest of the day was keynote sessions. First was the "Developer General" session, by Jason Zander (project manager for the Visual Studio team). Jason talked about the development ecosystem and the effort Microsoft has put into VS 2010 to make a better development experience. This includes push-of-a-button deployment of Sharepoint parts, instead of 22 manual steps. He might have been exaggerating about the 22 steps, but is sounds nice. Oh, he also announced that Microsoft has acquired the Teamprise client suite, which makes it possible for non-Windows, non-Micrsoft, non-.NET devs to work with Team Foundation Server.

Lastly there was the "real" keynote by Stephen Elop, President of Microsoft Business Division. This was a typically "fluffy" talk which did not have much real content for developers. It was interesting though, and he demoed some new features in Windows Server 2008 R2 and Exchange Server 2010. He got the biggest applause when demonstrating, that Outlook Web Access 2010 now runs seamlessly in Firefox & friends :-)

Tomorrow, I have another busy day lined up. Just have to figure out how to be 3 places at once ...

 


Sitecore Dictionary gotcha when using the master database

During some projects at work, we were having a real weird problem with the Sitecore Dictionary feature. This is the built in feature in Sitecore that lets you localize short texts, such as what to put in the "Read more" or "Next page" links on a web page. Of course, there are many ways to do this, but since Dictionary items is a supported Sitecore feature, and they can be edited from within the Sitecore environment, it seems reasonable to use this for Sitecore sites.

This is how it works: You put dictionary items under /sitecore/system/Dictionary. Each dictionary item consists of a shared key and a localized phrase field. That is, the key is the same for all languages, the phrase varies by language. To get a phrase at runtime, you use the static Translate.Text method and pass the key as a parameter, and it will return the correct phrase in the current context language (or you can explicitly pass a Language). This is also described on SDN here (you will need an SDN account to access the article). There even is an XSLT extension function for the Translate methods. Very nice.

The problem we were facing started to occur when we moved some of our front-end developers (who does most of the localization texts) away from working on a test-server, and instead having their own development version on their own workstation, working there (the way it really should be done - also gives you a better chance of running CI). The problem was, that on one developer's workstation you would see one set of Dictionary items on the website, on another workstation there would be a different set. Sometimes all dictionary phrases was completely missing. Inside the Sitecore Content Editor, the data seemed to be correct.

So I started digging around to find an explanation. I started using Reflector to determine what was really going on in the Sitecore.Globalization.Translate class. I quickly found out, that the class internally keeps a Hashtable containing the languages, and in that a Hashtable for each language's texts, in memory. Great for quick lookups. So when and how is the Hashtable filled with data ? This is where it gets tricky. When a phrase is first requested (after a application restart), Sitecore will look for a file called dictionary.dat in the temp directory and try to load it. This is where the Translate class keeps it's persistent cache: Each time a key is added, it will get saved to the file (in addition to being kept in memory); and it will try to load it from there when a phrase is requested, and there is no dictionary data in memory. If reading this file fails, it will rebuild it from the data in the database. Here lies the first problem: You might know that Sitecore operates with a core database (for Sitecore itself), a master database for content and a web database that content is served from. As it turns out, the dictionary will only ever be re-populated with data from the core database. This is hard-coded in the class. And we were adding all our Dictionary items to the master database (since this is really where they should be, it is content). This was my first "that's funny" moment - If the dictionary cache only rebuilds from core; how could our setup ever have worked ??

Time to research some more. After some more tinkering around, I found the Sitecore.Globalization.ItemSaveEventHandler. This is an event handler, that is hooked up to the ItemSaving event in web.config. What this does, is that whenever an item is saved, if it is of type "dictionary item", it will add the key and phrase to the internal language hashtable, which will also trigger a save of the dictionary.dat file. This event handler however, does not care which database is being used. Both master and core (and web for that matter) database saves, will trigger a update of the cache.

This explained everything. If Sitecore is being used on the same machine only, dictionary items in the master database, will work. If it is deployed to production, it will work, because we typically copy the entire website folder, including the temp files, and thus the "correct" dictionary.dat. However, if Sitecore is used in parallel on different servers, you will start seeing the errors we were seing, inconsistent and/or missing dictionary entries. This could be an issue during development if you setup the environment on different developer workstations, but also in staging environments or in load-balanced environments (depending on your setup). If dictionary items (again, in the master database), is saved in parallel on different environments, it will generate different dictionary.dat files with different phrases, and it is impossible to merge. And if you lose dictionary.dat, you can't restore the master dictionary entries without saving each item again.

Revisiting the SDN documentation, though it is quite thin on the subject, it does state that you should add your own dictionary items to the core database. It feels wrong to do this, since our own dictionary items would then be mixed with Sitecore's own internal ones; and because I don't think the core database is a place to store customer data. So I guess it is not a bug that storing dictionary items in the master is not supported, but it would be a nice and reasonable feature. But I do think that there is a bug here; in that it is at all possible to use dictionary items stored in master, when it is not supported. It should definitely work consistently; and not be some half-baked feature that works "occasionally, if you use the right setup". It should also be noted that the Dictionary node is already in the master database in a clean installation, so there are no alarm clocks going off when the novice Sitecore programmer starts using it.

Now, we already have solutions in production using this approach, and time committed on ongoing projects for using it this way. So we needed a way to ensure that dictionary items in the master database would behave consistently and just work.

The solution is below. It is basically a class that can rebuild the Sitecore dictionary from both databases. It reuses the Sitecore logic by invoking their Load and Save methods using reflection, and overwriting the static _languages hashtable field in the Translate class. This is really not pretty, it is a ugly hack, and I would definitely prefer not to use reflection to call into methods that were never intended to be used from outside the class. That being said however, it seems to work - but of course there are no guarantees, and if it blows up or kills your kitten; I'm not responsible.

To use it, simply call the Rebuild method. I used a custom IHttpHandler for the purpose, so I can call the URL whenever needed (don't deploy the handler it into production however ;-) ). After the cache has been rebuilt, you can share the dictionary.dat with other development machines just by copying it, or you can just rebuild when needed at each developer's discretion.

         1: using System;
         2: using System.Reflection;
         3: using Sitecore.Data;
         4: using Sitecore.Configuration;
         5: using System.Collections;
         6: using Sitecore.Data.Items;
         7: using Sitecore.SecurityModel;
         8: 
         9: namespace Webdanmark.SitecoreCMS.Common.Utility
         10: {
         11:     /// <summary>
         12:     /// This class supports rebuilding the Sitecore dictionary from both Core and Master databases.
         13:     /// Default implementation from Sitecore can only rebuild from Core, which leads to various issues if
         14:     /// the temp dictionary.dat file is lost, or editing happens on multiple servers.
         15:     /// </summary>
         16:     /// <remarks>
         17:     /// This class tinkers with Sitecore private methods and internal workings. Not pretty.
         18:     /// This is a hack to workaround a limitation in Sitecore without re-implementing the whole thing.
         19:     /// </remarks>
         20:     public class DictionaryRebuilder
         21:     {
         22:         /// <summary>
         23:         /// Event fired when progress in the task occurs.
         24:         /// </summary>
         25:         public event EventHandler<DictionaryRebuilderEventArgs> Progress;
         26:         /// <summary>
         27:         /// Databases.
         28:         /// </summary>
         29:         private readonly Database[] databases;
         30:         /// <summary>
         31:         /// The Translate type.
         32:         /// </summary>
         33:         private readonly Type translateType;
         34:         /// <summary>
         35:         /// Load method.
         36:         /// </summary>
         37:         private readonly Action<Hashtable, Item> loadMethod;
         38:         /// <summary>
         39:         /// Binding flags for a private static member.
         40:         /// </summary>
         41:         private static readonly BindingFlags privateStatic = BindingFlags.Static | BindingFlags.NonPublic;
         42:         /// <summary>
         43:         /// Save method
         44:         /// </summary>
         45:         private readonly Action saveMethod;
         46:  
         47:         /// <summary>
         48:         /// Initializes a new instance of the <see cref="DictionaryRebuilder"/> class.
         49:         /// </summary>
         50:         public DictionaryRebuilder()
         51:         {
         52:             databases = new[] { Factory.GetDatabase("core"), Factory.GetDatabase("master")};
         53:             translateType = typeof(Sitecore.Globalization.Translate);
         54:             loadMethod = (Action<Hashtable, Item>) FindMethod<Action<Hashtable,Item>>("Load", privateStatic, typeof (Hashtable), typeof (Item));
         55:             saveMethod = (Action) FindMethod<Action>("Save", privateStatic);
         56:         }
         57:  
         58:  
         59:         /// <summary>
         60:         /// Rebuilds the dictionary cache.
         61:         /// </summary>
         62:         public void Rebuild()
         63:         {
         64:             Hashtable rootTable = new Hashtable(10);
         65:             foreach (var db in databases)
         66:             {
         67:                 var langs = db.Languages;
         68:                 SendMessage("\nProcessing {0} database, {1} languages.", db.Name, langs.Length);
         69:                 foreach (var language in langs)
         70:                 {
         71:                     string languageKey = language.ToString();
         72:                     Hashtable languageTable;
         73:                     if (rootTable.ContainsKey(languageKey))
         74:                         languageTable = (Hashtable)rootTable[languageKey];
         75:                     else
         76:                         rootTable[languageKey] = languageTable = new Hashtable();
         77:  
         78:                     RebuildLanguage(db, language, languageTable);
         79:                 }
         80:             }
         81:             SendMessage("\nLanguages loaded.");
         82:             ReplaceSitecoreTable(rootTable);
         83:             SendMessage("Writing data cache to file.");
         84:             saveMethod();
         85:             SendMessage("\nDone.");
         86:         }
         87:  
         88:         /// <summary>
         89:         /// Finds the method.
         90:         /// </summary>
         91:         /// <typeparam name="TDelegate">The type of the delegate.</typeparam>
         92:         /// <param name="name">The name.</param>
         93:         /// <param name="bindingFlags">The binding flags.</param>
         94:         /// <param name="parameterTypes">The parameter types.</param>
         95:         /// <returns></returns>
         96:         private Delegate FindMethod<TDelegate>(string name, BindingFlags bindingFlags, params Type[] parameterTypes)            
         97:         {
         98:             MethodInfo method = translateType.GetMethod(name, bindingFlags, Type.DefaultBinder, parameterTypes, null);
         99:             return Delegate.CreateDelegate(typeof (TDelegate), method);
         100:         }
         101:  
         102:         /// <summary>
         103:         /// Replaces the sitecore table.
         104:         /// </summary>
         105:         /// <param name="hashtable">The hashtable.</param>
         106:         private void ReplaceSitecoreTable(Hashtable hashtable)
         107:         {
         108:             FieldInfo fi = translateType.GetField("_languages", privateStatic);
         109:             fi.SetValue(null,hashtable);
         110:         }
         111:  
         112:         /// <summary>
         113:         /// Rebuilds the language.
         114:         /// </summary>
         115:         /// <param name="db">The db.</param>
         116:         /// <param name="language">The language.</param>
         117:         /// <param name="languageTable">The language table.</param>
         118:         private void RebuildLanguage(Database db, Sitecore.Globalization.Language language, Hashtable languageTable)
         119:         {
         120:             using (new SecurityDisabler())
         121:             {
         122:                 var dictionaryRoot = db.GetItem("/sitecore/system/dictionary", language);
         123:                 if (dictionaryRoot == null)
         124:                 {
         125:                     SendMessage("\tNo dictionary found in {0} for {1}", db.Name, language.Name);
         126:                     return;
         127:                 }
         128:  
         129:                 SendMessage("\tProcessing {0}", language.Name);
         130:                 loadMethod(languageTable, dictionaryRoot);
         131:             }
         132:         }
         133:  
         134:         /// <summary>
         135:         /// Sends the message.
         136:         /// </summary>
         137:         /// <param name="msg">The MSG.</param>
         138:         /// <param name="inserts">The inserts.</param>
         139:         private void SendMessage(string msg, params object [] inserts)
         140:         {
         141:             if (Progress != null)
         142:             {
         143:                 var args = new DictionaryRebuilderEventArgs {Message = String.Format(msg, inserts)};
         144:                 Progress(this, args);
         145:             }
         146:         }
         147:  
         148:         /// <summary>
         149:         /// Event arguments
         150:         /// </summary>
         151:         public class DictionaryRebuilderEventArgs : EventArgs
         152:         {
         153:             /// <summary>
         154:             /// Gets or sets the message.
         155:             /// </summary>
         156:             /// <value>The message.</value>
         157:             public string Message { get; set; }
         158:         }        
         159:     }
         160: }

 And you could use it like this:

        1: DictionaryRebuilder builder = new DictionaryRebuilder();
        2: builder.Progress += (s, e) => Response.WriteLine(e.Message);
        3: builder.Rebuild();

If you want to display progress while rebuilding, hookup the Progress method to some event handler. The one in my example won't compile for you, since Response.WriteLine is an extension method in one of our common libraries.

Disclaimer: The contents of this Blog post is my own opinions only. I am not affiliated with Sitecore in any way. Some of the technical details was extracted using Reflector, and some are educated guesswork. I might be wrong, and Sitecore might very well change the implementation in a later version, so that the information above does no longer apply. This was done on Sitecore 6.0.1. rev 090212, but I suspect that the general idea is the same in previous Sitecore versions. 


Getting your public IP from a PowerShell script

I often work on computers at different locations, and often, I need to know what public IP I am using to connect to the internet. Of course, this is easy to find out - I can just go to a website that tells me my IP, such as http://myip.dk/.

But I find this to be suboptimal. If I am configuring something, finding the IP involves firing up a browser, going to the site, and copying the IP displayed. It is a speed bump when I am trying to be productive - and the display-my-ip sites are often covered in commercials, which I dislike.

So today, I decided to write a PowerShell script that can tell me my current public IP address. First, I needed a reliable way of finding it. Of course, I could just screen-scrape off a site such as http://myip.dk/, but it has some disadvantages. I can't know if the html structure will change - and it would mean that I would have to download all of the HTML just to get a few bytes of IP address. Furthermore, I don't know whether it would be legal at all.

Therefore, I started by writing a small ASP .NET HTTP handler, that could tell me my IP. I put the following simple code in the ProcessRequest method:

 1:     public void ProcessRequest (HttpContext context) {
 2:         context.Response.ContentType = "text/plain";
 3:         context.Response.AddHeader("X-RemoteIP", HttpContext.Current.Request.UserHostAddress);
 4:         context.Response.Write(HttpContext.Current.Request.UserHostAddress);        
 5:     }

This simply writes the IP address the handler is accessed with, to the response as well as to a custom http header. I then deployed this handler to my website.

Next, writing the PowerShell script, was equally simple; we can simply use the handy System.Net.WebClient class:

 1: $ipFinderHost = "http://www.somedomain.org/GetIP.ashx"
 2: $c = new-object System.Net.WebClient
 3: $c.DownloadString($ipFinderHost)

And voila, I have a PowerShell script that displays my public IP address. And, since I have the PowerShell Community Extensions installed, I can use the set-clipboard cmdlet to copy it to the clipboard.

 1: get-myip | set-clipboard

Much nicer than manually copying from the text in a browser :-) If you decide to use this script yourself, obviously you will need to change the URL in the script to where you have deployed the GetIP.ashx handler.


Introducing: The Google Chrome Password Recovery Tool

Today, I wanted to backup all my passwords stored in Google Chrome. I thought that would be an easy task, but it turns out, that this is not supported, at least as far as I can tell. There is an option to view the shared passwords one-by-one, but that was not really an option for me.

So, I decided to write a small program to extract the passwords from Chrome. Since Chrome (or Chromium, to be exact), is open source, I pulled the source from http://dev.chromium.org/getting-involved, compiled it, and starting looking around trying to figure out how passwords are stored. The setup and build experience was much nicer than what I have tried with other open source projects I have looked at; there are detailed build instructions with only a few steps available, and after setting up, it just works, in a Visual Studio 2008 solution. A full recompile does take some time however (45 minutes on my machine).

I quickly found out that Chrome stores most of its user and configuration data in small SQLite databases stored on disk in the AppData/Local/Google/Chrome/User Data directory. So, reading the data was no problem after grabbing a copy of the ADO .NET Provider for SQLite, as well as the sqlite3.dll binary from http://www.sqlite.org/. The data I was after (user names and passwords) is stored in the file named Web Data. This contains a table named logins, which contains the URL for which the login is valid, some details about the html form where the password has been used (in order to allow Chrome to auto-fill password boxes for you), and the username and password. It also contains a "preferred" and "blacklisted_by_user" column.

Decrypting the passwords

The passwords is, obviously for security reasons, not stored in plain text. Rather, they are encrypted, so I needed to figure out how they are encrypted and how to decrypt them. The answer lies in the Chromium source, where the Encryptor class contains the following method:

bool Encryptor::EncryptString(const std::string& plaintext,
                              std::string* ciphertext) {
  DATA_BLOB input;
  input.pbData = const_cast<BYTE*>(
    reinterpret_cast<const BYTE*>(plaintext.data()));
  input.cbData = static_cast<DWORD>(plaintext.length());

  DATA_BLOB output;
  BOOL result = CryptProtectData(&input, L"", NULL, NULL, NULL,
                                 0, &output);
  if (!result)
    return false;

  // this does a copy
  ciphertext->assign(reinterpret_cast<std::string::value_type*>(output.pbData),
                     output.cbData);

  LocalFree(output.pbData);
  return true;
}

As it turns out, the Windows Data Protection (DPAPI) is used to encrypt the data, namely the CryptProtectData function as shown above. Therefore, I can relatively easy decrypt the data, using the CryptUnprotectData function, as long as I do not try to decrypt the password of other users - the DPAPI encrypts with a key based on the current user's login credentials. I first tried to do the decrypting in C# using P/Invoke the the CryptUnprotect function, but for some reason, I could not get that to work. I kept getting a credentials dialog from Windows when trying it, which is not what i want. Luckily, after googling a bit, I found out that there already exist a managed wrapper for doing this, namely the ProtectedData class. After switching to using this, there were no problems decrypting the passwords.

The password recovery tool

I wrote a tiny C# console program to dump the passwords. They can be dumped to the console (default) or to an XML file. Running the program without parameters will try to dump all the passwords to the console. You might need to have Chrome closed while doing this. Run the program with the -help switch to display a short usage information message.

I am including the program for download here - both in a precompiled form and the C# source. It requires .NET Framework 3.5. The program as well as it's source is free for use non-commercially and is provided without any warranty or obligations for me, neither explicit or implied. It probably won't kill your cat, but don't come to me crying about it if it does ;-). If you wish to use the source or derivate thereof in a commercial product, contact me for permission first.

Download:

What is missing ?
It would be nice to have an option to import the exported passwords into a new Chrome installation on another computer. I am considering adding it, but don't really need it at this time. It should be relatively easy - if you happen to develop the feature based on my work, please email me the source.


Thoughts on Google Chrome

I admit it, I am a fan of the new Google Chrome browser.

This made me chuckle, however:
Google vs Microsoft ... ?

Is Google preparing to dominate the world ?


Making The HTC Touch Diamond Vibrate

One of the minor problems I had when making the Stopwatch for my HTC Touch Diamond, was to make the phone vibrate automatically. It seems there are no managed way of doing this. However, after a bit of googling around, I found out that the vibrator typically can be addressed as a LED object using the Open NET CF Framework. So I decided to throw together a tiny wrapper class around this functionality, so I can use it generally in the future. The most useful thing here, I think, is the ability to have the phone vibrate using a given on-off pattern in a fire-and-forget pattern that works well when programming Compact Framework forms.

This is the simple Vibrator class:

         1: using System;
         2: using System.Threading;
         3: using OpenNETCF.WindowsCE.Notification;
         4:  
         5:  namespace dr.WM.Common
         6: {
         7:     /// <summary>
         8:     /// Vibrator class. Works on HTC Touch Diamond, not tested anywhere else.
         9:     /// (Mostly, The LED index could be different on other devices.)
         10:     /// </summary>
         11:     public class Vibrator
         12:     {
         13:         /// <summary>
         14:         /// Index of the Vibrator LED.
         15:         /// </summary>
         16:         private const int VibratorLedIndex = 1;
         17:         /// <summary>
         18:         /// LED instance.
         19:         /// </summary>
         20:         private readonly Led led = new Led();
         21:         /// <summary>
         22:         /// Whether the Run thread is allowed to run.
         23:         /// </summary>
         24:         private bool allowRun = false;
         25:         /// <summary>
         26:         /// Starts this instance.
         27:         /// </summary>
         28:         public void Start()
         29:         {
         30:             allowRun = true;
         31:             led.SetLedStatus(VibratorLedIndex,Led.LedState.Blink);
         32:         }
         33:  
         34:         /// <summary>
         35:         /// Stops this instance.
         36:         /// </summary>
         37:         public void Stop()
         38:         {
         39:             allowRun = false;
         40:             led.SetLedStatus(VibratorLedIndex, Led.LedState.Off);            
         41:         }
         42:  
         43:         /// <summary>
         44:         /// Starts a vibrating sequence by specifying the vibrate and pause times.
         45:         /// Vibration will run until the Stop method is called.
         46:         /// </summary>
         47:         /// <param name="msVibrate">The vibrate time in milliseconds.</param>
         48:         /// <param name="msPause">The pause time in milliseconds.</param>
         49:         public void StartSequence(int msVibrate, int msPause)
         50:         {
         51:             StartSequence(msVibrate,msPause,0);
         52:         }
         53:         /// <summary>
         54:         /// Starts a vibrating sequence by specifying the vibrate and pause times.
         55:         /// Vibration will run for the specified total time, or until the Stop method is called.
         56:         /// </summary>
         57:         /// <param name="msVibrate">The vibrate time in milliseconds.</param>
         58:         /// <param name="msPause">The pause time in milliseconds.</param>
         59:         /// <param name="totalLength">The total time to vibrate.</param>
         60:         public void StartSequence(int msVibrate, int msPause, int totalLength)
         61:         {
         62:             allowRun = true;
         63:             ThreadPool.QueueUserWorkItem(Run,
         64:                                          new RunState
         65:                                              {VibrateTime = msVibrate, PauseTime = msPause, TotalTime = totalLength});
         66:         }
         67:  
         68:         /// <summary>
         69:         /// Thread worker for a vibrating sequence.
         70:         /// </summary>
         71:         /// <param name="state">The state.</param>
         72:         private void Run(object state)
         73:         {
         74:             long begin = Environment.TickCount;
         75:             RunState runState = (RunState)state;
         76:             while(allowRun && (runState.TotalTime <= 0 || Environment.TickCount - begin < runState.TotalTime))
         77:             {
         78:                 led.SetLedStatus(VibratorLedIndex, Led.LedState.Blink);
         79:                 Thread.Sleep(runState.VibrateTime);
         80:                 led.SetLedStatus(VibratorLedIndex, Led.LedState.Off);
         81:                 Thread.Sleep(runState.PauseTime);
         82:             }
         83:         }
         84:  
         85:         /// <summary>
         86:         /// Helper for passing vibration state to the worker thread.
         87:         /// </summary>
         88:         private struct RunState
         89:         {
         90:             public int VibrateTime { get; set; }
         91:             public int PauseTime { get; set; }
         92:             public int TotalTime { get; set; }
         93:         }
         94:     }
         95: }

Please note that this might (propably) will not work on other devices, since the vibrator might not be on the same LED index. One could refactor the class and make a couple of vibrator on/off virtual protected methods, and call these from the Start / Stop methods. That way, it could be easy to make the class general enough for use on other devices, you would just need to implement the start and stop operations. However, there might be an easier way of doing this using an unmanaged API (actually I hope there is, since collecting info about all types of devices in order to figure out how to fire the vibrator, seems as an unfeasible task).

It seems that the Klaxon Open-Source alarm clock for Windows Mobile has just been made Open Source. I think I will have a look at the source to see whether my way of using the vibrator is feasible, or the Klaxon author uses a better approach ;-)


A Stopwatch for Windows Mobile

I have got a new mobile phone, a HTC Touch Diamond. Besides the fact that it has a sleek design and is much easier to work with when reading email and browsing the web than my old phone.

However, that it is not the only reason for buying the Diamond. Another, very important reason, is that it runs Windows Mobile 6.1 - and therefore I can write my own programs for it using pretty much the same toolset as I use for any other .NET program. Granted, there are stuff missing in the Compact Framework compared to the full-blown framework (Expression trees anyone ?), but it is normally quite easy to find alternatives, and the Compact Framework does make it quite easy to program the device.

My first application for the Touch is a simple Stopwatch program. I wrote it, because there was no stopwatch and/or timer program on the Touch when I got it, so why not write my own ;-) The application it is quite simple, but I learned quite a deal about the device and the Compact Framework while developing it. It essentially relies on the Environment.TickCount counter to measure time, so it might not be 100% accurate - but for my needs (such as heating pizza's), it is quite sufficient.

If anyone's interested, you may download the source from here. If you want to compile it, you will need a copy of the OpenNET CF Framework, because I needed to use some parts of it for making the phone vibrate when the alarm goes off. (It could be replaced with some P/Invoke calls, but i got lazy ;-)

The application itself has the following features:

  • Simple stopwatch
  • Timer with alert (vibration and sound)
  • Configurable alarm sound (only .wav files, sorry).
  • Settings are remembered (stored in Application Data)

Last Day at Jaoo

Wednesday was the last official day of the JAOO conference, and once again it featured a bunch of interesting talks. I attended these:

50 in 50
This was todays keynote by Richard P. Gabriel and Guy L. Steele Jr. Before the talk, there had been some speculations about the title; was it 50 programming languages in 50 minutes ? Or what did it mean exactly ? It turned out to be 50 comments about programming and programming languages, in 50 minutes. These focused on the history of programming and did so in an entertaining and enlightening manner. This was a certainly a great talk - and for a "young" programmer like my self what was not even born when Ada and Algol 60 appeared; it provided also some historical insight. Only downside to this talk, is that the schedule was affected by the fact that it was more like 50 in 75 - the talk took about 75 minutes; but with this quality of technical and on the same time entertaining talk, that does not really matter for me.

Five Considerations For Software Developers
This was also a dual talk with two presenters - Frank Bushmann and Kevlin Henney. They talked about architecure and specifically five considerations that drives design quality. Those were:
  • Economy - the idea that software must be built for a reason and should not have an complicated or elaborate design just because it *might* be needed in the future.
  • Visibility - in the sense that the design must be easily discoverable.
  • Spacing - basically the idea to separate concerns and make sure not to bake the design into deep inheritance hierarchies that xould better be expressed with composition.
  • Symmetry - in that API's should be symmetric with the example that if you can create something with a Factory, said Factory should also be able to destroy it
  • Emergence


LINQ + New Microsoft Things
This talks title is actually wrong, since Erik Meijer primarily talked about LINQ, and very little about "New Microsoft Things". To be fair, he did not have much time to cover it all since the talk got started late because of the schedule slip at the keynote earlier on the day. LINQ was covered well, however, and from a slightly different angle than Anders Hejlsberg talked about earlier in the week. Erik talked about Expression trees and how they represent code as data. This makes it possible to hand an expression tree to an interpreter for a given query language, that can then execute it in the given domain. This is why we (in theory) could forget all other query languages such as XQuery or SQL, and only use Linq-to-Xxx - given that someone writes a Xxx extension to LINQ, of course.

Real World Refactoring
This talk about Refactoring by Neal Ford addressed the challenges that goes into actually performing refactorings in code. It was very hands-on and offered some good advice on how to structure refactorings. One of the best pieces of advice, I think, was to time-restrain major (multi-day) refactoring efforts to an estimated period of time before-hand. If you cannot complete the planned refactoring in the planned time, take the time to rethink the problem, and find out if you are doing it right. If not, you can throw the refactored code away and try again, instead of keeping on a track, that might resolve to more complicated code than before; because new knowledge has beeng gained during the process or because the refactorings was not well enough planned and thought out in advance.

JavaScript As An Assembly Language
This second presentation by Erik Meijer was primarily about Volta, an exciting new technology from Microsoft's Live Labs. The project basically promises to make it easier to make multi-tier applications that can run on the server and work with any client, with parts being executed on the client. This is done by decorating methods with custom attributes, that marks them for running on the client. The Volta compiler will then "compile" those to javascript, that can run on any client (or, if Silverlight is available on the client, the code will run in Silverlight as .NET IL). Erik explained the technology behind, and how they generate javascript code and the various problems involved in that. I do not think that this technology is quite ready to be used in the wild yet, but it should definitely be interesting to see how it evolves in the future. The documentation site on Live Labs seems to be down for the moment, however, this blogpost also explains the technology in more detail.

Concurrent Programming with Concurrent Extensions to .NET
In this talk, Joe Duffy, gave an introduction to the parallel extensions to .NET, a new API for writing concurrent applications with .NET. These extension is in CTP right now (so it's preview technology, not recommandable for production use). Joe promised though, that these APIs will be part of the .NET Framework version 4 release. These new APIs promise to make it easier to write concurrent applications with .NET with little overhad, both mentally for the programmer, but also performance-wise for the machine. The presentation featured running demos and code, and I believe that the new APIs are quite well-designed and that there is definitely a need for this kind of API in todays world of multi-core hardware. However, as Joe pointed out, there is no such thing as a free lunch; and even when using this API, of course you need to think hard over concurrency issues and side-effects before you can put it to use. The system makes it easier for you to program concurrently; but you can still fail badly if you do not understand what it does under the covers.

JAOO Day Two

Today on JAOO has also been packed with interesting talks. I attended these:

V8: The Javascript engine inside Google Chrome
Keynote by Lars Bak about the all-new javascript engine that was implemented by his team in Århus for Google Chrome. This javascript engine is about 10 times faster than other javascript implementations. Lars explained how this is possible in a very dynamic language like javascript, by creating classes that can be reused; if another object with the same properties is created, which tends to happen often. Optmizations can then be applied to those classes. Furthermore, Chrome compiles the Javascript code to native code so that it can run really fast on any platform. Lars mentioned a few other major improvements, and this was a very inspiring and interesting talk - even though he had some problems with the projector in the beginning.

Failure Comes In Flavours
This talk by Mikael Nygard (who is not danish, by the way, though his name resembles a danish name pretty much) was divided into two sessions. In the first, Mikael talk about anti-patterns that lead to failure - such as depending too hard on third parties, or waiting forever for some external call. This talk featured some "war stories" about failures Mikael had helped to resolve in the past. In the second session, Mikael offered his advice on how to avoid failure and some patterns that can help in this. Though focus was very much on big enterprise SOA systems; the principles can be applied anywhere. I learned a thing or two in this session, that can be applied to my every-day work on web applications in a smaller scale.

Not your Grandfather's Architecture: Taking Architecture into the Agile World
In this talk, James Coplien talked about Agile architecture. He presented his ideas about adding roles as a concept to the object-oriented world of classes and objects. He argued that programs could be made simpler and get rid of polymorphism using his approach; I am not sure that I agree. There was no working code demo, so his ideas is still kind of abstract in my mind.

Successfully applying REST - Integration, Web-style
Stefan Tilkov talked about REST integration; a subject that I find very interesting, since we already use it in projects at work, and are planning to use it even more extensively. Stefan had some very interesting points about REST, and how it can be applied to a SOA world. I really like the clean interface you can make of a REST service, without much of the overhead and scaffolding that is neccessary in SOAP, for instance.

Top Ten Software Architecture Mistakes
This was a talk focusing on what not to do in architecture; so that we can avoid mistakes or bad decisions in our architecture. The talker, Eion Woods, had his list of 10 mistakes and how to avoid them, which was presented with a little bit of humour. At least some of the items is going to be on my list of things to check before beginning development of new projects.


JAOO Day One

Today, I've been attending the first day at the JAOO Conference. It has been an interesting day, and I am amazed by all the very talented people that speaks here at the conference, as well as by the quality of the talks. I have been attending these sessions:

Opening Keynote: Where Are Programming Languages Going, by Anders Hejlsberg
In this talk, Anders presented his take on how the programming languages will be evolving in the future. One point made, was that programming languages has not evolved much over the last 25 years - which was exemplified by a "Hello world" program in Pascal versus one in C#. The C# one was neither the shortest nor the most concise one. Anders believes that we will se more implementation of what he calls "internal domain-specific-languages", such as LINQ. Furthermore, he thinks that in the future the gap between functional and imperative programming languages will diminish, since they are already today starting to borrow the best elements from each other. Finally, he talked about concurrency and in-language concurrency constructs such as isolation, which Anders predicts also will be part of the main-stream languages in the near future.

Continuous Integration
The Continuous Integration talk was a great introduction to me into Continuous integration, since it is something, that I have little to zero experience with. We do have a build server that does nightly builds at work, but as Chris Read, the speaker, pointed out, that is not CI, though it is a step on the way toward succesful CI.

Google Chrome: The Invisible Browser
This was a talk by Ben Goodger, the Google Chrome UI tech lead, about the minimalist Chrome UI and the architecture and decisions behind it. It was interesting, though there was not much new to learn here. (Or perhaps I should know better than to attend UI talks, when UI does not really interest me. I am trying to learn ;-) )

LING and C# 3.0
This was the second talk by Anders Hejlsberg this day, and featured the new features in C# 3.0. This was info that I knew (mostly) in advance, but Anders explained both the how and the why behind the features - which was really interesting.

PowerShell
The talk about PowerShell was really good; even for me who know and use PowerShell in advance. It got beyond the covers on why the architecture and implementation works as it does, which was interesting and enlightening, and I left with a better understanding of PowerShell.

The Scala Programming Language
Scala is a language for the JVM, that I did not know much about in advance. The talk was interesting, but in "real life", I am probably never going to use it.

Why Functional Programming (still) Matters
This talk by Erik Meijer was propably the most interesting and entertaining one on Day One of JAOO. With enthusiasm, Erik explained about side-effects and why they are bad and what one should do about them (make them explicit if they cannot be avoided). He also demonstrated a few side effects, that can hit you in C# or other main stream languages with closures and lambdas, which was a pleasant reminder for me.