Monthly Archives: November 2008

Serialization in Silverlight

I am working on a project were we have a challenge seeing that I work most of the week from my home office. The problem is that due to security at the location, there is no way to access the database we’re working with through VPN or similar. I can’t take the database from the site either. So, we need to have some sort of fake version of the data so that I can get my job done.

My initial idea was to just have a local SQL database, seeing that our Silverlight application is connecting through a servicelayer and we could pretty much just change the connectionstring. But that is jus too easy. 🙂  I started looking at how I could have data stored within the Isolated Storage and serialize data back and forth from this. It will be handy for other parts of the project, so it wouldn’t be a complete waste.

Anyhow, the XmlSerializer one is familiar with from the desktop framework is not present in the Silverlight scaled down version of the framework. But, since the WCF support in Silverlight supports SOAP, it must be able to serialize and deserialize stuff back and forth across the wire. There is a class called DataContractSerializer that does the job. Only thing is, everywhere I looked and samples I came across, they claimed you had to decorate whatever object you wanted to work with, with [DataContract] for the class and [DataMember] for the members. This actually proves to not be the case, which is just brilliant for my case.

The result is that I made a couple of helper methods to do it all.

[code:c#]
        public string Serialize<T>(T data)
        {
            using (var memoryStream = new MemoryStream())
            {
                var serializer = new DataContractSerializer(typeof (T));
                serializer.WriteObject(memoryStream, data);

                memoryStream.Seek(0, SeekOrigin.Begin);

                var reader = new StreamReader(memoryStream);
                string content = reader.ReadToEnd();
                return content;
            }
        }

        public T Deserialize<T>(string xml)
        {
            using( var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml)) )
            {
                var serializer = new DataContractSerializer(typeof (T));
                T theObject = (T)serializer.ReadObject(stream);
                return theObject;
            }
        }
[/code]

A sample with a couple of classes:

[code:c#]
    public class WorkPosition
    {
        public double PositionSize { get; set; }
    }

    public class Employee
    {
        public Employee()
        {
            this.WorkPositions = new WorkPosition[]
                                     {
                                        new WorkPosition {PositionSize=50d},
                                        new WorkPosition {PositionSize=25d},
                                        new WorkPosition {PositionSize=25d},
                                     };
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }

        public WorkPosition[] WorkPositions { get; set; }
    }

    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();

            var employee = new Employee {FirstName = “John”, LastName = “Doe” };

            string xml = this.Serialize(employee);

            var deserializedEmployee = this.Deserialize<Employee>(xml);
        }
    }

[/code]

Silverlight Extension Methods

Every so often I find myself needing some helpers to make my development experience better when dealing with different Silverlight related objects, and every now and then I gather these into extensions methods – as I find that convienient.

Lately I've been doing quite a bit of control development, both custom controls and user controls, during this development I deal a lot with storyboards and visual states. Here's the source for a couple of extension methods I find handy.

Finding a storyboard for a specific visual state
When dealing with visual states, I tend to want to modify content of the storyboard programatically or I want on occasion to hook up to the completed event to be notified when the transition to the new state is finished. To do this, we need to get the storyboard. The below code is something I use for UserControls and is relying on the existense of a Control called "LayoutRoot". This could be rewritten  to extend Control and you could work the layoutroot instead of the UserControl.

[code:c#]
        public static Storyboard GetStoryboardForState(this UserControl control, string stateName)
        {
            Storyboard stateStoryboard = null;

            var root = control.FindName("LayoutRoot") as FrameworkElement;
           
            var groups = VisualStateManager.GetVisualStateGroups(root);
            foreach (VisualStateGroup group in groups)
            {
                foreach (VisualState state in group.States)
                {
                    if (state.Name == stateName)
                    {
                        stateStoryboard = state.Storyboard;
                    }
                }
            }
            return stateStoryboard;
        }
[/code]

Hooking up to the storyboard completed event for a transition for a state change
As mentioned above, I like to hook up to the storyboard completed event to know when a storyboard of a transition between two states is finished. This can be done by using the above code and the following:

[code:c#]
        public static void AddStateCompletedEventHandler(this UserControl control, string stateName, EventHandler stateChanged)
        {
            Storyboard stateStoryboard = control.GetStoryboardForState(stateName);
            if (null != stateStoryboard && null != stateChanged)
            {
                stateStoryboard.Completed += (s, e) => stateChanged(s, new EventArgs());
            }
        }
[/code]

Setting a value for a specific named keyframe within a storyboard
Storyboards within a visual state is not programatically accessible, even though you through in the x:Name="" attribute. Therefor I created a helper for setting a specific value – this one only supports doubles, seeing that was the only datatype I was using for the controls I was developing. Extending this should be fairly simple.

[code:c#]
        public static void SetValueForKeyFrame(this Storyboard storyboard, string keyFrameName, double value)
        {
            foreach (var timeline in storyboard.Children)
            {
                if (timeline is DoubleAnimationUsingKeyFrames)
                {
                    var animation = timeline as DoubleAnimationUsingKeyFrames;
                    foreach (var keyframe in animation.KeyFrames)
                    {
                        string name = keyframe.GetValue(FrameworkElement.NameProperty) as string;
                        if (null != name && name == keyFrameName)
                        {
                            keyframe.Value = value;
                            return;
                        }
                    }
                }
            }           
        }
[/code]

Convienience methods for changing states for a UserControl
Instead of working directly with the VisualStateManager, I like to do "this.GoToState(…)" on my UserControls. Again, the below code is for user controls, but could just as easily be for a custom control. Combining all of the above and the code below will give you this convience.

[code:c#]
        public static void GoToState(this UserControl control, string stateName, EventHandler stateChanged)
        {
            GoToState(control, stateName, true, stateChanged);
        }

        public static void GoToState(this UserControl control, string stateName, bool useTransitions, EventHandler stateChanged)
        {
            Storyboard stateStoryboard = control.GetStoryboardForState(stateName);
            if (null != stateStoryboard && null != stateChanged)
            {
                stateStoryboard.Completed += (s, e) => stateChanged(s, new EventArgs());
            }
            VisualStateManager.GoToState(control, stateName, useTransitions);
        }

        public static void GoToStates(this Control control, params string[] stateNames)
        {
            GoToStates(control, true, stateNames);
        }

        public static void GoToStates(this Control control, bool useTransitions, params string[] stateNames)
        {
            foreach (string name in stateNames)
            {
                VisualStateManager.GoToState(control, name, useTransitions);
            }
        }
[/code]

Last stop for my Silverlight roadtrip this year; IKT Grenland

On the 27th of November, IKT Grenland in Porsgrunn Norway is hosting their developer forum. They’ve invited me to hold a talk about Silverlight 2 and why one should use this technology.

If you’re Porsgrunn and want to catch “the wind” of Silverlight, don’t hesitate to register for the event here.

Silverlight evening at NNUG Kristiansand, 26th of November

I will be holding an all Silverlight evening at NNUG Kristiansands next user group meeting.

The meeting will be in two sections; basics of Silverlight and using expression blend together with Visual Studio to create your solutions. The second part will dwell into more advanced features and how it all fits in your enterprise development.

If you happen to be in the neighbourhood and feel like getting some Silverlight goodness, don’t hesitate to sign up here.

NNUG Vestfold User Group Meeting, 19th of November

We’re having a really exciting evening on wednesday the 19th of November at NNUG Vestfold.

Gøran Kvarv and Tore Vestues, both from Objectware, are coming to talk about WPF and Boo.

This is the first time we’re holding the user group meeting out of the Notus / Visma location we’ve been till this point. We’ll be having the meeting at this location.

To read more about the meeting and how to sign up for it, please have a look here.

NNUG Vestfold User Group Meeting, 19th of November

We’re having a really exciting evening on wednesday the 19th of November at NNUG Vestfold.

Gøran Kvarv and Tore Vestues, both from Objectware, are coming to talk about WPF and Boo.

This is the first time we’re holding the user group meeting out of the Notus / Visma location we’ve been till this point. We’ll be having the meeting at this location.

To read more about the meeting and how to sign up for it, please have a look here.

Xna 3.0 is out

Finally the news of Xna 3.0 struck me as well. Its been some days since the release of Xna 3.0, but with a hectic schedule I am not always fitting in time to read my RSS feeds. Anywho, he Xna team delivers, again. Finally, the release of version 3.0 of Xna is out. A lot of new features is included in this release. To mention a few:

* Visual Studio Integration : Support for C# 3.0, LINQ
* Try before you buy: You can allow your customers to try your game before they buy it
* Invitations: You can programatically allow players to invite friends to join their game
* In addition Windows and Xbox 360, there is now Zune support (when will Europe get this?)
* OneClick deployment of Windows Games

If you want to get started with Xna 3.0, start at this location.

For more details on the release of Xna 3.0 go here.

Compiler extensions is just another framework

Over the years I’ve had several issues where I’ve longed for ways to better express my code that I felt that the language should have exposed grammar for me to make it more readable. Just like LINQ introduces an internal DSL, I’ve had quite a few cases were I also wanted to introduce my own internal DSL. Very often one ends up with working around it and do creative frameworks or libraries that helps doing the same thing without really solving the expressiveness.

I come to realize more and more that the programming language one chose is less important than the frameworks one use. As long as one can express the code the way one wants and perhaps even in a suitable manner for the domain you’re working in, the choice of language is really not important.

Attributes
Attributes in C# are great for expressiveness, they are great at providing additional meta information for classes, fields and properties. Often I find myself using attributes for expressing business rules and having evaluation code for classes that recognise the attributes and then validates according by calling the different validation attributes applied. In my opinion, this is a bit unnatural. A lot of the attributes found in the .net framework acts as more than just meta information at compiletime. The compiler recognizes a whole bunch of the framework attributes and alters the behavior of the execution accordingly.
Ofcourse, everything that could be solved at compiletime could certainly also be solved at runtime, but it affects runtime speed and scalability.

Modifying IL code
PostSharp is a project that solves this; one can alter the IL code generated after compilation and then commit it to the assembly. Attributes is a part of the language and with PostSharp we could solve this problem and we don’t need to extend the compiler.

Plumbing
Another good place were you’d might look at having compiler extensions are the places were you are basically just plumbing to make things work with how a framework wants it to work. A good candidate would be for instance the INotifyPropertyChanging and INotifyPropertyChanged interfaces were you basically are just doing the same code over and over again for all your properties. With a compiler extension you could plumb all this automatically.

Typically you would do the following:

[code:c#]
public class MyNotifyingObject : INotifyPropertyChanging
{
    public event PropertyChangedEventHandler PropertyChanging;

    protected virtual void OnPropertyChanging(string propertyName)
    {
       if( null != this.PropertyChanging )
       {
          this.PropertyChanging(this,new PropertyChangedEventArgs(propertyName));
       }
    }

    public string Name
    {
       get
       {
          return this._name;
       }

       set
       {
          if ((this._name != value))
          {
             this.OnPropertyChanging(“Name”);
             this._name = value;
             this.OnPropertyChanged(“Name”);
          }
       }
    }
}
[/code]

A more expressive way could be:

[code:c#]
public class MyNotifyingObject
{
    public notify string Name { get; set; }
}
[/code]

If you ever worked with WPF or Silverlight, you know the tedious parts where you want to have DependencyProperties on your controls. The syntax is like this:

[code:c#]
public static readonly DepedencyProperty MyStringProperty =
                  DependencyProperty.Register(“MyString”, typeof(string), typeof(ParentType), null);

public string MyString
{
     get
     {
           return this.GetValue(MyStringProperty);
     }
     set
     {
           this.SetValue(MyStringProperty,value);
     }
}
[/code]

Wouldn’t it be a lot more expressive if we could just do:

[code:c#]
public dependent string MyString { get; set; }
[/code]

The way a compiler extension would handle this, is to fill in all the code found above to make it all work like if you were to write it all. We would get a more expressive code and actually get rid of potential problems with the literal declaring the name of the property as we do today.

C# 4.0

During PDC there’s been a bit talk about C# 4.0 and further down the pipeline, Anders Hejlsberg talked about the new static type called dynamic, that will help us out getting more dynamic. I for one has been quite the skeptic over the years about dynamic languages, but I must admit that in many cases it is really convienient. My conclusion is that this is a really great step forward for the language.

Boo
The programming language Boo is a static language that can be dynamically altered by introducing new keywords into the language through compiler extensions. In addition to the compiler they’ve created a small framework that enables the developer to take part of the compilation and modify the AST. This feels very great and gives us developers the power we need to really express our code and give our programming model a domain specific feel. A colleague of mine; Tore Vestues blogs about Boo and all its glory. Have a look here.

Boo is great, but has a couple of obstacles before it will be embraced as a mainstream programming language by a lot of developers; syntax is one – even though I claim that the language shouldn’t really matter, it sort of does. If you are familiar with the C syntax of C++,Java,C#, JavaScript, then the chances are that you’d feel that swithching to a new language is too big and you fall back. So, what about C# – if this is so great, why aren’t we seeing this in C#? It is for sure, technically possible. At PDC there was a great panel on the future of programming languages where this among a ton of subjects was discussed. My impression was that Anders Hejlsberg was quite clear on this subject; they didn’t want to open it all up because of the danger of devolving the language. I think this is really sad, I really hope they turn around on this. After all, as the title of this post claims; it is basically just another framework. By extending the language, and doing it like Boo has done it, wouldn’t pose a threat to the language. The extensions one would build would in many cases be solving a domain specific problem and just act as just another framework one used to solve that problem.

Compiler Extensions – how
A compiler extension, would need access to the AST tree created during compile time and based upon the code and any extensions found extend the existing tree. Boo solves this in
a very graceful manner, the extensions are just part of your code as you compile or you can put them in a component. It is really not that intrusive as it might sound. We’re not talking about creating a whole new version of the language, rather than introducing domain specific problem-solvers or aiding in creating more expressiveness. In addition to compiler extensions, one need to hook into the IDE to get rid of all the errors one would get thrown in your face while writing code.