Silverlight serialization with MobileObject

Silverlight serialization with MobileObject

Old forum URL: forums.lhotka.net/forums/t/9891.aspx


Mudbugz posted on Monday, December 20, 2010

The Silverlight FAQ page (http://www.lhotka.net/cslanet/faq/SilverlightFaq.ashx) has a link to a Silverlight serialization page (http://www.lhotka.net/weblog/SilverlightSerializer.aspx) that has an example of how to use MobileObject for criteria classes in Silverlight 2.0.

In Csla 4.0.1, MobileObject doesn't have a GetValue() or SetValue() method to override. Getting and setting each individual property in OnGetState() and OnSetState() is no fun.  So, I've create a base class that inherits from MobileObject that does the work for me.

Example criteria class:

[Serializable()]
public class Person: DataPortalCriteria
{
 public string FirstName { get; set; }
 public string LastName {get; set;}
 public Guid Id { get; set; }
 public string LoginName { get; set; }
}

Serialize properties using reflection:

[Serializable()]
public class DataPortalCriteria : MobileObject
{
 private static List<PropertyInfo> lstProperties;

 protected List<PropertyInfo> GetProperties()
 {
  if (lstProperties == null)
  {
   lstProperties = new List<PropertyInfo>();

   PropertyInfo[] pis = this.GetType().GetProperties();
   foreach (System.Reflection.PropertyInfo pi in pis)
    lstProperties.Add(pi);
  }

  return lstProperties;
 }

 protected override void OnGetState(Csla.Serialization.Mobile.SerializationInfo info, StateMode mode)
 {
  foreach (PropertyInfo pi in GetProperties())
   info.AddValue(pi.Name, pi.GetValue(this, null));
 }

 protected override void OnSetState(Csla.Serialization.Mobile.SerializationInfo info, StateMode mode)
 {
  foreach (PropertyInfo pi in GetProperties())
   pi.SetValue(this, info.GetValue<object>(pi.Name), null);
 }
}

RockfordLhotka replied on Monday, December 20, 2010

That is a good idea for your purpose. However, this only works because your properties are public. Silverlight will block non-public reflection.

Our base classes are designed to support normal CSLA business types - where you can't just access the properties because that'd trigger business and authorization rules. So normally you have to access the fields, not the properties. And fields are almost always non-public, so reflection won't work.

You could create a MobileDto base class though, because what you are doing is creating a DTO that you want to be serializable through the data portal. As long as the DTO only has public read-write properties with no business logic this would work pretty well.

Copyright (c) Marimer LLC