Using surrogate binders in Silverlight

In WPF you can bind values to any property on a DependencyObject, however in Silverlight, you can only bind to FrameworkElements. Most often when I have hit this roadblock is when I want to bind the rotation or scale of an element to a value. For instance a compass direction bounded to the current heading.

In WPF this would look like this:

<Image>
<Image.RenderTransform >
<RotateTransform Angle="{Binding Path=Heading}" />
</Image.RenderTransform>
</Image>

Unfortunately, since RotateTransform isn’t a FrameworkElement, this won’t work in Silverlight.

Enter: Attached Properties.

Attached properties are really neat when you start getting to know them, and you can do some pretty cool stuff, and still stick to all the MVC glory that the above case prevents you from. Using an custom attached property that manages rotation, I could for instance write:

<Image local:SurrogateBinder.Angle="{Binding Path=Heading}">
<Image.RenderTransform >
<RotateTransform  />
</Image.RenderTransform>
</Image>

So what does this binder look like? The first step is to declare the actual attached property, as well as a get and set method. Note that the naming of the property and the two get and set methods are important for this to work.
 
public static class SurrogateBinder
{
public static readonly DependencyProperty AngleProperty =
DependencyProperty.RegisterAttached("Angle", typeof(double),
typeof(SurrogateBinder),
new PropertyMetadata(OnAngleChanged));
public static double GetAngle(DependencyObject d)
{
return (double)d.GetValue(AngleProperty);
}
public static void SetAngle(DependencyObject d, double value)
{
d.SetValue(AngleProperty, value);
}
}

The next step is to react to when this value is being set/changed. The property declaration above references an OnAngleChanged method to call when the property changes. The idea is that when the value changes, we grab the rotate transform and set the value.
private static void OnAngleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is UIElement)
    {
        UIElement b = d as UIElement;
        if (e.NewValue is double)
        {
            double c = (double)e.NewValue;
            if (!double.IsNaN(c))
            {
                if (b.RenderTransform is RotateTransform)
                    (b.RenderTransform as RotateTransform).Angle = c;
                else 
                    b.RenderTransform = new RotateTransform() { Angle = c };
            }
        }
    }
}

In this case, the property binder is only made to work with a UIElement that wants a rotation applied. But by using a little reflection magic, we can create a completely generic binder that can set any property.
Instead of using one attached property, we use two. One for the value to bind, and another for the property to bind to. This is very similar to when you are creating animations and you both set the target you are animating and the property you are animating on. Apart from the Reflection magic, the code is pretty much the same:
 
public static class SurrogateBind
{
    public static readonly DependencyProperty TargetProperty =
        DependencyProperty.RegisterAttached("Target", typeof(string), typeof(SurrogateBind), null);
 
    public static string GetTarget(DependencyObject d)
    {
        return (string)d.GetValue(TargetProperty);
    }
 
    public static void SetTarget(DependencyObject d, string value)
    {
        d.SetValue(TargetProperty, value);
    }
 
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.RegisterAttached("Value", typeof(object), typeof(SurrogateBind),
        new PropertyMetadata(OnValueChanged));
 
    public static object GetValue(DependencyObject d)
    {
        return (object)d.GetValue(ValueProperty);
    }
 
    public static void SetValue(DependencyObject d, object value)
    {
        d.SetValue(ValueProperty, value);
    }
 
    private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        string path = GetTarget(d);
        if (String.IsNullOrEmpty(path)) return;
        string[] pathElements = path.Split(new char[] { '.' });
        PropertyInfo propertyInfo = null;
        object o = d;
        for (int i = 0; i < pathElements.Length; i++)
        {
            if (o == null) break;
            string s = pathElements[i];
            int begin = s.LastIndexOf('[');
            bool isIndexed = s.EndsWith("]") && begin >= 0;
            propertyInfo = o.GetType().GetProperty(isIndexed ? s.Substring(0, s.LastIndexOf('[')) : s);
            if (propertyInfo == null) break;
            if (i < pathElements.Length - 1)
            {
                object[] index = null;
                if (isIndexed)
                {
                    index = new object[] { int.Parse(s.Substring(begin + 1, s.LastIndexOf(']') - begin - 1)) };
                }
                o = propertyInfo.GetValue(o, index);
            }
        }
        if (propertyInfo != null && propertyInfo.PropertyType == e.NewValue.GetType())
        {
            propertyInfo.SetValue(o, e.NewValue, null);
        }
    }
}

This allows us to to the same thing in XAML:
<TextBox Text="Hello World"
binders:SurrogateBind.Value="{Binding Path=Heading}" 
binders:SurrogateBind.Target="RenderTransform.Angle" >
<TextBox.RenderTransform>
<RotateTransform />
</TextBox.RenderTransform>
</TextBox>

Or if we have nested controls:
<TextBox RenderTransformOrigin="0.5,0.5"
Text="Hello Universe!"
binders:SurrogateBind.Value="{Binding Path=MoreValues.Heading}" 
binders:SurrogateBind.Target="RenderTransform.Children.Item[1].Angle" >
<TextBox.RenderTransform>
<TransformGroup>
<ScaleTransform />
<RotateTransform />
</TransformGroup>
</TextBox.RenderTransform>
</TextBox>

This approach can actually be extended to invoke methods on your control. For instance when a value changes, you can trigger a storyboard to start playing etc. This is partly something we will get with Triggers in Silverlight 3.0, but if you can’t wait, this is one way to do it. Maybe I’ll cover this in a later blogpost. but for now you can download the source-code and example here:
 

Extending Silverlight’s mouse events

If you just want the extension method library or source, jump to the bottom. If not, read on…

Silverlight is pretty limited when it comes to mouse events. Out of the box, you only have five events you can subscribe to on a given element:

Notice that there is no such thing as click, double-click, drag, right-click and mouse-wheel.

Click and double click you can create from the up/down events. If the mouse doesn’t move between up and down, its a click, and if it happens two times within a timespan, it’s a double-click. Similarly, a drag is a click with mouse movement in-between down and up. Using extension methods, we can easily extent the UIElement class with two new methods for each event: Attach[eventname] and Detach[eventname], that takes care of this tracking. I earlier described this approach for defining a double click extension. These are all types of gestures we often need, so creating a reusable library with these extensions is a no-brainer.

When it comes to mouse wheel, it gets slightly trickier. We can’t do this using existing Silverlight events. Instead we can use the JavaScript bridge to detect wheel events in the browser, and bubble them into the plugin. First we listen to the JavaScript event on the entire plugin, and then inside Silverlight we use the Enter/Leave events to track whether the mouse is over the element you are listening to events on. However there are cases where this wouldn’t work:

  • The application is running in full screen.
  • The Silverlight plugin is running with HTML access explicitly disabled.
  • The .xap file is hosted on a different domain than the page hosting it.
  • You are running the application in Silverlight 3’s Out-of-browser mode.

All of them are cases where the JavaScript bridge is disabled.

Lastly right-click. This is a whole different story. When you right-click a Silverlight page, it will should you a small context menu with a link to the Silverlight settings. This can’t be overridden, but using the same approach as for Wheel, you can intercept the event using JavaScript and prevent the bubbling to the plugin. However this only works reliably in Internet Explorer, and most secondly only if you run the application in windowless mode.

UPDATE: Right-click now also work in Mozilla browsers. See here

I took all these events, and wrapped the, into a little set of extension method, so you don’t have to write the code over and over again.

To use it, download the library (link at the bottom) and add a reference to the DLL. Then at the top of the class where you want to use the event extensions, add the following to your using statements:

using SharpGIS.MouseExtensions;

When you have done this, you will instantly get new intellisense on any object that inherits from UIElement:

image

You will see seven new Attach* and Detach* methods:

Click Mouse/Down without moving the mouse
DoubleClick Two quick clicks
Drag Mouse down, move, mouse up. Event will fire for each mouse movement.
Hover If the mouse stops over an element and stays in the same place for a short time.
KeyClick Click while the user is holding down a key.
RightClick Windowless only!
Wheel Mouse wheel

You can see a live sample of it in action here.

Assembly Library that you can reference in your project: Download binary (7.14 kb)

Sourcecode and sample application is available here:Download source (24.79 kb)

REALLY small unzip utility for Silverlight

UPDATE: See this updated blogpost.

There are quite a few libraries out there that adds zip decompression/compression to Silverlight. However, common to them all is that they add significantly to the size of the resulting .xap.

It turns out that Silverlight 2.0 already has zip decompression built-in. It uses this to uncompress the .xap files which really just are zip files with a different file extension.

There are several blog posts out there that will tell you how to dynamically load a XAP file and load it. It turns out that if you use the same approach with almost any other zip file, you can actually do the same thing, even though this is not a Silverlight XAP. I don’t think this was the original intent. but its still really neat! Here’s how to accomplish that, based on a zip file stream:

public static Stream GetFileStream(string filename, Stream stream)
{
    Uri fileUri = new Uri(filename, UriKind.Relative);
    StreamResourceInfo info = new StreamResourceInfo(stream, null);
    StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(info, fileUri);
    if (streamInfo != null)
        return streamInfo.Stream;
    return null; //Filename not found or invalid ZIP stream
}

However, the problem is that this requires you to know before-hand what the names of the files are inside the zip file, and Silverlight doesn’t give you any way of getting that information (Silverlight uses the manifest file for reading the .xap).

Luckily getting filenames from the zip is the easy part of the ZIP specification to understand. This enabled us to create a generic ZIP file extractor in very few lines of code. Below is a small class utility class I created that wraps this all nicely for you.

public class UnZipper
{
    private Stream stream;
    public UnZipper(Stream zipFileStream)
    {
        this.stream = zipFileStream;
    }
    public Stream GetFileStream(string filename)
    {
        Uri fileUri = new Uri(filename, UriKind.Relative);
        StreamResourceInfo info = new StreamResourceInfo(this.stream, null);
        StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri);
        if(stream!=null)
            return stream.Stream;
        return null;
    }
    public IEnumerable<string> GetFileNamesInZip()
    {
        BinaryReader reader = new BinaryReader(stream);
        stream.Seek(0, SeekOrigin.Begin);
        string name = null;
        while (ParseFileHeader(reader, out name))
        {
            yield return name;
        }
    }
    private static bool ParseFileHeader(BinaryReader reader, out string filename)
    {
        filename = null;
        if (reader.BaseStream.Position < reader.BaseStream.Length)
        {
            int headerSignature = reader.ReadInt32();
            if (headerSignature == 67324752) //PKZIP
            {
                reader.BaseStream.Seek(14, SeekOrigin.Current); //ignore unneeded values
                int compressedSize = reader.ReadInt32();
                int unCompressedSize = reader.ReadInt32();
                short fileNameLenght = reader.ReadInt16();
                short extraFieldLenght = reader.ReadInt16();
                filename = new string(reader.ReadChars(fileNameLenght));
                if (string.IsNullOrEmpty(filename))
                    return false;
                //Seek to the next file header
                reader.BaseStream.Seek(extraFieldLenght + compressedSize, SeekOrigin.Current);
                if (unCompressedSize == 0) //Directory or not supported. Skip it
                    return ParseFileHeader(reader, out filename);
                else
                    return true;
            }
        }
        return false;
    }
}

Basically you create a new instance of the UnZipper parsing in the stream to the zip file. The method “GetFileNamesInZip” will provide you with a list of the file names available inside the file, that you can use to reference the file using “GetFileStream”.

Below is a simple example of using this. The contents of each file will be shown in a message box:

private void LoadZipfile()
{
    WebClient c = new WebClient();
    c.OpenReadCompleted += new OpenReadCompletedEventHandler(openReadCompleted);
    c.OpenReadAsync(new Uri("http://www.mydomain.com/myZipFile.zip"));
}
 
private void openReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    UnZipper unzip = new UnZipper(e.Result);
    foreach (string filename in unzip.GetFileNamesInZip())
    {
        Stream stream = unzip.GetFileStream(filename);
        StreamReader reader = new StreamReader(stream);
        string contents = reader.ReadToEnd();
        MessageBox.Show(contents);
    }
}

Note that some ZIP files which doesn't report file size before the file content is not supported by Silverlight, and is therefore also ignored by this class. This is sometimes the case when the zip file is created through a stream where the resulting file size is written after the compressed data. If you are dealing with those kind of zip files (seems fairly rare to me), you will need to use a 3rd party zip library that supports this.
UPDATE: See this updated blogpost.

This class will hardly add much to your resulting .xap, and I think it will cover 95% of the use cases when working with zip files.

Download class file: UnZipper.zip (1.25 kb)

Parsing a GeoRSS Atom feed using XML to LINQ in Silverlight

…or how to put a map of your blogposts on your blog.

I recently started a little pet project with a “photo a day” blog. I thought it could be fun to geocode each blogpost with to the place where each photograph was taken, and then place each photo on a map, similar to the flickr map I created earlier.

The most common way of geocoding an atom feed, is by adding a <georss:point>[latitude] [longitude]</georss:point> field for each entry. However, the blogengine I’m using currently doesn’t support that, so I will also try and find the location using a magic string in the blogpost, in this case “Location: [latitude] [longitude]”. You will notice that the posts I made so far, all have this at the end of the post. This might not be the most elegant solution to geocoding your blogposts, but it should work for any type of blog.

So the first step is to create a WebRequest that will download the feed (this could be simplified by using the WebClient, but I like the full control of the WebRequest):

System.Net.WebRequest request = System.Net.WebRequest.Create(
     new Uri("http://socaldaily.sharpgis.net/syndication.axd?format=atom", UriKind.Absolute));
request.BeginGetResponse(new AsyncCallback(createRssRequest), new object[] { request, this });

Begin get response handler:

private static void createRssRequest(IAsyncResult asyncRes)
{
      object[] state = (object[])asyncRes.AsyncState;
      System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest)state[0];
      Page page = (Page)state[1];
 
      if (!httpRequest.HaveResponse) { return; }
 
      System.Net.HttpWebResponse httpResponse = (System.Net.HttpWebResponse)httpRequest.EndGetResponse(asyncRes);
      if (httpResponse.StatusCode != System.Net.HttpStatusCode.OK) { return; }
      Stream stream = httpResponse.GetResponseStream();
      page.Dispatcher.BeginInvoke(() => { page.ParseAtomUsingLinq(stream); });
}

When the request comes back, it will call our ParseAtomUsingLinq method with the response stream. The LINQ expression will select basic parameters like title, date, link, contents and if available, the georss location point.

private void ParseAtomUsingLinq(System.IO.Stream stream)
{
    System.Xml.Linq.XDocument feedXML = System.Xml.Linq.XDocument.Load(stream);
    System.Xml.Linq.XNamespace xmlns = "http://www.w3.org/2005/Atom"; //Atom namespace
    System.Xml.Linq.XNamespace georssns = "http://www.georss.org/georss"; //GeoRSS Namespace
 
    //Use LINQ to select all entries
    var posts = from item in feedXML.Descendants(xmlns + "entry")
                select new 
                {
                    Title = item.Element(xmlns + "title").Value,
                    Published = DateTime.Parse(item.Element(xmlns + "updated").Value),
                    Url = item.Element(xmlns + "link").Attribute("href").Value,
                    Description = item.Element(xmlns + "summary").Value,
                    Location = fromGeoRssPoint(item.Element(georssns + "point"))  //Simple GeoRSS <georss:point>X Y</georss.point>
                };
     foreach (var post in postsOrdered)
     {
          ESRI.ArcGIS.Geometry.MapPoint point = null;
          if (post.Location != null)
          {
               point = post.Location; //Use GeoRSS location
          }
          else
          {
               point = ExtractLocation(post.Description); //Search for location in blog content
          }
          if (point == null) continue; //We didn't find a point
          string imageSrc = ExtractImageSource(post.Description, post.Url); //try and find an image to use for symbol
          //TODO: Add points to map...
     }
}

You will notice in the above code we use three utility methods for extracting data. First we have a method that converts the simple GeoRSS format “<georss:point>X Y</georss.point>” to a point. In this case I’m using the MapPoint class from the ESRI ArcGIS Silverlight API, since I wan’t to use that to draw my entries on the map.

private ESRI.ArcGIS.Geometry.MapPoint fromGeoRssPoint(System.Xml.Linq.XElement elm)
{
    if (elm == null) return null;
    string val = elm.Value;
    string[] vals = val.Split(new char[] { ' ' });
    if (vals.Length != 2) return null;
    double x = double.NaN;
    double y = double.NaN;
    if (double.TryParse(vals[1], out x) && double.TryParse(vals[0], out y))
    {
        return new ESRI.ArcGIS.Geometry.MapPoint(x, y);
    }
    return null;
}

If this doesn’t return any results (usually if the feed is not georss enabled), we will during the loop look for the location tag in the entry content, using the following helper method:

private ESRI.ArcGIS.Geometry.MapPoint ExtractLocation(string description)
{    
    int idx = description.LastIndexOf("Location: ");
    int idx2 = description.LastIndexOf("</p>");
    double x = double.NaN;
    double y = double.NaN;
    if (idx < idx2 && idx > -1)
    {
        string sub = description.Substring(idx, idx2 - idx);
        string[] vals = sub.Split(new char[] { ' ' });
        foreach (string val in vals)
        {
            if (val[0] == 'N')
            {
                double.TryParse(val.Substring(1), out y);
            }
            else if (val[0] == 'S')
            {
                if (double.TryParse(val.Substring(1), out y)) y *= -1;
            }
            else if (val[0] == 'E')
            {
                double.TryParse(val.Substring(1), out x);
            }
            else if (val[0] == 'W')
            {
                if (double.TryParse(val.Substring(1), out x)) x *= -1;
            }
        }
        if (!double.IsNaN(x) && !double.IsNaN(y))
        {
            return new ESRI.ArcGIS.Geometry.MapPoint(x, y);
        }
    }
    return null;
}

Lastly, we will search for the first <img src=”…”/> entry in the body and use that for displaying the entries on the map:

private string ExtractImageSource(string description, string feedlink)
{
    int idxSrc = description.IndexOf("<img ");
    if (idxSrc >= 0)
    {
        int idxSrc2 = description.Substring(idxSrc).IndexOf("src=\"");
        int idxSrc3 = description.Substring(idxSrc + idxSrc2 + 5).IndexOf("\"");
        if (idxSrc2 >= 0 && idxSrc3 >= 0)
        {
            string src = description.Substring(idxSrc + idxSrc2 + 5, idxSrc3);
            Uri uri = new Uri(src, UriKind.RelativeOrAbsolute);
            if (uri.IsAbsoluteUri) return uri.AbsoluteUri;
            Uri page = new Uri(feedlink, UriKind.Absolute);
            return new UriBuilder(page.Scheme, page.Host, page.Port, src).Uri.AbsoluteUri;
        }
    }
    return null;
}

In our feed entries loop, we can now simply construct a graphic, set a few attributes that we will use for binding the look for the symbol (ie title and image) and add it to our graphics layer. The symbol I use here is the same as used for the flickr application mentioned above.

ESRI.ArcGIS.Graphic g = new ESRI.ArcGIS.Graphic()
{
    Geometry = point,
    Symbol = myFeedSymbol
};
g.Attributes.Add("Title", title);
g.Attributes.Add("ImageURI", src);
g.Attributes.Add("WebURI", link);
myGraphicsLayer.Graphics.Add(g);

You can view the blog map in action here: http://socaldaily.sharpgis.net/page/Photo-map.aspx

Note that there are several ways to geocode blogposts, and this approach only deals with the simplest version.

ESRI ArcGIS Silverlight/WPF API released

FINALLY we released the beta of our new ArcGIS client API for Silverlight and WPF the end of this week.

You can download the beta here, where you also can find links to documentation and samples. Note that the download requires an ESRI global account, which you can create for free.

Art has the details on his blog.

This his has been (well still is since it's beta :-) a great fun project to work on. We tried to design it to be similar to our JavaScript and Flex APIs, but at the same time make it more ".NET" when it made sense, or taken advantage of capabilities Silverlight had. We really look forward to the feedback from you, as well as talking to anyone who's at the ESRI Developer summit next week. I'll be there Monday through Thursday, mostly hanging out at the showcase area, so if you're there, stop by say hi and get to see the API first hand. Art and Rex will be doing an intro session Wednesday at 1pm, and I'll join them Thursday 10:15am for the advanced session.

Below is a simple flickr application that I created for the api, (source is available for download at the code gallery). Just zoom to any area of interest, hit the flickr button, and images in that area pops up. The sample demonstrates the power of templating the symbols which allows you to associate animations to states of the symbols, as well as using binding. This is really no different than the states model used in other Silverlight controls. The flickr symbols here has two states: MouseOver, which zooms the image and displays a small description at the bottom. The result box to the left uses the selection state when you hover on the features to first scale the image slightly and highlight the border, and if you stay hovering on it, will expand to full size. Click the result to center on that feature.

Silverlight 3.0 Pixel shaders

rippleeffect Silverlight 3.0 beta1 was released today. One of the new cool features is the pixel shader support, allowing you to make some really cool effects. I managed to fairly quickly convert the WPF Pixel Shader library to a Silverlight library (except a couple of effects), and successfully apply them to any UIElement.

To save you the trouble, you can grab the source for the library from here: ShaderEffectLibrary.zip (44.65 kb)

To use it, simply import the assembly namespace:

xmlns:fx=”clr-namespace:ShaderEffectLibrary;ShaderEffectLibrary"

and then apply any effect to your elements by setting the Effect property:

<Grid>
    <Grid.Effect>
        <fx:RippleEffect />
    </Grid.Effect>
</Grid>

The supported effects are: BandedSwirl, Bloom, BrightExtract, ColorKeyAlpha, ColorTone, ContrastAdjust, DirectionalBlur, Embossed, Gloom, GrowablePoissonDiskEffect, InvertColor, LightStreak, Magnify, Monochrome, Pinch, Pixelate, Ripple, Sharpen, SmoothMagnify, Swirl, Tone, Toon, and ZoomBlu.

Note that you will need to have the Silverlight 3.0 bits installed to use this.

UPDATE: The WPF Pixel Shader library has now added support for Silverlight as well: http://wpffx.codeplex.com/

Also note that if you want to take advantage of the new GPU hardware acceleration to further enhance performance, this is an opt-in feature! To get it, you have to go to the hosting html page and set the following object parameter (update: This doesn't apply to pixel shaders which are software only):

      <param name=”enableGPUAcceleration” value=”true” />

Also note that pixel shaders are software only, and if you add a shader to your hardware accelerated element, it will switch back to software.

Silverlight and WPF code reuse pitfalls.

The idea is really great: Write your code once, and reuse it across all your platforms. This is one of the great things about .NET. I can reuse business logic in ASP.NET, Mobile, Desktop, Embedded devices, Phones, Web services and so on. Usually the only difference is the UI that behaves a little different on the various platforms.

With WPF and Silverlight, even the UI code can be reused between Desktop and Web, since Silverlight is a subset of WPF. That means that any Silverlight code should be able to run in a WPF application, right? Well at least that’s what Microsoft keeps telling us, and you will fine numerous blog posts discussing it. However, in reality it’s not that straight forward. I’ve been trying to reuse some Silverlight code in a WPF application, and ran into a lot of headaches. What I found is that Silverlight is NOT a subset of WPF and .NET. It is a completely new framework with the subset as a design goal, but Microsoft made several mistakes, some even so bad that fixing it in either WPF or Silverlight would cause a breaking change. In other cases the XAML syntax is incompatible different. This means that you won’t get around using several compiler conditionals and duplicate XAML files.

Below is a list of some of the things I’ve run into, and I’ll try and add to it if I found more. I you know of more, or find errors or explanation to differences please add comments below.

For code that is only for Silverlight I have declared a SILVERLIGHT compiler conditional. so anything inside a #if SILVERLIGHT block is Silverlight only code, and vice verse if it’s in #if !SILVERLIGHT or #else it’s for WPF.

As a side note, the following blog posts discusses some good practices for reusing the same code files in your WPF and Silverlight projects: Sharing source code between .NET and Silverlight. However it hardly deals with code differences like the ones below.

Loading a bitmap

Loading bitmaps are probably one of the biggest differences in the two frameworks (that I’ve seen). In WPF you must call BeginInit and EndInit, and checking for download errors are very different, which requires you to use two different handlers for handling an image load error.

BitmapImage bmi = new BitmapImage();
#if 
!SILVERLIGHTbmi.BeginInit();
#endif
Image img = new Image();
bmi.UriSource = new Uri(url, UriKind.Absolute);
#if
SILVERLIGHTimg.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(img_ImageFailed); //Silverlight specific error handler
#else
bmi.DownloadFailed += new EventHandler<System.Windows.Media.ExceptionEventArgs>(bmi_DownloadFailed); //WPF specific error handler
bmi.EndInit();
#endif
img.Source = bmi;

Modifying Animations

WPF is very restrictive when it comes to working with animations. When you initialize the animation, you must use an overload that takes the element you are modifying as well as specifying that its modifiable. Silverlight doesn’t have any of these overloads, and is there fore not required.

#if SILVERLIGHT
myStoryboard.Begin();
myStoryboard.Stop();
#else
myStoryboard.Begin(element, true); //true allows for changing animation later
myStoryboard.Stop(element); //element parameter required when Begin was called with element
#endif

Delay Signing

Silverlight does not support delay signing of your assemblies. This might not be a big issue for you though.

Binding to Dictionary

This is more of a subset limitation, but it’s an annoying one, that is fairly tricky to get around.

In WPF you can bind a Dictionary<string,object> object as simple as :

<TextBlock Text="{Binding Path=MyDictionary.[KeyName]}" />

However in Silverlight you have to create your own value converter:

public class DictionaryItemConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
   var dict = value as Dictionary<string, string>;
   if (dict != null)
   {
     return dict[parameter as string];
   }
     throw new NotImplementedException();
   }
   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
     throw new NotImplementedException();
   }
}

Using the converter you can then bind your dictionary:

<Grid x:Name="LayoutRoot" Background="White">
    <Grid.Resources>
   <local:DictionaryItemConverter x:Name="myDictConvert" />
    </Grid.Resources>
    <TextBlock Text="{Binding Converter={StaticResource myDictConvert}, ConverterParameter=KeyName}" />
</Grid>

(note that you will have to define the local: namespace to point to the namespace/assembly where DictionaryItemConverters is placed).

Value converters are pretty powerful though, so this lesson might come in handy later. This approach does work for WPF too.

Accessing resources declared in XAML from code

Accessing resources you have in your XAML is a common pitfall. If I were to declare a resource in a grid like this:

<Grid x:Name="LayoutRoot">
    <Grid.Resources>
   <local:MyClass x:Key="myResource" />
    </Grid.Resources>
</Grid>

In WPF you would access it like this:

object o = LayoutRoot.Resources["myResource"];

However in Silverlight that would return null! Instead in Silverlight you have to use x:Name instead of x:Key in your XAML:

<local:MyClass x:Name="myResource" />

Unfortunately in Silverlight you can’t declare both a Key and a Name in your XAML (you can in WPF), so you will have to maintain two different XAML files. In WPF you are required to specify a x:Key attribute, so you can’t just make do with the name attribute either.

Control Templates

When you create a control template, you will have to assign the type that the control template belongs to. Here’s the syntax in Silverlight:

<ControlTemplate TargetType="local:MyControl">

And in WPF:

<ControlTemplate TargetType="{x:Type local:MyControl}">

Debug.WriteLine

This one is a little interesting, because it's a method in Silverlight that proves that it’s not necessarily a subset of WPF, since here’s a method that actually have different overloads in Silverlight and WPF. I often use System.Diagnostics.Debug.WriteLine to write out values or warnings that I or the developer should be aware of, but not necessarily is an error.

Here are the overloads in Silverlight:

public static void WriteLine(object value);
public static void WriteLine(string message);
public static void WriteLine(string format, params object[] args); //NOT IN WPF! 

and WPF:

public static void WriteLine(object value);
public static void WriteLine(string message);
public static void WriteLine(object value, string category);
public static void WriteLine(string message, string category); 

Notice that the 3rd method in Silverlight which is equivalent of using string.Format, doesn’t exist in WPF. Therefore always use WriteLine(string.Format(format,args)) instead.

OnApplyTemplate fired in different order

The OnApplyTemplate call on your controls are fired at different times in WPF and Silverlight. This can cause a lot of problems if you rely on certain events to have happened before the OnApplyTemplate event has triggered, or vice versa. This is a case where you have to be really careful with code-reuse in Silverlight and WPF.

In the example below I created a simple sample and ran it in Silverlight and WPF, with breakpoints in each loaded handler, constructor and OnApplyTemplate in my custom control.  The XAML is below (simplified and removed namespace declarations for readability):

<UserControl Loaded="UserControl_Loaded”>     <my:Control Loaded="MyControl_Loaded /> </UserControl>

Order the methods were hit:

  Silverlight WPF
1. UserControl Constructor UserControl Constructor
2. MyControl Constructor MyControl Constructor
3. MyControl Loaded MyControl.OnApplyTemplate
4. UserControl Loaded UserControl Loaded
5. MyControl.OnApplyTemplate MyControl Loaded

See this post for a workaround.

Case sensitivity

Silverlight in general seems less restrictive when it comes to your XAML. For instance case sensitivity. I was recently trying to use a class modifier on my UserControl using the following:

<UserControl x:ClassModifier=”Internal”>

However this doesn’t work in WPF. It turns out that the “internal” keyword must be lowercase in WPF.

--------------------------

Jeff Wilcox also has a list of issues that he hit in his gravatar project described in this blog post: http://www.jeff.wilcox.name/2009/03/gravatar-control/

Doubleclicking in Silverlight

Mike Snow recently posted an article on how to do double clicks in Silverlight. However, his approach isn't very reusable, doesn't allow for multiple listeners and doesn't check to see if the mouse moved between the two clicks. Below is my solution, which uses extension methods and attached properties to track clicks and event handlers.

To use it, first include the namespace in your code:

using MyApplication.Extensions;

This will add AddDoubleClick and RemoveDoubleClick methods to any UIElement. You can then add an event handler to your element like so:

MyDblClickElement.AddDoubleClick(MyDblClickElement_MouseDoubleClick);

The double click handler signature is the same as for mouse down. Example:

private void MyDblClickElement_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
Point position = e.GetPosition(this);
MessageBox.Show(string.Format("dblclick at {0},{1}", position.X, position.Y));
} 

Here's the code:

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace MyApplication.Extensions
{
public static class Mouse
{
private const int doubleClickInterval = 200;
private static readonly DependencyProperty DoubleClickTimerProperty = DependencyProperty.RegisterAttached("DoubleClickTimer", typeof(DispatcherTimer), typeof(UIElement), null);
private static readonly DependencyProperty DoubleClickHandlersProperty = DependencyProperty.RegisterAttached("DoubleClickHandlers", typeof(List<MouseButtonEventHandler>), typeof(UIElement), null);
private static readonly DependencyProperty DoubleClickPositionProperty = DependencyProperty.RegisterAttached("DoubleClickPosition", typeof(Point), typeof(UIElement), null);
/// <summary>
/// Adds a double click event handler.
/// </summary>
/// <param name="element">The Element to listen for double clicks on.</param>
/// <param name="handler">The handler.</param>
public static void AddDoubleClick(this UIElement element, MouseButtonEventHandler handler)
{
element.MouseLeftButtonDown += element_MouseLeftButtonDown;
List<MouseButtonEventHandler> handlers;
handlers = element.GetValue(DoubleClickHandlersProperty) as List<MouseButtonEventHandler>;
if (handlers == null)
{
handlers = new List<MouseButtonEventHandler>();
element.SetValue(DoubleClickHandlersProperty, handlers);
}
handlers.Add(handler);
}
/// <summary>
/// Removes a double click event handler.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="handler">The handler.</param>
public static void RemoveDoubleClick(this UIElement element, MouseButtonEventHandler handler)
{
element.MouseLeftButtonDown -= element_MouseLeftButtonDown;
List<MouseButtonEventHandler> handlers = element.GetValue(DoubleClickHandlersProperty) as List<MouseButtonEventHandler>;
if (handlers != null)
{
handlers.Remove(handler);
if(handlers.Count == 0)
element.ClearValue(DoubleClickHandlersProperty);
}
}
private static void element_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
UIElement element = sender as UIElement;
Point position = e.GetPosition(element);
DispatcherTimer timer = element.GetValue(DoubleClickTimerProperty) as DispatcherTimer;
if (timer != null) //DblClick
{
timer.Stop();
Point oldPosition = (Point)element.GetValue(DoubleClickPositionProperty);
element.ClearValue(DoubleClickTimerProperty);
element.ClearValue(DoubleClickPositionProperty);
if (Math.Abs(oldPosition.X - position.X) < 1 && Math.Abs(oldPosition.Y - position.Y) < 1) //mouse didn't move => Valid double click
{
List<MouseButtonEventHandler> handlers = element.GetValue(DoubleClickHandlersProperty) as List<MouseButtonEventHandler>;
if (handlers != null)
{
foreach (MouseButtonEventHandler handler in handlers)
{
handler(sender, e);
}
}
return;
}
}
//First click or mouse moved. Start a new timer
timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(doubleClickInterval) };
timer.Tick += new EventHandler((s, args) =>
{  //DblClick timed out
(s as DispatcherTimer).Stop();
element.ClearValue(DoubleClickTimerProperty); //clear timer
element.ClearValue(DoubleClickPositionProperty); //clear first click position
});
element.SetValue(DoubleClickTimerProperty, timer);
element.SetValue(DoubleClickPositionProperty, position);
timer.Start();
}
}
}

Impressions from Microsoft PDC

I attended the Microsoft PDC in Los Angeles Convention Center this week, and here's a recap of various statements, quotes and sessions that I found interesting.

 

WCF Preconference notes

It looks like a class, it feels like a class, it smells like a class, it works like a class – but it’s a service!

This was a full day seminar on Windows Communication Foundation. It was very cool to see how ordinary looking classes could be turned into WCF services that can be exposed through a multitude of protocols using just two class/method attributes. One of the interesting statements were how .NET had replaced COM 7 years after its introduction, and now 8 years later, WCF is replacing .NET (well at least the part that replaced COM). Or to put it in the presenters word: ".NET as you know it is dead!"

WCF is host agnostic. No difference between hosting on IIS, in-proc, self-hosting, Windows Activation Service etc.

Possible transport protocols: HTTP, HTTPS, TCP, P2P, IPC, MSMQ.
Possible message formats: Plain text, Binary, MTOM.
Security options: None, Transport security, Message security, Authentication and authorizing callers.

WCF is the first platform that provides Interoperability, Productivity/Quality AND Extensibility all at once.

Favorite sessions

I must admit that many of the sessions were a little dissappointing. They were often marked as advanced or expert level, but rarely lived up to that. There were also way too many Twitter demos. But having said that, here are the ones I attended that didn't dissappoint. You can watch them all online by clicking the links next to them or see the whole list of sessions here.

  • TL16: "The Future of C#" by Anders Hejlsberg. My Danish hero and the brain behind C# talks about where C# is headed with upcoming v4 and 5 of C#. View
  • TL49: "Microsoft .NET Framework: Overview and Applications for Babies" by Scott Hanselman. Using a a wide varity of .NET core technologies, Scott takes his BabySmash application and ports it to WPF, Silverlight, Mobile and Surface, in his usual entertaining way. Great demonstration of the power of .NET. View
  • PC06: "Deep Dive: Building an Optimized, Graphics-Intensive Application in Microsoft Silverlight" by Seema Ramchandani. Seema goes through all the gory internal details of how Silverlight works and uses this knowledge to present a great set of tips and tricks to making the performance of your Silverlight applications scream. A must-see if you are doing serious work with Silverlight. View
  • TL26: "Parallel Programming for Managed Developers with the Next Version of Microsoft Visual Studio" by Daniel Moth. Processors are not really getting much faster anymore, but instead we get more and more cores to work with, but this also requires us to start changing the way we make software. The Parallel Framework that comes in .NET 4 makes this task really easy. All I can say is that this framework rocks! View
  • BB24: "SQL Server 2008: Deep Dive into Spatial Data" by Isaac Kunen. Isaac's deep dive on the spatial support in SQL Server (thanks for the plug Isaac :-). View
  • PC29: "Microsoft Silverlight 2: Control Model" by Karen Corby. Good information on how to build reusable, skinnable controls for Silverlight. View
  • PC32: "ASP.NET AJAX Futures" by Bertrand Le Roy. Upcoming features for ASP.NET AJAX. View
  • TL46: "Microsoft Visual C# IDE: Tips and Tricks" by Dustin Campbell. LOTS of great shortcuts and features in Visual Studio that you never knew was there and you wonder how you could ever live without. MUST SEE if you want to be more efficient when coding C# in Visual Studio. View
There were a lot of sessions I didn't make it to, but hopefully I'll get some time to view them online over the next coming weeks. If I see anything more that I like, I'll update this list. If you have watched any good sessions as well, please feel free to mention it in the comments.

 

My favorite comment was Juval Lowy's reaction when he the first time heard that Microsoft was working on the successor to VB6:

Giving VB developers access to a multithreaded environment (VB.NET) is like giving razorblades to babies.

It’s not that C++ developers are better off with C#, but they are more used to seeing blood.

 

Microsoft is already planning a new PDC next year November 17-20, 2009 (unfortunately same place).

IE8beta1 and Silverlight 2.0 beta 1 available

Reporting live from the Mix08 conference in Vegas :-)

Internet Explorer 8 beta1 and Silverlight 2.0 beta1 will be available from today !

IE8 comes with a much improved Developer tool with full debugger and style tracing, CSS2.1 and HTML5 support. You better get testing in IE8, because your existing website might be broken in IE8 (since it now finally follows the standards).

Silverlight will also be available for Mobile, and is supported by Nokia who will add it to their S40 and S60 series. You can already see a mobile silverlight app here: silverlight.weatherbug.com. This app was developed in less than 3 weeks and works cross-platform, cross-browser, cross-mobile, cross...