Guid serialization in the windows phone

Nov 11, 2010 at 9:42 AM

I'm just starting to put Sterling to use now, on my first Phone app! :)

I read the doc last week and I think I read that Guid serialization was not supported on the phone because there is no Guid parse method.

If my memory serves me right, let me suggest a Guid parsing method! :)

private static Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.None);

public static bool TryGetGuid(this string candidate, out Guid output)
	if (candidate != null && isGuid.IsMatch(candidate))
		output = new Guid(candidate);
		return true;
	output = Guid.Empty;
	return false;

public static Guid? GetGuid(this string candidate)
	Guid g;
	if (TryGetGuid(candidate, out g))
		return g;
	return null;

Nov 11, 2010 at 12:22 PM

Yes! That is where the serializers come in. You can encapsulate that in a class based on BaseSerializer and then register it and you're good to go!

Nov 11, 2010 at 12:43 PM

Haven't test it yet, but how about adding this (default) serializer to the phone version? (I'm going to do it on my build! :))


	public class GuidSerializer : BaseSerializer
		public override bool CanSerialize(Type targetType)
			return targetType == typeof(Guid);
		public override void Serialize(object target, BinaryWriter writer)
			var data = (Guid)target;
		public override object Deserialize(Type type, BinaryReader reader)
			return new Guid(reader.ReadBytes(16));

Nov 11, 2010 at 12:52 PM

I found that:

            _serializers.Add(typeof(Guid), new Tuple<Action<BinaryWriter, object>, Func<BinaryReader, object>>(
                (bw, obj) => bw.Write(obj.ToString()),
                br => Guid.Parse(br.ReadString())));

 which can be turned into

            _serializers.Add(typeof(Guid), new Tuple<Action<BinaryWriter, object>, Func<BinaryReader, object>>(
                (bw, obj) => bw.Write(((Guid)obj).ToByteArray()),
                br => new Guid(br.ReadBytes(16))));

can't it!?! ;-)

Nov 15, 2010 at 10:35 PM

Yup! Will be there the next release, thanks!