Tuesday, April 19, 2011

Mango = Layar, Skype, and almost too much to name...

Just a quick YAY! After the recent MIX reveals it seems like my Layar wish will come true with Mango! Now I'm "just" waiting for a resolution of the Google (Maps) vs Bing (Maps) situation in the Netherlands.

DevDays 2011

Yes, it is almost time: the 2011 edition of the Dutch DevDays. That's why the rest of this blog post will be in Dutch. My apologies to any international readers.

Zoals je op dit moment (het attending logo zal later waarschijnlijk wel weer verdwijnen) hiernaast kunt zien ben ik er ook weer bij. Kleine tip wat betreft dat logo: de Beleef pagina waar je de HTML snippet kunt krijgen voor je eigen logo bevat een fout. De image URL begint met ./images in plaats van met http://www.techdays.nl/images. Beetje slordig, maar gelukkig makkelijk te corrigeren.

Mijn persoonlijke agenda zal waarschijnlijk best een hoop op die van Joost lijken: veel Windows Phone, zeker na MIX met alle nieuwe aankondigingen. Een daadwerkelijke definitieve keuze maak ik waarschijnlijk zoals altijd pas op de dag zelf.

Tot in het World Forum in Den Haag!

Friday, March 11, 2011

#7slp = SevenSteps #wp7dev LAN Party

LAN Party kick-offYesterday I was at the Dutch Windows Phone 7 LAN party, "and all I got was this damn T-shirt." ;-)

It was a great day, in which the Dutch Windows Phone 7 developer community tried to come together with dozens of developers/designers to create a WP7 app from scratch. For some more information (including some killer images), please check out my description in Dutch or the English machine-translation made possible by a Google server farm.

Wednesday, March 2, 2011

Syntax highlighting is (finally!) back on this blog...

After recently changing the look of my blog not only did I lose my Google Analytics code from the template, but also the inclusion of Syntax Highlighter. I added analytics back earlier, but hadn't come round to putting source highlighting back into place. This has now been done, and all source code posted while highlighting was gone now has the needed brush class in place again. Hopefully this will make you enjoy reading code on this weblog even better.

Example code for SplitUp(), on infinite sequence! ;-)

I've received some positive reactions to my previous post, in which I gave source code of a lazy implementation of a SplitUp() function that could be used for paging an IEnumerable<T>.

However, I also got comments that example code on how you could use this would be nice. I had been thinking about that - also to show off exactly how the SplitUp() code is lazy and what actually happens if you use it - but decided to leave it out. That was mainly because I myself already knew; it just wasn't a goal of that previous blog post for me. Personally I'm not that much of a "need to see it work in an example" kind of guy, you know? Plus, blog posts take a bit of time. ;-)

Having said that, I can now give you this example, which should be self-explanatory if you run the following code in a console app project that includes the source from the previous blog code as well. Hope you enjoy it; as always all comments are welcome!

namespace SplitUpExample
{
  using System;
  using System.Linq;
  using System.Collections.Generic;
  using peSHIr.Utilities;

  class Program
  {
    static bool TraceDataCreation;
        
    static Action<string> println = text => Console.WriteLine(text);
    static Action<string> print = text => Console.Write(text);
    static Action newline = () => Console.WriteLine();

    static void Main(string[] args)
    {
      newline();
      println("* How can SplitUp() be used for paging");
      TraceDataCreation = false;
            
      var allData = TestData(64);
      var pagedData = allData.SplitUp(7);
      foreach (var page in pagedData)
      {
        print("Page:");
        foreach (int i in page)
        {
           print(" ");
           print(i.ToString());
        }
        newline();
      }

      newline();
      println("* And is it really lazy?");
      TraceDataCreation = true;
            
      println("Calling SplitUp() on infinite sequence now");
      var pagedInfinity = TestData().SplitUp(4);

      println("Retrieving first page now");
      var page1 = pagedInfinity.ElementAt(0);
            
      println("Retrieving third page now");
      var page3 = pagedInfinity.ElementAt(2);
            
      Action<string,int,int> results = (text,sum,count)
        => Console.WriteLine("{0}: {1}, {2}", text, sum, count);

      println("Showing results:");
      results("First page", page1.Sum(), page1.Count());
      results("Third page", page3.Sum(), page3.Count());
      println("So yes, SplitUp() is lazy like LINQ! ;-)");

#if DEBUG
      newline();
      println("(Key to quit)");
      Console.ReadKey();
#endif
    }

    static IEnumerable<int> TestData(int n)
    {
      return TestData().Take(n);
    }

    static IEnumerable<int> TestData()
    {
      // WARNING: this returns an infinite sequence!
      // Or at least: until int overflows... ;-)
      int i = 0;
      while (true)
      {
        if (TraceDataCreation)
          Console.WriteLine("Yielding {0}", i);
        yield return i++;
      }
    }

  }

}

Thursday, February 24, 2011

Example of C# lazy, functional programming: SplitUp()

I seem to be on a bit of roll here regarding extension methods. They are by no means a silver bullet, but this method is a nice LINQ-like lazy method on a generic sequence that is a perfect fit. I think it nicely illustrates how you can write your own such functional methods that are usable like LINQ methods that are part of the .NET framework, and have some of the same characteristics.

This SplitUp() extension method takes a sequence and splits it up into subsequences that each have a maximum length. For instance, you can split a sequence (list, collection, array, etc.) of 64 integers into an enumerable sequence of List<int> instances of lengths 10, 10, 10, 10, 10, 10 and 4 by calling SplitUp(10) on it.

Here is the source:

namespace peSHIr.Utilities
{
 using System;
 using System.Linq;
 using System.Text;
 using System.Collections.Generic;

 /// <summary>Utility code for working with sequences</summary>
 public static class SequenceUtility
 {
  /// <summary>Split up sequence of items</summary>
  /// <typeparam name="T">Item type</typeparam>
  /// <param name="input">Input sequence</param>
  /// <param name="n">Maximum number of items per sublists</param>
  /// <returns>Sequence of lists with a maximum
  /// of <paramref name="n"/> items</returns>
  /// <remarks>Might need a suppression of code analysis rule
  /// CA1006 because of the nested generic type in the method
  /// signature.</remarks>
  public static IEnumerable<IEnumerable<T>>
   SplitUp<T>(this IEnumerable<T> input, int n)
  {
   // Non-lazy error checking
   if (input == null) throw new ArgumentNullException("input");
   if (n < 1) throw new ArgumentOutOfRangeException("n", n, "<1");
   return SplitUpLazy(input, n);
  }

  private static IEnumerable<IEnumerable<T>>
   SplitUpLazy<T>(IEnumerable<T> input, int n)
  {
   // Lazy yield based implementation
   var list = new List<T>();
   foreach (T item in input)
   {
    list.Add(item);
    if (list.Count == n)
    {
     yield return list;
     list = new List<T>();
    }
   }
   if (list.Count > 0) yield return list;
   yield break;
  }
 }
}

As you can see, the SplitUp function behaves like built in LINQ functions because its implementation is split up (pun intented...). The public variant basically just does argument checking, so you get the ArgumentExceptions on improper use immediately when calling the method, while the private actual implementation uses yield statements to implement the actual splitting of the input sequence into lists of at most n elements.

This mirrors the implementation of LINQ methods, as shown in the very informative Edulinq blog series on their implementation by Jon Skeet, the so called superuser of stackoverflow.com.

I hope you find this extra illustration of this technique informative, or at least find the method itself useful. Personally I have used it for splitting up sequences of input records from a file into batches for processing by a web service that had a maximum request size. I would love to hear what you have used it for, so all comments are welcome.

(Added later: For those of you that like to have working pieces of example code to play with for code nuggets like this, please check out my next blog post.)