.net comments

Starting from Windows Vista, you should have noticed that actions which require administrative privileges and needs to elevate the current process, displays a shield icon right next to them. For example the Change date and time... button on Date and Time dialog requires admin rights to modify system date, hence displays a UAC shield right next to it:

Date and Time

If your application has any buttons or menu items like this, to conform the Windows UX Guidelines, it is a good idea to display a UAC shield icon on your controls. This CodeProject article has a good example that shows how to add shield icons to regular WinForms buttons. The gist is the following P/Invoke code:

const int BCM_FIRST = 0x1600; //Normal button
const int BCM_SETSHIELD = BCM_FIRST + 0x000C; //Elevated button

static void AddShieldToButton(Button b)
{
  b.FlatStyle = FlatStyle.System;
  SendMessage(b.Handle, BCM_SETSHIELD, 0, 0xFFFFFFFF);
}

Simply pass your Button instance reference to AddShieldToButton and you will have a nice UAC shield icon on your button on Windows Vista and above.

If you are using a third party library for your user interface controls (like DevExpress WinForms) or you need to add an icon to a menu item rather than a button, this method won't work unfortunately. There is a support ticket on DevExpress Support Center about this issue and the suggested workaround is to use the Image property of SimpleButton class. So you can save a 16px * 16px version of this shield icon in your project resources and then use it. This has a minor issue though, if you want to strictly stick to the look and feel of the operating system, you may have problem while using a single hard-coded image. The reason is, this icon on Windows Vista was a shield icon with 4 colors (red, green, blue and yellow) but since Windows 7, it has only 2 colors (blue and yellow). Who knows what it will become on Windows 9 (do not get surprised if this icon becomes a flat metro-style icon). Not a big deal but if you really want to blend in with Windows desktop, these small things matter.

UAC Shield Icons on Windows Vista

Windows stores these resources in its DLL files and it is a good idea to reuse them. This way, we will stick to what operating system has as the UAC shield icon and won't need to maintain that image resource in our project. Even WinForms has a managed API to access these kind of icons like error, warning, information, shield, etc. You can get a shield Icon instance by accessing SystemIcons.Shield property since .NET Framework 2.0 SP1. There are 2 issues with this approach:

  1. SystemIcons.Shield returns an Icon instance whereas SimpleButton.Image expects an Image instance.
  2. The icon is in 32px * 32px size but a regular button on Windows should have a small 16px * 16px icon. (On 96 DPI desktops)

To resolve these issues, I have come up with the following piece of code:

static void AddShieldToButton(SimpleButton b)
{
  var icon = Icon.FromHandle(SystemIcons.Shield.Handle);

  var iconSize = SystemInformation.SmallIconSize;
  var bitmap = new Bitmap(iconSize.Width, iconSize.Height);

  using (var g = Graphics.FromImage(bitmap))
  {
      g.InterpolationMode = InterpolationMode.HighQualityBicubic;
      g.DrawIcon(icon, new Rectangle(0, 0, iconSize.Width, iconSize.Height));
  }

  b.Image = bitmap;
}

This is what you get as a result with DevExpress controls using this method:

DevExpress UAC SimpleButton

This is ugly, huh? The issues are:

  1. Even though I am on Windows 8.1, I am getting Windows Vista's 4 color UAC shield icon. If you dig down the SystemIcons.Shield code with Reflector, you will see that the getter of this property first tries to load the system UAC shield icon using a P/Invoke code to LoadIconWithScaleDown function of comctl32.dll. This call fails, you can see that on your Visual Studio output pane reporting a first chance exception of type EntryPointNotFoundException thrown. The reason is, LoadIconWithScaleDown seems to be removed on a later version of comctl32.dll. Fortunately, the getter has a backup method which gets the icon loaded from the System.Drawing.dll embedded resources, which unfortunately is the old UAC shield icon:

    new Icon(typeof(SystemIcons), "ShieldIcon.ico");
    
  2. The resized icon looks rubbish. Even though we are using InterpolationMode.HighQualityBicubic, scaling down a 32px icon to 16px doesn't end well.

Digging down a bit more, I have finally managed to get all these issues sorted with the following piece of code:

[DllImport("user32.dll")]
static extern IntPtr LoadImage(
    IntPtr hinst, 
    string lpszName, 
    uint uType, 
    int cxDesired, 
    int cyDesired, 
    uint fuLoad);

static void AddShieldIcon(SimpleButton button)
{
  var size = SystemInformation.SmallIconSize;
  var image = LoadImage(IntPtr.Zero, "#106", 1, size.Width, size.Height, 0);

  if (image == IntPtr.Zero)
  {
    return;
  }

  using (var icon = Icon.FromHandle(image))
  {
    var bitmap = new Bitmap(size.Width, size.Height);

    using (var g = Graphics.FromImage(bitmap))
    {
      g.DrawIcon(icon, new Rectangle(0, 0, size.Width, size.Height));
    }

    button.Image = bitmap;
  }
}

And this is the result:

DevExpress UAC SimpleButton

Much better, if I may say so myself. This one uses LoadImage P/Invoke call to get the correct size of the icon, so we don't need to scale it down. Since this function returns an icon handle, we are just converting the icon to a bitmap. Using this method, you can even put UAC shield icons to your menu items:

WinForms UAC menu item

Or you can get each and every size of the UAC shield icon, just because...you can:

UAC icons

.net comments

If you ask this question on Google, you will find the following code snippet all over the web:

var text = "lorem ipsum dolor sit amet";
var bytes = Encoding.UTF8.GetBytes(text);
var stream = new MemoryStream(bytes);

This totally answers the question and works fine, but you should weigh your requirements while using this code. With short strings, that shouldn't be much problem but if you are working with larger ones, the call to GetBytes() method will allocate a huge array at least the length of your string. And worse, if this byte array is larger than 85.000 bytes, it will go into the Large Object Heap (LOH) which we should avoid as much as we can. Think also about this, if you need to pass that string to a consumer which expects a Stream, this should hint that this consumer won't need that bulk of bytes at a single point of time, rather it will read those bytes batch by batch using regular streaming interface techniques.

Stephen Toub, on one of his MSDN Magazine blog posts writes about this very issue and comes up with 3 solutions. The first two are very much like the code snippet above, only the second one is a bit refactored version of it but it has still the same semantics.

On the other hand, the third solution illustrates a quite nice approach as you can see on Figure 1 Alternate StringStream Implementation code listing. Possibly due to recent style changes on MSDN pages, the code is quite garbled but you can copy it over to Visual Studio and auto format it. This is a regular .NET Stream implementation code with the required overridden implementations. The interesting part is the Read() method which performs the real work:

public override int Read(byte[] buffer, int offset, int count)
{
  if (_position < 0) throw new InvalidOperationException();

  int bytesRead = 0;

  while (bytesRead < count)
  {
    if (_position >= _byteLength) return bytesRead;
    char c = _str[_position / 2];
    byte b = (byte)(_position % 2 == 0 ? c & 0xFF : (c >> 8) & 0xFF);
    buffer[offset + bytesRead] = b;
    Position++;
    bytesRead++;
  }

  return bytesRead;
}

This method, on each call, tries to fill the given buffer with the byte representations of the remaining string until either the buffer is full or it reaches to the end of the underlying string. Since .NET strings are UTF-16 encoded, each char is represented with 2 bytes. The while loop in this method on each iteration writes a single byte, hence writing out a single char takes 2 iterations, one for lower byte and the other for upper byte. You can see this StringStream implementation in action with a code like this:

var text = "lorem ipsum dolor sit amet";

using (var stream = new StringStream(text))
using (var reader = new StreamReader(stream, Encoding.Unicode))
{
  var read = reader.ReadToEnd();

  Assert.AreEqual(text, read);
}

Here I am providing a text to StringStream constructor, giving that stream to a StreamReader, reading to the end of the stream and what I read back is the exact same string I have provided in the first place. But notice that the second parameter of StreamReader constructor which is Encoding.Unicode, that is required in this case because StreamReader defaults to Encoding.UTF8 in the absence of an encoding parameter. We need to explicitly specify the encoding because the underlying stream implementation will spit the bytes according to Unicode (UTF-16) encoding rules.

If the consumer of your stream instance doesn't use Unicode encoding while decoding the bytes that come out of your StringStream.Read() method, it will fail to get the desired string decoded. In the previous code snippet, go either delete the second parameter of StreamReader constructor or replace it with Encoding.UTF8, you will read a string like this:

"l\0o\0r\0e\0m\0 \0i\0p\0s\0u\0m\0 \0d\0o\0l\0o\0r\0 \0s\0i\0t\0 \0a\0m\0e\0t\0"

This string has a null char for every other char, this is because UTF-8 represents the characters in English alphabet (or any character in ASCII subset for that matter) with a single byte and secondary 0x00 bytes are represented as null chars in this string. The encoding assumption of StringStream class fails the consumer of this stream. To fix this issue, the StringStream class must know the desired encoding to use when spitting out bytes. I have modified this class to accept an encoding in its constructor and produce bytes according to the specified encoding rules. Here is what Read() method became with this implementation:

public override int Read(byte[] buffer, int offset, int count)
{
  if (_position < 0)
  {
    throw new InvalidOperationException();
  }

  var bytesRead = 0;
  var chars = new char[1];

  // Loop until the buffer is full or the string has no more chars
  while (bytesRead < count && _position < _str.Length)
  {
    // Get the current char to encode
    chars[0] = _str[_position];

    // Get the required byte count for current char
    var byteCount = _encoding.GetByteCount(chars);

    // If adding current char to buffer will exceed its length, do not add it
    if (bytesRead + byteCount > count)
    {
      return bytesRead;
    }

    // Add the bytes of current char to byte buffer at next index
    _encoding.GetBytes(chars, 0, 1, buffer, offset + bytesRead);

    // Increment the string position and total bytes read so far
    Position++;
    bytesRead += byteCount;
  }

  return bytesRead;
}

The key point in this implementation is that we are first making sure there is enough room to put the byte(s) of current char to buffer, to do that we are using Encoding.GetByteCount() method. If there are no rooms left to encode current char, the method simply returns with the total bytes read count so far, leaving the rest of reading to next Read() method call. If there is room, then the method uses Encoding.GetBytes() method to write current char byte(s) to buffer at next index.

You can find the source code of this class at my GitHub repository.

.net comments

The other day I was tasked to load XML and JSON documents to a WinForms TreeView control. Nothing fancy, obviously a recursive method will do the job but I thought this should be one of those already solved problems and I can easily find a snippet on the interwebs. For XML a simple Google search lead me to the expected source code snippet and after a few refactoring here and there, I was done.

But for the JSON, the first page of Google search results failed me and I couldn't find that single method snippet, preferably using the great Newtonsoft.JSON library. So I have given it a spin and get my hands dirty, after all it is good to refresh my rusty recursive coding skills :) I hope the next guy finds the following code useful and saves him a better half/one hour time.

void LoadJsonToTreeView(TreeView treeView, string json)
{
  if (string.IsNullOrWhiteSpace(json))
  {
    return;
  }

  var @object = JObject.Parse(json);
  AddObjectNodes(@object, "JSON", treeView.Nodes);
}

void AddObjectNodes(JObject @object, string name, TreeNodeCollection parent)
{
  var node = new TreeNode(name);
  parent.Add(node);

  foreach (var property in @object.Properties())
  {
    AddTokenNodes(property.Value, property.Name, node.Nodes);
  }
}

void AddArrayNodes(JArray array, string name, TreeNodeCollection parent)
{
  var node = new TreeNode(name);
  parent.Add(node);

  for (var i = 0; i < array.Count; i++)
  {
    AddTokenNodes(array[i], string.Format("[{0}]", i), node.Nodes);
  }
}

void AddTokenNodes(JToken token, string name, TreeNodeCollection parent)
{
  if (token is JValue)
  {
    parent.Add(new TreeNode(string.Format("{0}: {1}", name, ((JValue)token).Value)));
  }
  else if (token is JArray)
  {
    AddArrayNodes((JArray)token, name, parent);
  }
  else if (token is JObject)
  {
    AddObjectNodes((JObject)token, name, parent);
  }
}

That's fine and dandy, but how about adding some unit tests, there are quite lot of code execution paths over there, right? How would you test such a piece of code? The first thing comes to my mind is to not directly code against UI components like TreeView and TreeNodeCollection, but creating a generic view model and testing that model on your unit tests. This also decouples the design from the UI framework, so that you can easily port your code to another UI framework, say WPF. But still, I couldn't think of an easy and maintainable way to write your assertions. This brings me to this great unit test helper library I have discovered recently, Approval Tests.

Simply put, Approval Tests diffs the results of your test code output with the output you have expected. The comparison can be made on either regular texts or on images if you are testing some UI code. You can watch Using ApprovalTests in .Net 16 WinForms to get the idea. Here is a simple unit test that uses Approval Tests to perform assertion:

[Test]
public void Should_load_simple_json()
{
  var treeView = new TreeView
  {
    BorderStyle = BorderStyle.None,
    Width = 400,
    Height = 400,
  };

  LoadJsonToTreeView(treeView, "{ 'foo': 'bar', 'baz': [ 42, 'quux' ] }");
  treeView.ExpandAll();

  WinFormsApprovals.Verify(treeView);
}

The test first creates a WinForms TreeView control and calls the LoadJsonToTreeView() method (System Under Test) with a simple JSON string. Then ExpandAll() method is called on TreeView instance to get all nodes visible, since we are going to take a snapshot on the last line, all nodes better be visible. When you run this unit test for the first time, the test fails and you get the screen shot of the WinForms control that is produced:

Received Image

In Approval Tests terms, this is a received image which shows the actual output of current unit test code. What you do next is to simply approve this result if that looks correct. To approve a result, you need to create the image of the expected result. Approval Tests helps you here by providing the necessary move command on your unit test failure message, something along these lines:

move /Y "Test_name.received.png" "Test_name.approved.png"

If you also prefer to use ClipboardReporter as another reporter for your unit tests, this command will automatically copied to your clipboard to be able to quickly run it, which is a great time saver.

Just run this command on your command prompt and the image you have just seen will be renamed and from now on, it will work as the expected result for this unit test. If you change the code and break the unit test, a nice side-by-side comparison view of the actual and expected images will show on a TortoiseDiff window. TortoiseDiff seems to be a hard dependency of Approval Tests and I am not sure how it is discovered on your system or any chance to change it to another diff viewer for that matter.

I have created a sample project and unit tests project on GitHub, send me a pull request if I am missing anything :)

PS: I am curious whether Approval Tests handle the different control styles across different operating systems, i.e. you create your approved images on a Windows 8 box but if your build server runs your tests on a Windows Server with classic Windows theme, you will end up having different images. Please let me know if you have any idea about this in comments.

javascript comments

Suppose you have the following form on your HTML page:

<form id="MyForm" action="process.aspx" method="POST">
  <input type="text" name="foo" />
  <input type="submit" name="submit" value="Send" />
</form>

Seems pretty innocent right? No. At least until you try to submit that form using JavaScript code. Try running the following JavaScript code on a page that contains this form inside developer tools console of your favorite browser:

document.getElementById('MyForm').submit()

You will get a lovely error, on Chrome:

TypeError: Property 'submit' of object #<HTMLFormElement> is not a function

On Internet Explorer:

Member not found.

But how come? Is submit() broken? Chrome's error message hints that a property named submit exists but not a function. Let's see what it is:

document.getElementById('MyForm').submit

This call will return a reference to submit button element in the form. Apparently you can access child form input elements as properties of parent form element, neat! But seriously, I need to call the submit() method. To do that I need to have a reference to the overridden function. If I had a reference to that function I know I can call it with the form reference I have in hand, thanks to call() method exists on all JavaScript functions. Using the call() method I can execute the submit() function with any instance I want. OK then, how about using another form reference's non-overridden submit() method, let's try this:

document.createElement('form').submit(document.getElementById('MyForm'))

Bingo! It worked. But it doesn't feel quite right, especially creating another form element to solely access one of its methods? There should be a better way. A little research took me to this: HTMLFormElement which represents the base of all form elements and has references to all form functions accessible through its prototype, great! Let's give the following revised code a chance:

HTMLFormElement.prototype.submit.call(document.getElementById('MyForm'))

This worked and is a reasonable solution for this problem.

firefox comments

Semantic (anlamsal) webin önemli unsurlarından biri de web sayfalarının URL’lerinin (URI mi deseydik acaba?) kısa, öz ve kullanıcı tarafından da anlaşılabilir olmasıdır. Bilgisayarlar açısından bir sorun yok, onlar kurallara uygun olduğu sürece bize doğru sayfayı gösterir ama bu adreslerin kullanıcılar tarafından da anlaşılabilir olması, sadece bir sitenin domain kısmının değil alt sayfalarının da akılda tutularak adres çubuğuna elle girilebilir olması hoş olmaz mı? Son zamanlarda biraz da Web 2.0 furyasının sayesinde web sitesi geliştiricileri sitelerinin URL yapısına dikkat etmeye başladı. Böylelikle URL’ler kısaldı, bir kaç kırılımdan oluşan bir şekil aldı ve en önemlisi sadece bilgisayarların anlam vereceği abidik gubidik karakter silsileleri olmaktan çıktı. Bununla beraber kendimden örnek vermem gerekirse bir sitede bir yerden başka yere geçerken sayfada gideceğim yeni sayfaya uygun link bulmaya çalışmaktansa, gider elle adres çubuğuna o alt sayfanın adresini girer oldum. Sanki bilgisayarımın sabit diskinde dolaşırmış gibi. Veya bulunduğum sayfa hiyerarşisine göre bir üst seviyeye geçmek istediğimde adres çubuğunda şu an bulunan adresin son segmentini silerek bu sayfaya gitmeye çalışır oldum, ve genelde de gidebildim. Hani nasıl derler, URL hackerı oldum çıktım :)

Eğer siz de kendinize bu şekilde URL’ler ile haşır neşir buluyorsanız ve Firefox web tarayıcısını kullanıyorsanız size süper bir eklenti tavsiye etmek istiyorum: Locationbar². Bu eklenti yardımı ile adres çubuğunuzda bulunan URL segmentlerini tıklanabilir linkler haline getirebilir ve bu segmentlerin görünümün daha anlaşılır bir hale sokabilirsiniz. Benim eklenti ayarlarım şu şekilde:

Bu ayarlar ile fare imlecinizi adres çubuğunun alt kısmına yaklaştırdığınızda adres link şeklini alıyor ve o segmente kadar olan URL’ye tıklamanız suretiyle gidebiliyorsunuz. Başta biraz kullanım zorluğu çekebilirsiniz ancak sonraları alışkanlık yapıyor ve kullandığınız her tarayıcıda arar oluyorsunuz.