SQL Server 2008 R2: StreamInsight changes at RTM: Access to grouping keys via explicit typing

One of the problems that existed in the CTP3 edition of StreamInsight was an error that occurred if you tried to access the grouping key from within your projection expression. That was a real issue as you always need access to the key. It’s a bit like using a GROUP BY in TSQL and then not including the columns you’re grouping by in the SELECT clause. You’d see the results but not be able to know which results are which. Look at the following code:

var laneSpeeds = from e in vehicleSpeeds

                 group e by e.Lane

                 into lanes

                 from eventWindow in lanes.TumblingWindow

                      (TimeSpan.FromSeconds(10),

                       HoppingWindowOutputPolicy.ClipToWindowEnd)

                 select new

                 {

                    Lane = lanes.Key.ToString(),

                    AverageSpeed = eventWindow.Avg(e => e.Speed),

                    MaxSpeed = eventWindow.Max(e => e.Speed)

                 };

Executing this code would return:

System.IndexOutOfRangeException: Index was outside the bounds of the array.

This was a known issue in CTP3 that I hoped would have been corrected at RTM. I spoke with the development team and they pointed out that the error only occurs if you’re using an anonymous type. This means that if I declare the type using code like:

struct LaneGroup

{

  public string Lane;

  public double AverageSpeed;

  public double MaxSpeed;

}

my code will then work as long as I modify it to specify the type in the select clause:

var laneSpeeds = from e in vehicleSpeeds

                 group e by e.Lane

                 into lanes

                 from eventWindow in lanes.TumblingWindow

                      (TimeSpan.FromSeconds(10),

                       HoppingWindowOutputPolicy.ClipToWindowEnd)

                 select new LaneGroup

                 {

                    Lane = lanes.Key.ToString(),

                    AverageSpeed = eventWindow.Avg(e => e.Speed),

                    MaxSpeed = eventWindow.Max(e => e.Speed)

                 };

This should be a suitable workaround in most cases. I gather the original problem with be fixed in a later refresh of StreamInsight.

2010-05-08