Category: Code Snippets

16 Apr

A little better MeasureString…

System.Drawing.MeasureString is a shit.

You are better work it out with API calls and so on, but if you are on Mono that is out of choice.

Apart from the known problems (not working correctly without Antialiasing enabled, requiring specific StringFormats), it also skips trailing spaces.

At least this should fix that issue up:

int CountTrailingSpaces(string str)
{
    int spaces = 0;

    int i = 0;
    for (i = 0; i < str.Length; i++)
    {
        if (str[i] == ' ') ++spaces;
        else break;
    }

    for (int j = str.Length - 1; j > i; j--)
    {
        if (str[j] == ' ') ++spaces;
        else break;
    }
    return spaces;
}

SizeF MeasureString(Graphics gfx, string str, Font font)
{
    // these are the times you hate MS..
    SizeF size = gfx.MeasureString(str, font,
          new PointF(0.0f, 0.0f),
          StringFormat.GenericTypographic);

    if ((str.EndsWith(" ")||(str.StartsWith(" "))))
    {
        SizeF spacesize = gfx.MeasureString("! !", font,
              new PointF(0.0f, 0.0f),
              StringFormat.GenericTypographic);
        SizeF spacesizemin = gfx.MeasureString("!!", font,
              new PointF(0.0f, 0.0f),
              StringFormat.GenericTypographic);

        float spacewidth = spacesize.Width - spacesizemin.Width;

        int spaces = CountTrailingSpaces(str);

        size.Width += (spacewidth*(float)spaces);
    }

    return size;
}


:|

Filed under: .NET, Code Snippets, Programming

12 Feb

Ajax problem on Firefox

Just a quick problem report with solution.

If you get :

Error: [Exception… “Component returned failure code: 0×80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]” nsresult: “0×80040111 (NS_ERROR_NOT_AVAILABLE)” location: “JS frame :: http://www.********.*** :: **** :: line **” data: no]

Check if you did a “xhr.send(null);” and convert to “xhr.send(”);”.

Don’t ask me why, it worked for me. Take it as a cargo culting solution (not that with browsers you can actually aim for well motivated, rational solutions anyway) but it works.

Filed under: Code Snippets, Programming

23 Oct

Helper application for COM interop in .NET

A common usage of COM interop in .NET is using Active Scripting (or the Microsoft Script Control) to add scripting to an application. While this seems odd (.NET has powerful scripting capabilities, why not use them?), it’s infact frequently used for its simplicity.

There are a couple of problems, however. The classes must be declared COM visible (or the entire assembly if you prefer) AND overloaded methods and statics are not accessible.

Here is a small C# app (source) which lists all public overloaded and static methods and properties which are in public classes of the assemblies passed in the command line.

Check the source here.