Monthly Archives: July 2012

Windows phone 8 to support chat rooms?

More digging into the emulator images for wp8 has thrown up more interesting finds that should be coming to the platform come the end of this yeat.  This time it looks like Microsoft has some interesting plans for the already cool “groups” functionality.

Digging through the resource files I have numerous mentions to “rooms” being supported.  From what I am gathering this feature would be an addition to the groups functionality whereby you should be able to add a group of your friends to a chat room and all chat live.  Super cool!

This resources are used by the contactsres.dll in system32 and I have a couple of snippets for you below.

Gather your friends and family together. Invite them to a private Room where you can share a calendar, photos, group chat and notes. Or add them to a Group to see social updates from just those folks and text them all at once. Tap the plus sign to get started.

This room will be deleted. You can create a new room in the People Hub.

1 people left the room

Room membership has changed

I must admit this feature sounds awesome and if it turns out to be true fits perfectly in-line with windows phone being the premier social networking phone.

Advertisement

Will WP8 have new parental control features?

Been looking over the WP8 emulator images today and came across this interesting resource string.

The My Family settings for your account prevent you from downloading this item. Your parent can manage My Family settings at windowsphone.com.

This resource string found in the common mobile UX resources seems to suggest that a new feature called “My Family” will be coming to WP8.

WP8 SDK Silverlight Alive!……XNA Dead……Native XAML gone missing!

I suppose you guys have heard that the windows phone 8 SDK has leaked. Well I decided to download the bits and have a quick look around.  This  post is really just summary of some interesting observations I made.  If you want to download the bits yourself you will have to hunt around. I found it on on a torrent site and had good seeding.

Where is the winRT support? 

One of the first things I did once I had installed the SDK was to run up Visual Studio 2012 and see what projects types were available.  What caught my eye was the fact that there appears to be no “Metro style” or “WinRT” project templates installed.  The naming of the projects is pretty much the same as the 7.5 SDK. I’m sure that’s a good thing as you don’t want to confuse people right? Below is a screenshot of the project picker.

You can see I have highlighted a new project type which never used to exist in the 7.5 SDK.  I’ll come back to that shortly.  As winRT tech does not seem to be obviously visible in the project list it seems I will have to dig a little deeper.  Lets see if creating a standard “Windows Phone Application” will provide more detail as to what’s going on in this new release.

new apps for WP8 wont be running on winRT aka native xaml but instead managed xaml

Well that’s a turn up for the books.  From what I can tell these new apps for WP8 wont be running on winRT aka native xaml but instead managed XAML.  To me that looks like standard CLR namespaces being imported and therefore is managed code. Also it seems I have classes that aren’t available in winRT such as RadialGradientBrush. Digging out jetbrains dotpeek proves exactly that, the whole runtime is silverlight.

This raises a couple of questions, firstly why did Microsoft put so much effort into creating native XAML and then not adopt it for WP8?  Secondly what does this mean for developers wishing to develop across 3 screens?

The first question I think is easily answered, it is likely to be timing issue. With the monumental effort to get Windows 8 ready for its October release there probably hasn’t been time to migrate the winRT tech & tooling to WP8. Further, developers who have already created apps on the platform do not want to have to rewrite them for winRT.  Especially as winRT is equivalent to Silverlight 2.0 at the mo and would lead alot of gaps.

 If you’re a html5 developer building apps for winRT and you want to port them to WP8, well you are royally screwed at the moment

The second question is difficult.  It seems the one dev platform for all screens is not here yet. Although porting code is possible it’s not going to be smooth given the current situation. If you’re a html5 developer building apps for winRT and you want to port them to WP8, well you are royally screwed at the moment.

One last point on this, it seems C++ devs get a raw deal as they wont be able to leverage XAML on WP8.  Well not until winRT arrives.  From what we have heard from Microsoft, the key deliverable for this release was about providing native code access.   This is so that all those game developers who need to extract every cycle of  performance out of platform can do so.  It will be good to see popular games from iOS transitioning quicker to WP8.  But that leads to the next topic….

What’s the deal with XNA? 

Well I think with WP8 SDK I think you can official say goodbye to XNA.

One of the other big questions hanging over the the future of WP8 was what’s happening to XNA.  Well I think with WP8 SDK I think you can official say goodbye to XNA.  In this new SDK you only seem to be able to create XNA games that target WP7.1. If you want to use XNA in WP8 then it seems you are out of luck.

But the story gets a little worse than that,  if you remember in my screenshot above I highlighted a new project type called “Windows Phone Direct3D XAML Application”.  Well the good news is that this project can target WP8, however on creating one of these projects your actually going to be developing your game in C++.  The project is set up with a simple c# xaml app with a DirectX drawing surface, then all your access to DirectX must be written in native code.  I can’t see XNA coming back from this personally but hey, you never know. Microsoft are anything from consistent these days.

All in all this leak is a bit of mixed bag, while the WP8 platform looks to be getting some cool new features the dev story is a mixed one.  A few bullet points below for the guys that don’t want to read my waffle above.

  • Managed xaml lives on in WP8
  • winRT is nowhere to be seen
  • 3 Screens development story not being realised in this release.
  • Native code now available on the platform
  • XNA is left out of the WP8 party
  • If you want to build games then dig your C++ book out

Coding challenge: Reading an LCD display

If you read my previous post “Coding challenge: Creating an LCD display” then you will remember I was set a challenge by a friend of mine to create a function that would take an integer and produce a LCD display inside of a console window.

Well I got a follow up challenge from him this week which went like this.

This week’s kata is simply the inverse of last week’s … instead of taking a number and producing a “LCD display”, the task this week is to accept an LCD display and produce a number.  Numbers will always be 3 lines high and 3 characters wide: The easy version: accept a single digit in a single and return the numeric value. The harder version: accept a multi-digit display and return the numeric value.

So with the challenge set it was time to attack the problem.  Again the real difficulty that presents itself in this challenge is the fact that the data must be read line by line.  Therefore you must track the pattern of each digit as you move down through the data and only once you have that data can you start to make some decisions.  First however I still set myself some base rules for this challenge. I have listed them below.

  • All numbers through 0-9 must be matched.
  • Each number must be easily encoded in order to compare with the input data.
  • Extracting the number of digits from the input data can be worked out given the fixed size of the challenge.
  • Each digit being pattern matched must be encoded in the same way as the list we will compare against.
  • We will need to avoid the blank lines in the data.

Given all these, here is my code below. Lucky for me I could seed my function by using the draw method from previous post so made it easier to test.

First I created a unique encoding of all the numerals from 0-9 using a simple read of each line and concatenating the strings together.  This pre-computer value saves time and should be easy to compare against.

        private static Dictionary<string, string> GetMatchPatterns()
        {
           return new Dictionary<string, string>
                        {
                            {"0", " - | |   | | - "},
                            {"1", "     |     |   "},
                            {"2", " -   | - |   - "},
                            {"3", " -   | -   | - "},
                            {"4", "   | | -   |   "},
                            {"5", " - |   -   | - "},
                            {"6", " - |   - | | - "},
                            {"7", " -   |     |   "},
                            {"8", " - | | - | | - "},
                            {"9", " - | | -   | - "}
                        };
        }

And below is the main Read method that actually does the pattern matching.  It’s fairly concise this time round.

        private static string Read(string number)
        {
            var patterns = GetMatchPatterns();
            var stringReader = new StringReader(number);
            var line = stringReader.ReadLine();
            var nCount = (line.Length / 4) + 1;
            var chars = new string[nCount];

            while (line != null)
            {
                for (int i = 0; i < nCount; i++)
                {
                    var currentPos = (i * 3) + i;
                    var data = new string(line.Skip(currentPos)
                                               .Take(3)
                                               .ToArray());
                    chars[i]= chars[i] + data;
                }

                line = stringReader.ReadLine();
            }

            return chars.Select(c => patterns.First(kc => kc.Value.Equals(c)).Key)
                        .Aggregate((a, b) => a + b);
        }

Performance seems good with rendering of the LCD representation of 1234567890 in around 140 ticks.

Stack vs Heap

So in relation to my last post on the LCD coding challenge.  A few more examples came up for solving this kata.  As we were discussing memory and speed etc I casually stated

Well if you convert all you classes to structs then that should make things faster.

I’ve heard this a lot but it occurred to me that I have never really tested the theory.  Also I couldn’t answer the question on everyone’s lips which is how much faster.  Therefore I put a quick spike together to test this and below are the results.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Testing creating 100,000,000 heap objects");
            for (int j = 0; j < 10; j++)
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                for (int i = 0; i < 100000000; i++)
                {
                    var person = new PersonClass();
                }

                stopwatch.Stop();
                Console.WriteLine(string.Format("Elaspsed ms: {0}", stopwatch.ElapsedMilliseconds));
            }

            Console.ReadLine();
        }
    }

    public class PersonClass{}

    public struct PersonStruct{}

And below is the summary of the results.  I create 100 million class heap objects and the same number using structs.  I run this in a loop 10 times.

Testing creating 100,000,000 heap objects
Elaspsed ms: 850
Elaspsed ms: 824
Elaspsed ms: 820
Elaspsed ms: 809
Elaspsed ms: 825
Elaspsed ms: 850
Elaspsed ms: 809
Elaspsed ms: 803
Elaspsed ms: 793
Elaspsed ms: 794
Finished!

Testing creating 100,000,000 struct objects
Elaspsed ms: 255
Elaspsed ms: 248
Elaspsed ms: 246
Elaspsed ms: 251
Elaspsed ms: 244
Elaspsed ms: 245
Elaspsed ms: 245
Elaspsed ms: 248
Elaspsed ms: 244
Elaspsed ms: 246
Finished!

As you can see creating the structs are way quicker as we are no longer allocating memory on the heap and are avoiding putting pressure on the GC.  Based on this non-scientific test we would average over 3 times quicker. 

Moral of the story, if you need to create a lot of simple throw away objects in memory and you want the best performance then consider converting your objects to value types.

Coding challenge: Creating an LCD display

A friend of mine and sharpfellow John Rayner posted a coding Kata to a c# group I subscribe to on Friday.   We have a lot of these posted in the group and its a great way to see how different people attack the problem.  Fridays Kata was described as follows.

Today’s problem is to create an LCD for displaying numbers.  You are given two integers s and n, where n is the number to be displayed and s is the size,  You need to use | and _ characters to construct a display.  Each digit occupies exactly s+2 columns and 2s+3 rows. There has to be exactly one column of blanks between digits.

Examples:
  s=2, n=12345 & s=3, n=67890

After thinking about this problem for a little while, I came to conclusion that each digit in the display has some fairly simple structure and that structure is common across all digits.  I set out some core rules that would help me break down this problem.  I have listed these out.

  • Each Digit has two box sections.  And upper and lower box.
  • Each Digit has a top, middle & bottom which must be formed of dashes.
  • Excluding the top, middle and bottom dash sections, you must assume that the gaps must be bars ( “|”)
  • In the “bars” sections a digit can be formed of 3 types of bar. Left, Right and Both.

With these rules in place I set about tacking the problem.  I went through a few iterations to reach the version below and I am sure I could go through a few more to make it cleaner and more efficient.  This version does pretty well though by generating the number 1234567890 with 5 chars per segment in 4 ms.

        private static StringBuilder Draw(int b, int n)
        {
            var format = string.Join("|", n.ToString().ToCharArray());
            var buffer = new StringBuilder();
            var line = new StringBuilder();
            var lineCount = 2 + (b * 2);
            var dash = string.Format(" {0} ", string.Concat(Enumerable.Repeat("-", b)));
            var blank = string.Format(" {0} ", string.Concat(Enumerable.Repeat(" ", b)));
            var barLeft = string.Format("|{0} ", string.Concat(Enumerable.Repeat(" ", b)));
            var barRight = string.Format(" {0}|", string.Concat(Enumerable.Repeat(" ", b)));
            var barAll = string.Format("|{0}|", string.Concat(Enumerable.Repeat(" ", b)));
            var dashLines = new Dictionary<int, string>
            {
                {0, "23567890"},
                {lineCount / 2, "2345689"},
                {lineCount, "2356890"},
            };

            for (int i = 0; i <= lineCount; i++)
            {
                line.Clear();
                foreach (var character in format)
                {
                    if (character.Equals("|"[0]))
                    {
                        line.Append(" ");
                        continue;
                    }

                    if (dashLines.ContainsKey(i))
                    {
                        line.Append(dashLines[i].Contains(character) ? dash : blank);
                        continue;
                    }

                    if(i < lineCount / 2)
                    {
                        if ("4890".Contains(character))
                        {
                            line.Append(barAll);
                            continue;
                        }
                        if ("1237".Contains(character))
                        {
                            line.Append(barRight);
                            continue;
                        }
                        line.Append(barLeft);
                    }
                    else
                    {
                        if ("086".Contains(character))
                        {
                            line.Append(barAll);
                            continue;
                        }
                        if ("1345679".Contains(character))
                        {
                            line.Append(barRight);
                            continue;
                        }
                        line.Append(barLeft);
                    }
                }
                buffer.AppendLine(line.ToString());
            }

            return buffer;
        }

Using And, Then & When in Reactive Extensions

When you look over the list of observable method’s on MSDN I can see that I use maybe 60% of them quite frequently.  I find that I’ll use Do’s or SelectMany etc almost every day and more involved operators like Publish and Merge at least once a week.

Today I wanted to cover 3 operators that I find aren’t used frequently but can be used together to provide powerful synchronization techniques.  The operators are “And”, “Then” and “When”.

The “And” operator

If we look on MSDN for the “And” operator we can see that documentation tells us this “Matches when both observable sequences have an available value.”. Well ok, that sounds pretty simple.  I reckon I can put some code together to show how this works.   I just need two streams which both produce a value. Let’s have a try.

Hmmm, well firstly that reads well.  I can see quite easily from reading this code what its intent is, but what I expected as a result of the “And” operator was another IObservable which I could then subscribe to.  So it seems on its own the “And” operator doesn’t work as I expected.  When I look at the return type for “And” I can see it returns something called a “Pattern” and the only operator I can apply to this seems to be a “Then”.

The “Then” Operator

So it seems I have been led to the “Then” operator by some clever design decisions from the Rx designers.  They obviously want me the use the then operator as its really the only thing available to me.  Therefore I better go back to msdn and see what it tells me “Observable.Then<TSource, TResult> Method – Matches when the observable sequence has an available value and projects the value.”.  Well this operator seems very familiar, its almost exactly the same as the “Select” operator.  The select operator takes the value that is pushed to it and transforms the pipeline by returning a different return type.  I can do that!!! lets implement “Then” and we are done right?

Uh oh!! Dead end.  Well this isn’t good.  The one thing that gets me through with LINQ and RX is that operators are discoverable and now I’ve got nowhere to go.  Digging a little deeper I can see that actually what I thought I would get back from “Then” an IObservable<T> what I’m  actually getting is a Plan<T>.  What the heck is a Plan? Why does it have no methods on it so I can do something with it? I’m going to have to do some research.

The “When” Operator

Back to msdn looking for a Plan<T> lets see what it tells us. “Represents an execution plan for join patterns.”  Well that makes sense as that’s essentially what I have been trying to do.  But unfortunately its not giving me the answers for how I actually get values from my stream.  Therefore it’s time to stretch my google-fu and see what I can find.  Turn’s out all the information I needed was actually at the same msdn page I had been looking at for other observable operators.   When I search the page for “Plan” I found that only 1 operator seems to be able to use this construct and thats the “When” operator.

This time I’m told that the “When” operator takes in a Plan<T> and returns a IObservable<T> “Joins together the results from several patterns.”. Yes! This looks like the final piece of the puzzle.  Lets finish the code.

As you can see from the code above, I now use the When operator on my plan so that we can actually gain access to the projected values. Then I write the values to the console window.  The slower stream is in essence the regulating stream in this scenario and therefore the stream only pumps once every 10 seconds.

Summary

As you can see the three operators “And”, “Then” and “When” working together provide some powerful synchronization primitives that we can use in our code to solve a number of different scenarios.  Discovery of these operators is a little trickier than the basic operators and I feel that a few extensions could have been added to make life easier (Why no “When” extension on a Plan<T> for example?).