Sample:Passing a generic dictionary from Silverlight Client to ServerSample:Passing a generic dictionary from Silverlight Client to Server
Old forum URL: forums.lhotka.net/forums/t/6624.aspx
mamboer posted on Wednesday, March 18, 2009
A few hours ago,Rocky made a little fix on the Cals.Core.MobileDictionary<K,V>,now it can be serialized/deserialized correctly by both BinaryFormatter and Csla's MobileFormatter,although it has come restrictions on the generic parameters' type(type of K&V),it should work if both of your K&V,
1,are a primitive type such as int,string,etc.
2,have implemented the IMobileObject interface.
Now,i will define a custom criteria class,add a MobileDictionary<string,object> property to it,and then pass it from SL client to Server
Below is my criteria class:
[Serializable]
public class DicCriteria : CriteriaBase {
public DicCriteria():this(null) {
}
public DicCriteria(Dictionary<string,object> value) {
if (value == null)
_Value = new MobileDictionary<string, object>();
else
{
_Value = new MobileDictionary<string, object>(value);
}
}
private MobileDictionary<string, object> _Value;
public MobileDictionary<string, object> Value
{
get {
return _Value;
}
private set {
if (_Value != value)
_Value = value;
}
}
public DicCriteria Add(string key, object value)
{
if (!_Value.ContainsKey(key))
{
_Value.Add(key, value);
}
return this;
}
protected override void OnGetState(Csla.Serialization.Mobile.SerializationInfo info, StateMode mode)
{
//Note:Must serialize your MD property to byte[]
//before adding to the info,because MF will new a
//DataContractSerializer for
//List<SerializationInfo> type
//to do the serialization,and your
//MobileDictionary is not a known type to it.
info.AddValue("_Value", MobileFormatter.Serialize(_Value));
base.OnGetState(info, mode);
}
protected override void OnSetState(Csla.Serialization.Mobile.SerializationInfo info, StateMode mode)
{
_Value = MobileFormatter.Deserialize((byte[])info.Values["_Value"].Value) as MobileDictionary<string, object>;
base.OnSetState(info, mode);
}
}
Now on your SL client,you can do:
...
var criteria = new DicCriteria();
criteria.Add("Name", "Levin").Add("Country","CN");
dataPortalInstance.BeginFetch(criteria);
...
On your server side somewhere in Data access layer,it may be:
public override L Fetch(CriteriaBase criteria)
{
if (criteria != null)
{
var list = (L)Activator.CreateInstance(typeof(L), true);
IList<TDto> _list;
using (UOWorker.Start(DatabaseKey))
{
var crit = criteria as DicCriteria;
Check.Require(crit!=null,"A parameter of DicCriteria type is required!");
_list = _repository.FindAll(crit.Value);
}
list.Add(_list);
MarkOld(list);
return list;
}
return Fetch();
}
That's it!
Copyright (c) Marimer LLC