RSS

Two little “endians”…and then there were none (of big)

1940 cover of the bookIf you don’t have problems, it means that you are doing nothing new. In my job, I do have problems almost everyday, and that’s making me happy!
If you deal with low-level data transfer, then you probably faced the different “endianness” of the processors. Traditionally, companies like Intel embraced the Little-endian choice, whereas Motorola (now Freescale) joined the Big-endian way.
Now, it seems that the .Net Framework cares only the Little-endian vision of the world. Here is an excerpt of the BitConverter class as seen with any decent disassembler:

	public static class BitConverter
	{
		/// <summary>Indicates the byte order ("endianness") in which data is stored in this computer architecture.</summary>
		/// <filterpriority>1</filterpriority>
		[__DynamicallyInvokable]
		public static readonly bool IsLittleEndian = true;

                // ...

Anyway, when you have to write a C#/.Net program which has to exchange data with a Big-endian device, you’re in trouble because the very poor support of this format. So, I created a pretty decent reader/writer pair that should come useful for many of you.

The “BIDI”-way.

Many modern processors supports both the “endiannesses”, so…why a BinaryReader/BinaryWriter shouldn’t act as them? Furthermore, it’s not unusual to see a mixed-format data in the same stream. One of the latest occasions was just on the FT800 chip, which requires a mixture of Big-endian for the addressing, despite the specs state that the chip is Little-endian based.
So, I definitely wanted a Reader/Writer capable of both. However, the interface is meant as “explicit” reference to a type yet the format. There’s no any “default” format, and this context might be interesting as well. The classes have been based by the original Microsoft’s BinaryReader and BinaryWriter, then I modified the data access. The pair of new classes are named as BidiBinaryReader and BidiBinaryWriter.
If any of you browsed the sources of my Modbus library, then the problem isn’t new at all. This time I turned the source to “wrap” a generic Stream object, instead a faster but less-abstract byte array. Here is an example of how the BidiBinaryReader:


        /// <summary>Reads a 4-byte signed integer (Little-endian) from the current stream and advances the current position of the stream by four bytes.</summary>
        /// <returns>A 4-byte signed integer read from the current stream.</returns>
        /// <exception cref="T:System.IO.EndOfStreamException">The end of the stream is reached. </exception>
        /// <exception cref="T:System.ObjectDisposedException">The stream is closed. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <filterpriority>2</filterpriority>
        public virtual int ReadInt32LE()
        {
            this.FillBuffer(4);
            return
                (int)this.m_buffer[0] |
                (int)this.m_buffer[1] << 8 |
                (int)this.m_buffer[2] << 16 |
                (int)this.m_buffer[3] << 24;
        }


        /// <summary>Reads a 4-byte signed integer (Big-endian) from the current stream and advances the current position of the stream by four bytes.</summary>
        /// <returns>A 4-byte signed integer read from the current stream.</returns>
        /// <exception cref="T:System.IO.EndOfStreamException">The end of the stream is reached. </exception>
        /// <exception cref="T:System.ObjectDisposedException">The stream is closed. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <filterpriority>2</filterpriority>
        public virtual int ReadInt32BE()
        {
            this.FillBuffer(4);
            return
                (int)this.m_buffer[3] |
                (int)this.m_buffer[2] << 8 |
                (int)this.m_buffer[1] << 16 |
                (int)this.m_buffer[0] << 24;
        }

What the classes don’t expose.

The original Microsoft’s sources also offer the support for reading and writing chars, thus the codec-way to manipulate bytes. The problem is that those sources access to several internal stuffs, so the only way to leverage them is via reflection. I usually work with plain byte-arrays, and the text conversion is made by some specific codec (e.g. UTF8Encoding).
As stated, there’s no a support for setting a “default” endinanness of the Reader/Writer. I mean using the same original’s interface, but allowing the user to set whether adopt the Big- instead of the Little-endian format.

So far so well. As usual here are the sources.

 
Leave a comment

Posted by on March 27, 2014 in .Net, Software

 

Tags: , , , ,

Micro-JSON for Netduino (and PC)

JSON logoThis is a pretty useful tool for the Netduino, which I need for playing around some Micro-WPF demo on the Eve board.
As soon you want to deal with web-services, JSON is a must-have format for serializing data. Although Netduino does not use Javascript, the JSON format is very compact, at least when compared to XML. By the way, XML is richer as structure and schema, and JSON is sometimes blurry about the data format (e.g. date and time).
The small software library comes with both a parser and a serializer. The parser rules strictly rely on the specification as in the official JSON portal.
The parser deserializes a JSON string to a DOM of specific objects. I’ve been deeply inspired by the JLinq of the awesome library JSON.Net by James Newton-King.

The problem.

Create a JSON parser isn’t a really complex task, unless you have to work on very-low resources devices. In that case, everything should be optimized at best.
My first attempt to create a decent parser and serializer was successful, but the result was not what I’d expected. Although the code runs surprisingly fast on a normal PC, on the Netduino Plus 2 runs pretty slow and takes a lot (i.e. too much) RAM. That leaded me to adjust and optimized several parts of the code, at least to solve the memory occupation issue. The second release is pretty better.

How it works.

The approach is functional-like, although it’s normal C# highly optimized for low-resources platform. However, the same code works on any .Net platform without any problem.
As stated, the first attempt wasn’t the best one. I used several resource-heavy components, which de-facto prohibits the usage on the Netduino. So, it turned to a different yet trivial solution using as less resources as possible. Not sure that’s the very best achievement possible, though.

For instance, here is the piece of code to parse a JSON string, as used in the first release:

        private static JsonParserContext ConsumeString(
            this JsonParserContext ctx,
            bool throws
            )
        {
            var src = ctx.Source;
            JsonParserContext rtn;
            if ((rtn = ctx.ConsumeWhiteSpace().ConsumeAnyChar("\"", throws)).IsSucceeded)
            {
                var sb = new StringBuilder();

                for (int p = src.Position, len = src.Text.Length; p < len; p++)
                {
                    char c;
                    if ((c = src.Text[p]) == '"')
                    {
                        src.Position = p + 1;
                        break;
                    }
                    else
                    {
                        sb.Append(c);
                    }
                }

                rtn.SetResult(
                    new JValue { BoxedValue = sb.ToString() }
                    );
            }

            return rtn;
        }

Below is how it is the new improved version. Notice that there’s no more the StringBuilder object, and it avoids the creation of new JsonParserContext instances on every call.

        private static JsonParserContext ConsumeString(
            this JsonParserContext ctx,
            bool throws
            )
        {
            if (ctx.ConsumeWhiteSpace().ConsumeAnyChar("\"", throws).IsSucceeded)
            {
                JSonReader src = ctx.Begin();

                for (int p = src.Position, len = src.Text.Length; p < len; p++)
                {
                    if ((src.Text[p]) == '"')
                    {
                        ctx.SetResult(
                            new JValue { BoxedValue = src.Text.Substring(src.Position, p - src.Position) }
                            );

                        src.Position = p + 1;
                        break;
                    }
                }
            }

            return ctx;
        }

Another great improvement (in terms of resource savings) is about the way to store the key-value pairs in a JSON object.
The first attempt uses the Hashtable object, which comes with any .Net platform, and it’s tailored for such purpose. However, its O(1)-access ability comes with a price in terms of resources, and it’s too high to afford for a Netduino.
The more-trivial solution of a simple array requires much less resources, but the data access now takes O(N).

Performance.

I performed the test with several JSON strings. The longest is about 9kiB, while the shortest is roughly 500 bytes.
Using the first release, the longest string is almost impossible to parse: the parser runs out of RAM very quickly.

Here are some results.
In the following picture there is the complete JSON “roundtrip” (parsing+serializing) of the shortest string (about 500 bytes), using the FIRST release.
The upper plot shows the parsing duration (high level) and takes about 170ms to complete. The serialization of the resulting object is way faster and requires a little more than 20ms (lower plot).

UNIT0000

Hereinafter, the charts are all related to the SECOND library release.
Here is the same 500 bytes-string parsed then serialized. Despite on the PC the revision takes a little longer to perform, on the Netduino is a little faster instead. I suppose all the benefits derive from the less RAM usage.

UNIT0001

Here is a 2kiB-JSON parsed, which takes almost 1.2 seconds to perform. The serialzation is not shown here.

UNIT0003

Finally, the “huge” 9kiB-JSON taking looooong to parse: almost 25 seconds!!!. There’s no serialization in this chart, because after a while the Netduino runs out of RAM. I believe there’s something to trim yet…

UNIT0002

The J-DOM.

I don’t know how to call it. The reference JSON.Net library where I inspired from offers a complete DOM support together with Linq, but that’s not possible in a tiny context as the Micro Framework is. By the way, the DOM I defined is JSON-specific: is the result of the serialization, and allows to manipulate the resulting object with ease. Once the DOM is complete, you can serialize it to have back a JSON string.
As stated, a must-have tool for any web-related application.

The usage is very simple and it’s the same as the JSON.Net’s JLinq (except for the Linq!).
Given this sample JSON string (as from Wikipedia):

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}

Here is some example of manipulation from within your C# code:

            var jdom = (JObject)JsonHelpers.Parse(s);

            Console.WriteLine((int)jdom["age"]);    //displays 25

            //add a new phone entry
            var jentry = new JObject();
            jentry["type"] = "mobile";
            jentry["number"] = "+39-123-456-7890";

            var jphones = (JArray)jdom["phoneNumbers"];
            jphones.Add(jentry);

            string jtxt = JsonHelpers.Serialize(jdom);
            Console.WriteLine(jtxt);

Okay, take me to the source code…

Here is the link with two complete Visual Studio solutions: both regular .Net and Netduino MF. The source contains also the first release of the parser, although it is not used.

 
1 Comment

Posted by on March 6, 2014 in .Net, Software

 

Tags: , , ,

Netduino + FT800 Eve = MicroWPF

The spare time is few, but step by step the target is getting closer.
It’s a been I’ve started playing around the FTDI FT800 Eve board, and it must admit it is awesome. If you need a quick solution to add a small touch display to your *duino board, the Eve is something you should consider.

EVE image

You know, I love Netduino and C#. That’s because I chose to play with the display using Netduino (Plus 2), and honestly I’d expected a pretty bad performance. Instead, the graphic engine of the Eve can be easily driven via SPI from any board. That is, the SPI on Netduino is fast, very fast.

My goal is creating a small library for helping many users to create small and funny home/hobby projects with the Netduino and the Eve display boards. Since I love the classic WPF, how could I avoid to inspire from them?

Micro WPF

If you know WPF, many concepts would come easier. Otherwise, I recommend to take a look to the documentation, tutorials and whatever you want. Even if you don’t harm with a PC, rather with the Windows Store/Phone APIs, the approach here isn’t too far from.
The “WPF” term for a simple Netduino is clearly abused. Here is just the visual approach, the XAML-like approach to create the UI, and -yes- the same ability to create your own controls: MeasureOverride and ArrangeOverride.
That’s not all.
If you have any visual application in mind with Netduino+Eve (e.g. a climate control, IoT client, etc), then probably you’d need some kind of navigation service across several pages. That’s the most modern UI experience, on every device: PC, tablets, and phones.

I still don’t write what the library will offer, because it’s just something made for fun: for helping hobbists and even students working with a UI on a such small board as Netduino is.
For sure, there are NOT (nor in the future):

  • data binding
  • XAML parsing (the tree has to be created programmatically)
  • styling
  • the remaining 99.99% of regular WPF…

An example of layout

The most versatile yet complex layout control is the Grid, but it seems working fine.
Let’s take this sample XAML:

<Page x:Class="WpfApplication2.Page1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
	Title="Page1">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="150" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="2*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <StackPanel
            Grid.Row="0"
            Grid.Column="0"
            x:Name="R0C0"
            Background="Blue"
            />

        <StackPanel
            Grid.Row="0"
            Grid.Column="1"
            x:Name="R0C1"
            Background="DarkGreen"
            />

        <StackPanel
            Grid.Row="0"
            Grid.Column="2"
            x:Name="R0C2"
            Background="Red"
            >
            <Button
                Content="Caption"
                Width="120"
                Height="30"
                Margin="10,5"
                HorizontalAlignment="Center"
                x:Name="B0"
                />
        </StackPanel>


        <StackPanel
            Grid.Row="1"
            Grid.Column="0"
            Grid.ColumnSpan="2"
            x:Name="R1C0"
            Background="LightPink"
            />


        <StackPanel
            Grid.Row="2"
            Grid.Column="1"
            Grid.ColumnSpan="2"
            x:Name="R2C1"
            Background="MediumSlateBlue"
            >
            <Button
                Content="Caption"
                Width="120"
                Height="30"
                Margin="10,5"
                HorizontalAlignment="Center"
                x:Name="B2"
                />
        </StackPanel>

    </Grid>
</Page>

On the regular WPF the result is the following:

sample-wpf

Now, let’s see how to write the same thing on Netduino:

    public class DemoPage2 : PageBase
    {
        protected override void OnCreate(FT800Device dc)
        {
            var btn_prev = new WidgetButton() { Margin = new Thickness(10, 5), Text = "Prev" };
            btn_prev.Click += new EventHandler(btn_prev_Click);

            var btn_next = new WidgetButton() { Margin = new Thickness(10, 5), Text = "Next" };
            btn_next.Click += new EventHandler(btn_next_Click);
            btn_next.HAlign = HorizontalAlignment.Center;

            var grid = new WidgetGridContainer();
            grid.Name = "GRID";

            grid.AddColumnDefinition(150);
            grid.AddColumnDefinition(1, GridUnitType.Star);
            grid.AddColumnDefinition(1, GridUnitType.Auto);

            grid.AddRowDefinition(1, GridUnitType.Star);
            grid.AddRowDefinition(2, GridUnitType.Star);
            grid.AddRowDefinition(1, GridUnitType.Auto);

            {
                var ctr = new WidgetStackContainer();
                ctr.Name = "R0C0";
                ctr.Background = Colors.Blue;
                grid.SetRowCol(ctr, 0, 0);
                grid.Children.Add(ctr);

                ctr.Children.Add(btn_prev);
            }
            {
                var ctr = new WidgetStackContainer();
                ctr.Name = "R0C1";
                ctr.Background = Colors.DarkGreen;
                grid.SetRowCol(ctr, 0, 1);
                grid.Children.Add(ctr);
            }
            {
                var ctr = new WidgetStackContainer();
                ctr.Name = "R0C2";
                ctr.Background = Colors.Red;
                grid.SetRowCol(ctr, 0, 2);
                grid.Children.Add(ctr);

                ctr.Children.Add(
                    new WidgetButton() { Name = "B0", Margin = new Thickness(10, 5) }
                    );
            }
            {
                var ctr = new WidgetStackContainer();
                ctr.Name = "R1C0";
                ctr.Background = Colors.LightPink;
                grid.SetRowCol(ctr, 1, 0, 1, 2);
                grid.Children.Add(ctr);
            }
            {
                var ctr = new WidgetStackContainer();
                ctr.Name = "R2C1";
                ctr.Background = Colors.MediumSlateBlue;
                grid.SetRowCol(ctr, 2, 1, 1, 2);
                grid.Children.Add(ctr);

                ctr.Children.Add(btn_next);
            }

            this.Content = grid;
        }

        void btn_prev_Click(object sender, EventArgs e)
        {
            NavigationService.Instance.GoBack();
        }

        void btn_next_Click(object sender, EventArgs e)
        {
            NavigationService.Instance.Navigate(new DemoPage3());
        }
    }

That leads the following snapshot:

My Snapshot5

NOTE: by live the display shows the colors correctly. However, the picture taken renders a bad result.

Widgets, widgets, widgets…

The Eve board is very well designed, because it’s plenty of useful widgets. I don’t believe you’d need something different from the provided.
At the moment of writing, the Netduino library supports:

  • (normal) Button
  • ToggleButton
  • TextBlock
  • Slider
  • Dial

and, as for the layout control:

  • StackPanel
  • Grid

As long the spare time helps me, I will try to add some other useful component as the TextBox and the Image.

Yet some screens generated by the Netduino and the FT800 Eve board.
WP_000595

My Snapshot4

My Snapshot3

My Snapshot7

Source code

I will release a beta release soon.

 
2 Comments

Posted by on February 16, 2014 in .Net, Electronics, Software

 

Tags: , , , , , , , , , , ,

Which is better?

Just a quick post on how to write “better” a small piece of code.
First off, “better” is ambiguous: it should mean “elegant”, or “readable”? Maybe “performing” or even “compact”? In general, I tend to favor the readability, for a better maintenance; whereas possible a good performance as well.
Secondly, although this case is against the .Net Micro Framework (where the resources are very poor), the considerations may be applied for any platform. Here the discussion is focused just on the IL: not more in depth.
Last but lot least, the language is C#. Plain and safe C#: pointer tricks are not allowed at all.

The problem.

The problem depicted here is just an example. The goal is to store an Int16 value (16-bits wide signed integer) onto a byte-array, at a certain offset, using the Little-Endian format. It’s clear that it could be used any kind of integer, and also a different format.
As for example, given:

  • N = 12345 (0×3039 in Hex), as the value to store;
  • K = 23 (0×17 in Hex), as the starting offset of the array

The aim is storing N in the array as follows:

K K+1
Offset: 21 22 23 24 25 20
Content: x x 0×39 0×30 x x

Many ways to do it: which is better?

I found four different ways to solve the problem, but new versions are welcome.

The first is perhaps the most intuitive. I think there’s nothing to explain.

        private static void Test1(short value)
        {
            _buffer[_ptr++] = (byte)value;
            _buffer[_ptr++] = (byte)(value >> 8);
        }

The second way is a revised version of the first one, just because the post-increment is typically less compact yet performing than the pre-increment.

        private static void Test2(short value)
        {
            _buffer[_ptr] = (byte)value;
            _buffer[++_ptr] = (byte)(value >> 8);
            ++_ptr;
        }

The third way looks as the dumbest one: instead updating the offset on every step, just calculate the actual cell index. At the end, the global offset is updated once only.

        private static void Test3(short value)
        {
            _buffer[_ptr] = (byte)value;
            _buffer[_ptr + 1] = (byte)(value >> 8);
            _ptr += 2;
        }

The fourth looks as a file corruption, because it seems having no sense. Hard to read, hard to understand what the program does, and even if what id does, does it correctly. Always reliable?…hum…
However, there’s an explanation for this code further.

        private static void Test4(short value)
        {
            _buffer[_ptr] = (byte)(value + 0 * (_buffer[(_ptr += 2) - 1] = (byte)(value >> 8)));
        }

The results.

The comparison of the four snippets is relative to the speed of execution, but also on the compactness.
The execution template looks as follows:

            const int num = 10000000;
            const short k = 12345;
            Stopwatch sw;

            sw = Stopwatch.StartNew();
            for (int i = 0; i < num; i++)
            {
                _ptr = 0;
                Test1(k);
                Test1(k);
                Test1(k);
                Test1(k);
                Test1(k);
                Test1(k);
                Test1(k);
                Test1(k);
                Test1(k);
                Test1(k);
            }

            sw.Stop();
            Console.WriteLine("Test1=" + sw.ElapsedMilliseconds);

Here are the IL dump of the various snippets:

        private static void Test1(short value)
        {
            _buffer[_ptr++] = (byte)value;
            _buffer[_ptr++] = (byte)(value >> 8);
        }
	IL_0000: ldsfld uint8[] ConsoleApplication1.Program::_buffer
	IL_0005: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_000a: dup
	IL_000b: ldc.i4.1
	IL_000c: add
	IL_000d: stsfld int32 ConsoleApplication1.Program::_ptr
	IL_0012: ldarg.0
	IL_0013: conv.u1
	IL_0014: stelem.i1
	IL_0015: ldsfld uint8[] ConsoleApplication1.Program::_buffer
	IL_001a: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_001f: dup
	IL_0020: ldc.i4.1
	IL_0021: add
	IL_0022: stsfld int32 ConsoleApplication1.Program::_ptr
	IL_0027: ldarg.0
	IL_0028: ldc.i4.8
	IL_0029: shr
	IL_002a: conv.u1
	IL_002b: stelem.i1
	IL_002c: ret

        private static void Test2(short value)
        {
            _buffer[_ptr] = (byte)value;
            _buffer[++_ptr] = (byte)(value >> 8);
            ++_ptr;
        }
	IL_0000: ldsfld uint8[] ConsoleApplication1.Program::_buffer
	IL_0005: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_000a: ldarg.0
	IL_000b: conv.u1
	IL_000c: stelem.i1
	IL_000d: ldsfld uint8[] ConsoleApplication1.Program::_buffer
	IL_0012: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_0017: ldc.i4.1
	IL_0018: add
	IL_0019: dup
	IL_001a: stsfld int32 ConsoleApplication1.Program::_ptr
	IL_001f: ldarg.0
	IL_0020: ldc.i4.8
	IL_0021: shr
	IL_0022: conv.u1
	IL_0023: stelem.i1
	IL_0024: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_0029: ldc.i4.1
	IL_002a: add
	IL_002b: stsfld int32 ConsoleApplication1.Program::_ptr
	IL_0030: ret

        private static void Test3(short value)
        {
            _buffer[_ptr] = (byte)value;
            _buffer[_ptr + 1] = (byte)(value >> 8);
            _ptr += 2;
        }
	IL_0000: ldsfld uint8[] ConsoleApplication1.Program::_buffer
	IL_0005: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_000a: ldarg.0
	IL_000b: conv.u1
	IL_000c: stelem.i1
	IL_000d: ldsfld uint8[] ConsoleApplication1.Program::_buffer
	IL_0012: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_0017: ldc.i4.1
	IL_0018: add
	IL_0019: ldarg.0
	IL_001a: ldc.i4.8
	IL_001b: shr
	IL_001c: conv.u1
	IL_001d: stelem.i1
	IL_001e: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_0023: ldc.i4.2
	IL_0024: add
	IL_0025: stsfld int32 ConsoleApplication1.Program::_ptr
	IL_002a: ret

        private static void Test4(short value)
        {
            _buffer[_ptr] = (byte)(value + 0 * (_buffer[(_ptr += 2) - 1] = (byte)(value >> 8)));
        }
	IL_0000: ldsfld uint8[] ConsoleApplication1.Program::_buffer
	IL_0005: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_000a: ldarg.0
	IL_000b: ldsfld uint8[] ConsoleApplication1.Program::_buffer
	IL_0010: ldsfld int32 ConsoleApplication1.Program::_ptr
	IL_0015: ldc.i4.2
	IL_0016: add
	IL_0017: dup
	IL_0018: stsfld int32 ConsoleApplication1.Program::_ptr
	IL_001d: ldc.i4.1
	IL_001e: sub
	IL_001f: ldarg.0
	IL_0020: ldc.i4.8
	IL_0021: shr
	IL_0022: conv.u1
	IL_0023: stelem.i1
	IL_0024: conv.u1
	IL_0025: stelem.i1
	IL_0026: ret

The real surprise is on the speed results (milliseconds):

Test1=1034
Test2=848
Test3=712
Test4=801

It is worthwhile to notice that:

  • the pre-increment yields a little bonus in performance, despite the less-readable code. Also notice there are five “_ptr” accesses vs four in the first snippet, but that seems running faster anyway.
  • Surprisingly, the “dumbest” way to write the code is also the best one: not just on the speed, but compactness and readability as well.
  • The fourth snippet was just a test on how to “force” a certain IL generation, and -yes- it is very compact. Despite this effort, the speed result isn’t gratifying at all. That’s the loser solution for sure.
  • The interesting thing in the firth snippet is the fake multiplication (by zero), which aims to “compress” the two assignments in a single row. I’m pleased to see how smart is the compiler: it discard the useless multiplication, but not its terms.

Conclusions.

Just a short lesson on how to writer the code better.
Most of the times, you don’t have to bump your head against the wall to find the best solution as it were in native languages like C/C++. That’s why I love C#!

 
Leave a comment

Posted by on January 19, 2014 in .Net, Software

 

Tags: , ,

WPF editable ComboBox and its weird bug

This is a double-purpose post: a simple hack around the WPF ComboBox, and a subtle bug in it.
The short video explains both the problems way better than my words could do.

Most of the times, I use the ComboBox as a simple drop-down list. That works perfectly and that’s why I never bumped against the problems around.
This time I needed a real ComboBox, that is the ability to select from a drop-down list as always, but with the editable box as well. More precisely, I wanted the following behaviors:

  1. the user can drop the list and select any item (that’s the usual feature)
  2. the user can type in an existent item or a new one
  3. as the user type in the selection box, the drop-down should open
  4. (future) the drop-down list should be filtered upon the actual text typed in the selection box

The first two points are already available in the standard ComboBox control, while the fourth is just a wish for the (near) future. The problems arose with the third point, because the simplest yet intuitive way I used yielded a nice exception!

The base for the test.

Nothing fancy here: just a collection of objects, very simple. The classic “Person” with an “ID” (why didn’t I named so?):

    public class MyItem
    {
        public string Code { get; set; }
        public string Description { get; set; }

        public override string ToString()
        {
            return this.Code;
        }
    }

The data-set generation looks as follows:

    public partial class App : Application
    {
        public IEnumerable<MyItem> ItemCollection { get; private set; }


        protected override void OnStartup(StartupEventArgs e)
        {
            var nomi = new[] { "Mario", "Carlo", "Lucia", "Elena", "Giorgio", "Nicoletta" };
            var cognomi = new[] { "Bianchi", "Rossi", "Verdi", "Brambilla", "Scarpa", "Zennaro" };

            var items = new List<MyItem>();

            for (int i = 0; i < cognomi.Length; i++)
            {
                for (int k = 0; k < nomi.Length; k++)
                {
                    var mi = new MyItem();
                    mi.Code = (i * 10 + 11 + k).ToString();
                    mi.Description = nomi[k] + " " + cognomi[i];
                    items.Add(mi);
                }
            }

            this.ItemCollection = items;

            base.OnStartup(e);
        }
    }

The deal is populating the combo-box with such a data-set, then testing for a numeric input so that the drop-down part should arrange accordingly. As a (future) bonus, the list should be filtered upon the actual number. That should facilitate the user when he/she has to enter a non-existent ID.
On the XAML-side the base is something like this:

<Window 
    x:Class="ComboEditableDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ComboEditableDemo"
    Title="Window1 - buggy" 
    Height="300" 
    Width="400"
    x:Name="This"
    >
    
    <Window.Resources>
        
        <DataTemplate x:Key="dtplItem">
            <StackPanel
                Orientation="Horizontal"
                >
                <TextBlock Text="{Binding Path=Code}" Margin="0,0,8,0" />
                <TextBlock Text="{Binding Path=Description}" />
            </StackPanel>
        </DataTemplate>
        
    </Window.Resources>
    
    <Grid>
        <ComboBox
            x:Name="Cbo1"
            Width="250"
            Height="30"
            IsEditable="True"
            StaysOpenOnEdit="True"
            ItemTemplate="{StaticResource dtplItem}"
            FontSize="18"
            SelectedItem="{Binding Path=CurrentItem, ElementName=This}"
            Text="{Binding Path=CurrentText, ElementName=This}"
            . . .
            >
        </ComboBox>
    </Grid>
</Window>

Finally, here is a possible way to link the data-set to a ComboBox:

            this.Cbo1.ItemsSource = ((App)App.Current).ItemCollection;

First attempt: the bug.

The first attempt was done via a simple styling of the ComboBox, since it exposes two interesting properties:

The style was defined as follows:

        <Style x:Key="ComboStyleKey" TargetType="ComboBox">
            <Setter Property="StaysOpenOnEdit" Value="True" />

            <Style.Triggers>
                <Trigger Property="IsSelectionBoxHighlighted" Value="True">
                    <Setter Property="IsDropDownOpen" Value="True" />
                </Trigger>
            </Style.Triggers>
        </Style>

Although everything seemed going fine (no errors), once you click with the left mouse button in the selection box, a nasty “StackOverflow” exception is suddenly raised. No matter whether the application is creates as “Debug” or “Release”: the error seems very stable.

stack-overflow

At first glance it’s not clear why it happens, and not how to solve or even around it. Also because the actual exception looks as raised in a very deep layer, below the managed. However, that’s just what I suppose.
The second attempt gave me a clearer idea.

Second attempt: better, but not solved yet.

The second attempt was focus on find any (decent) workaround to the bug. Internet didn’t give more help, so I had to find something reliable to make the ComboBox working.
The hint was just on the “stack overflow”, because most of the times it’s a recursive problem. Again, many times you generate such a exception when there are circular calls, that fill the stack sooner. So, let’s give the UI a “breath”: a small delay, so that a routine can complete before actually calling the next one.
Here is the trick:

    public class ComboBox2
        : ComboBox
    {
        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);

            if (e.Property.Name == "IsSelectionBoxHighlighted" &&
                this.IsEditable &&
                this.IsSelectionBoxHighlighted &&
                this.IsDropDownOpen == false &&
                this.StaysOpenOnEdit)
            {
                this.OpenDropDown();
            }
        }


        private async void OpenDropDown()
        {
            await Task.Delay(200);
            this.IsDropDownOpen = true;
        }

    }

Well, the exception wasn’t raised any more, but…AW!…the interaction result was not the expected.
Since the drop-down part is actually a borderless “Window” object, it tries to capture the mouse, at least until some kind of mouse action is worthwhile to be captured. As soon, the mouse click outside its client area, the down-down window closes, but the click is “lost”. That is, there’s no (easy) way to interact with the “real” window, so even an attempt to close the application looks impossible.

Despite this trick did not solved the problem, at least it clears *why* the exception is raised in the previous scenario. As soon the selection box is highlighted, the trigger starts the opening of the drop-down. However, the opening of this new child-window would captures the user-input, moving the focus off the selection box. However, the focus is restored to the selection box, and the condition will trigger again the drop-down opening.

Third attempt: all right!

The final solution isn’t much different than the previous attempt: simply avoid the “IsSelectionBoxHighlighted” property…

    public class ComboBox3
        : ComboBox
    {

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);

            if (this.IsEditable &&
                this.IsDropDownOpen == false &&
                this.StaysOpenOnEdit)
            {
                this.IsDropDownOpen = true;
            }
        }

    }

Conclusion.

You may download the source for the demo application here.

 
Leave a comment

Posted by on January 15, 2014 in .Net, Software

 

Tags: , , , ,

San Martino 2013 a Campalto, Venezia

Anche per quest’anno la tradizionale Festa di San Martino si è conclusa, con tanto di scongiuri verso la pioggia che in più occasioni ha minacciato l’anidirivieni dei visitatori.
La cosa che si attende maggiormente è la chiusura della grande via Orlanda: densa di traffico tutto l’anno, per un giorno diventa di proprietà assoluta di grandi e piccini. Già questo rende felici…

Alessio ed io aspettavamo con ansia i falconieri, che negli ultimi anni portavano alcuni uccelli rapaci in mostra, nel boschetto sotto casa nostra. Quest’anno però non si sono fatti vedere…
In compenso, il piazzale della chiesa ha visto i soliti spettacoli di strada…

True makers…

L’inventiva ed il fai-da-te sta facendo sempre più da padrona in questo genere di eventi: l’artigianato e la manualità stanno riscoprendo vecchi sapori, che davvero fanno ben sperare.

Le mani di fata di Emma e Mariangela.

I bijoux trendy di Sabrina ed Arianna.

Arrivederci al prossimo anno!

 
Leave a comment

Posted by on November 11, 2013 in Campalto

 

Tags: , , , ,

Hacking the WPF GridView – Two more features

This is another post about the hacking of the standard WPF GridView typically used with(in) the ListView. If you missed anything about my previous three article on it, please have a look here.
By using the hacked component in some real projects, I discovered that something was missing, and something else could be improved. In particular, here are a couple of features making my GridViewEx almost complete (well…not perfect yet!)

XAML-defined columns.

The GridViewEx approach was based on a GridViewColumn wrapper. The host application should add as many wrappers as needed, and the real columns will be created (and synchronized) accordingly. This approach is basically the MVVM pattern, and yields the ability to manipulate the visual columns with ease and flexibility.
However, that’s not always an acceptable usage: the XAML-way to define templates and styles is far better than the classic code. Well, I wished to find a solution as a compromise between the MVVM flexibility and the XAML power.
The solution I chose is pretty easy: an extra columns “back” synchronization, which operates when there’s no ambiguity between the XAML and the MVVM collections content. The legacy MVVM columns management is still alive and full compatible. However, when the MVVM is bound “empty” the XAML columns definition will be taken in account.
Here follows the code added to the GridViewEx class.

        /// <summary>
        /// Provides the backward-alignment from the XAML-defined columns
        /// to the wrapper collection source.
        /// That should happen only when the source collection is empty,
        /// and there are XAML-column defined in the view.
        /// </summary>
        /// <param name="source"></param>
        private void BackAlign(Collection<GridViewColumnWrapper> source)
        {
            if (source.Count == 0 &&
                this.Columns.Count > 0)
            {
                foreach (GridViewColumn column in this.Columns)
                {
                    var wrapper = new GridViewColumnWrapper();
                    wrapper.Header = column.Header;
                    wrapper.Width = column.Width;
                    wrapper.IsVisible = true;
                    wrapper.ColumnHash = column.GetHashCode();
                    source.Add(wrapper);

                    //setup the column
                    this.SetupColumn(wrapper, column);
                }
            }
        }

The above method is called once only, at the moment of the binding to a new wrapper collection. As the code shows, if there’s no wrappers, the defined XAML GridViewColumn are automatically converted to wrappers. Hereinafter the game plays as usual.

The column’s setup has been moved off the existent Align method, to a dedicated one in order to be used both in the forward- and in the back-alignment of the columns’ collection.

        /// <summary>
        /// Prepares the column binding it to the wrapper
        /// </summary>
        /// <param name="wrapper"></param>
        /// <param name="col"></param>
        private void SetupColumn(
            GridViewColumnWrapper wrapper,
            GridViewColumn col)
        {
            //creates the behavior for the length animation
            var bvr = new LengthAnimationBehavior(GridViewColumn.WidthProperty);
            Interaction.GetBehaviors(col).Add(bvr);
            bvr.ControlledValueChanged += bvr_ControlledValueChanged;

            //binds the nominal width of the column to the behavior
            BindingOperations.SetBinding(
                bvr,
                LengthAnimationBehavior.NominalLengthProperty,
                new Binding("Width")
                {
                    Source = wrapper,
                });

            //also binds the visibility to the behavior
            BindingOperations.SetBinding(
                bvr,
                LengthAnimationBehavior.IsVisibleProperty,
                new Binding("IsVisible")
                {
                    Source = wrapper,
                });

            //now finally enables the animation
            bvr.IsAnimationEnabled = true;
        }

To test the new feature, the window’s XAML page has been simplified as follows.

<Window 
    x:Class="ListViewHacking.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ListViewHacking"
    Title="ListView hacking demo" 
    Height="480" Width="900"
    WindowStartupLocation="CenterOwner"
    FontSize="14"
    Background="{StaticResource BG}"
    >
    
    
    <Window.Resources>
        
        <DataTemplate x:Key="dtpl1">
            <TextBlock
                Text="{Binding Path=FirstName}"
                />
        </DataTemplate>


        <DataTemplate x:Key="dtpl2">
            <TextBlock
                Text="{Binding Path=LastName}"
                />
        </DataTemplate>


        <DataTemplate x:Key="dtpl3">
            <TextBlock
                Text="{Binding Path=City}"
                />
        </DataTemplate>

    </Window.Resources>
    
        
    <Grid
        Margin="50,40"
        >
        <ListView
            ItemsSource="{Binding Path=People, Source={x:Static local:App.Current}}"
            x:Name="lvw1"
            >
            <ListView.Resources>
                <local:ColumnHeaderEnableConverter x:Key="cv1" />
                <Style TargetType="{x:Type GridViewColumnHeader}">
                    <Setter Property="IsEnabled" Value="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=Self}, Converter={StaticResource cv1}}" />
                </Style>
            </ListView.Resources>

            <ListView.View>
                <local:GridViewEx
                    AllowsColumnReorder="False"
                    ColumnsSource="{Binding Path=.}"
                    >
                    <GridViewColumn Header="FirstName" Width="150" CellTemplate="{StaticResource dtpl1}" />
                    <GridViewColumn Header="LastName" Width="150" CellTemplate="{StaticResource dtpl2}" />
                    <GridViewColumn Header="City" Width="150" CellTemplate="{StaticResource dtpl3}" />
                </local:GridViewEx>
            </ListView.View>
        </ListView>
        
    </Grid>
</Window>

Now, let’s switch to the trickier problem.

Per-column defined cell content alignment.

Sometime is useful to define the alignment (horizontal and vertical) of a cell content. Unfortunately the native GridView offers no help about this feature, and the only way to control the cell behavior is via the ListViewItem styling.
To be clear, none of the below approaches will align the text content to the right edge of the respective cells.

        <DataTemplate x:Key="dtpl1">
            <TextBlock
                Text="{Binding Path=FirstName}"
                Background="Yellow"
                HorizontalAlignment="Right"
                />
        </DataTemplate>
        
        <DataTemplate x:Key="dtpl2">
            <TextBlock
                Text="{Binding Path=LastName}"
                Background="Yellow"
                TextAlignment="Right"
                />
        </DataTemplate>

lh5-1

That’s because the template-created content is actually hosted in a ContentPresenter object. The GridView creates as many ContentPresenters as the columns are, and the user’s control over these components is very limited. Please note that the ContentPresenters are created always but when you bind the cell’s content via a simpler DisplayMemberBinding. In that case, a simple TextBlock is created instead.
As said, the only way to control the alignment of the hosted ContentPresenters is by settings the HorizontalContentAlignment (or VerticalContentAlignment) in the ListViewItem style. In other words, you could style the rows as follows:

        <ListView
            ItemsSource="{Binding Path=People, Source={x:Static local:App.Current}}"
            x:Name="lvw1"
            >
            <ListView.Resources>
                <local:ColumnHeaderEnableConverter x:Key="cv1" />
                <Style TargetType="{x:Type GridViewColumnHeader}">
                    <Setter Property="IsEnabled" Value="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=Self}, Converter={StaticResource cv1}}" />
                </Style>

                <!-- alter the items (rows) implicit style -->
                <Style TargetType="ListViewItem">
                    <Setter Property="HorizontalContentAlignment" Value="Right" />
                </Style>
            </ListView.Resources>

            <ListView.View>
                <local:GridViewEx
                    AllowsColumnReorder="False"
                    ColumnsSource="{Binding Path=.}"
                    >
                    <GridViewColumn Header="FirstName" Width="150" CellTemplate="{StaticResource dtpl1}" />
                    <GridViewColumn Header="LastName" Width="150" CellTemplate="{StaticResource dtpl2}" />
                    <GridViewColumn Header="City" Width="150" CellTemplate="{StaticResource dtpl3}" />
                </local:GridViewEx>
            </ListView.View>
        </ListView>

The result is as expected, but involves all the cells, without any control on a specific column.

lh5-2

This behavior is predefined in the GridViewRowPresenter, which is part of the default rows styling. The most straightforward way to take the control over the row’s cell presenters is creating (or deriving) a custom GridViewRowPresenter, then re-styling the ListViewItem. However, I would avoid to touch any of the Windows’ default styles.

The solution I used takes advantage of a couple of Attachable DependencyProperty: one for each alignment orientation.
The attached DP comes in aid because it can be stuck anywhere in the logical tree, and that’s helping to reach the hidden visual element. The basic idea is right on the attaching event of the DP: at that time the visual tree is walked up, up to the “original” GridViewRowPresenter. The immediate-child of that presenter is the sought ContentPresenter, and the alignment properties are fully exposed.

        #region DPA HorizontalContainerAlignment

        public static readonly DependencyProperty HorizontalContainerAlignmentProperty = DependencyProperty.RegisterAttached(
            "HorizontalContainerAlignment",
            typeof(HorizontalAlignment),
            typeof(GridViewEx),
            new UIPropertyMetadata(
                default(HorizontalAlignment),
                HorizontalContainerAlignmentChanged
                ));


        public static HorizontalAlignment GetHorizontalContainerAlignment(DependencyObject obj)
        {
            return (HorizontalAlignment)obj.GetValue(HorizontalContainerAlignmentProperty);
        }


        public static void SetHorizontalContainerAlignment(DependencyObject obj, HorizontalAlignment value)
        {
            obj.SetValue(HorizontalContainerAlignmentProperty, value);
        }


        private static void HorizontalContainerAlignmentChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            var current = sender as DependencyObject;
            int levels = 10;

            while (current != null && levels-- > 0)
            {
                var next = VisualTreeHelper.GetParent(current);
                if (next is GridViewRowPresenter)
                {
                    var cp = current as ContentPresenter;
                    if (cp != null)
                    {
                        cp.HorizontalAlignment = (HorizontalAlignment)args.NewValue;
                    }
                    break;
                }

                current = next;
            }
        }

        #endregion

And here is how to apply it:

        <DataTemplate x:Key="dtpl1">
            <TextBlock
                Text="{Binding Path=FirstName}"
                Background="Yellow"
                local:GridViewEx.HorizontalContainerAlignment="Stretch"
                />
        </DataTemplate>


        <DataTemplate x:Key="dtpl2">
            <TextBlock
                Text="{Binding Path=LastName}"
                Background="Yellow"
                local:GridViewEx.HorizontalContainerAlignment="Right"
                />
        </DataTemplate>


        <DataTemplate x:Key="dtpl3">
            <TextBlock
                Text="{Binding Path=City}"
                Background="Yellow"
                />
        </DataTemplate>

Finally, the visual result is the following.
lh5-3

Conclusions.

Hacking. Far funnier than digging around for hours looking for a ready-to-go solution, which (we do know) does not exist.
I loved this series of hacking around the GridView, because it showed me that even a very simple component as the (ListView plus the) GridView is, yields a lot of power by just learning a bit on how its core works.

Feel free to download the demo source here.

 
Leave a comment

Posted by on November 10, 2013 in .Net, Software

 

Tags: , , ,

 
Follow

Get every new post delivered to your Inbox.

Join 75 other followers