01 March 2016

.NET - Creating an async-capable background task

In the old days we used BackgroundWorkers, but these days we want to create tasks we can run with the async keyword. Here is an example for a task that will return a boolean:
public async Task Test()
{
    bool result = false;
    Exception error = null;

    await Task.Run(() =>
    {
        try
        {
            result = someSlowComponent.getBooleanResult();
        }
        catch (Exception ex)
        {
            error = ex;
        }
    });

    if (error != null)
        throw error;
    else
        return result;
}
You can now await this method and make it asynchronous:
public async bool GetValue()
{
    bool result = await Test();

    //Do more things with the result.

    return result;
}

28 December 2015

C++ - Write a number to a file.

For debugging a C++ DLL, I needed a way to write the value of a numeric variable to a file. This is how:

Includes needed

#include <sstream>
#include <fstream>

Convert the number

You can convert the number to a string using a stringstream.
std::stringstream convert;
convert << 305.24;

Output to a file

The result of the following is a text file at the DLL's location containing the number.
std::ofstream out("Output.txt");
out << "Value: ";
out << convert.str();
out.close();

27 August 2015

JS - Convert a (nested) JSON object to HTML

For testing purposes I wanted to display the JSON retrieved from an API in a HTML page. I used Fiddler for that, but after some security was included that became impossible. The following Javascript function converts the JSON to a ordered list tree:
function jsonToHtml(data) {
    var result = "<ol>";

    for (var key in data) {
        if (typeof (data[key]) == 'object' && data[key] != null) {
            result += "<li><span class='key'>" + key + "</span>:<ul>";
            result += jsonToHtml(data[key]);
            result += '</ul></li>';
        }
        else {
            result += "<li><span class='key'>" + key + '</span>: ';
            result += '<span class="string">' + data[key] + '</span></li>';
        }
    };

    result += '</ol>';
    return (result);
}

05 August 2015

.NET - What is a GUID?

I found out something interesting today. I always thought a GUID was a string, but as it turns out, it's 128 bits of binary data that is represented in hexadecimal numbers, making it appear like a string. That makes the question of whether a GUID is case-insensitive irrelevant. It would also be better to store GUID's in a binary field rather than a text field.

21 July 2015

Windows Store App - Saving data on suspending

In my app I have a method WriteBinaryDataFile, that is called when the app is suspended. First it writes Started writing to the output window, then does it's work, and finishes by outputting Finished writing. Interestingly, Started writing appeared, but Finished writing didn't, exept when I terminated the app manually. It turned out that the method needs to be async, and had to be awaited. The code is quite simple:
public async Task WriteBinaryDataFile()
{
    //Do what needs to be done.
}

private async void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    await MainPage.WriteBinaryDataFile(); //Await and in the middle.
    deferral.Complete();
}

22 April 2015

.NET - Using a font file in a custom control

For my text editor project Filepad I came up with the idea to use a custom control that would use an icon font, like we often do these days in web projects. The obvious font choice is of course FontAwesome. I found initial assistance at this project, and some at MSDN. It's actually pretty easy. Include the font file in the project and set it to copy to the output directory. The following is the relevant parts of the code of my control to make the font work. I provide the code point of the icon I want through a property that is then converted to a string. The code points for FontAwesome are listed here.
private int mIconInt = 0;
private string mIconString = string.Empty;

[Category("Appearance")]
public int Icon {
  get {
    return mIconInt;
  }
  set {
    if (value != mIconInt) {
      mIconInt = value; //In FontAwesome, the code point "0xf0c7" is the "save" icon.
      mIconString = char.ConvertFromUtf32(value);
    }
  }
}

[Category("Appearance")]
public float IconSize { get; set; } //Unit = em

private static PrivateFontCollection Fonts { get; set; } //This object must live as long as it's fonts are in use.
private static Font IconFont { get; set; } //Shared among all font icon buttons.

private Font GetFont() {
  if (IconFont == null) {
    Fonts = new PrivateFontCollection();
    if (File.Exists("FontIconAwesome.ttf")) {
      Fonts.AddFontFile("FontIconAwesome.ttf");
    }

    if (Fonts.Families.Length > 0) {
      IconFont = new Font(Fonts.Families[0], IconSize > 0f ? IconSize : this.Font.Size);
    }
  }

  return IconFont;
}

protected override void OnPaint(PaintEventArgs e) {
  Font font = GetFont(); //Needs to be done before any painting goes on.
  if (font == null) {
    font = this.Font;
  }

  base.OnPaint(e);

  string text = IconFont != null && mIconInt > 0 ? mIconString : this.Text;
  Rectangle textArea = new Rectangle(1, 1, this.Width, this.Height);
  Brush textColor = ...;
  e.Graphics.DrawString(text, font, textColor, textArea);
}

18 April 2015

.net - Keyboard input in custom controls

I'm working on a custom control in .net WinForms that allows the user to input characters when it is focused. So far so good, but there's also a button on the form that has a hotkey assigned. It's label is New &chapter, so whenever I press "ALT+C", it's OnClick event fires. However, I noticed that it also fires when I just press "C", and that of course conflicts with my custom control, which doesn't even receive the keystroke for "C" anymore. I also noticed this doesn't happen when I'm typing in a regular text box. After a lengthy search I found this hotkey behavour is by design, so I needed to find a workaround for my control. After some more searching I finally found this event that does te trick:
protected override bool IsInputChar(char charCode) {
  if (this.Focused) {
    return true;
  }
  else {
    return base.IsInputChar(charCode);
  }
}
I put this in my custom control, and all works well. "ALT+C" still works on the button, but "C" goes to my custom control.