/Source/Lokad.Serialization/Serialization/ProtoBufUtil.cs

https://code.google.com/p/lokad-shared-libraries/ · C# · 62 lines · 54 code · 8 blank · 0 comment · 0 complexity · 73f1e2db1894832d612d57ff47c388af MD5 · raw file

  1. using System;
  2. using System.Reflection;
  3. using System.Runtime.Serialization;
  4. using System.Text;
  5. using System.Xml.Serialization;
  6. using ProtoBuf;
  7. namespace Lokad.Serialization
  8. {
  9. public static class ProtoBufUtil
  10. {
  11. public static string GetContractReference(Type type)
  12. {
  13. var attribs = type.GetCustomAttributes(false);
  14. var helper = new AttributeHelper(attribs);
  15. var name = Maybe.String
  16. .GetValue(() => helper.GetString<ProtoContractAttribute>(p => p.Name))
  17. .GetValue(() => helper.GetString<DataContractAttribute>(p => p.Name))
  18. .GetValue(() => helper.GetString<XmlTypeAttribute>(p => p.TypeName))
  19. .GetValue(() => type.Name);
  20. var ns = Maybe.String
  21. .GetValue(() => helper.GetString<DataContractAttribute>(p => p.Namespace))
  22. .GetValue(() => helper.GetString<XmlTypeAttribute>(p => p.Namespace))
  23. .Convert(s => s.Trim() + "/", "");
  24. return ns + name;
  25. }
  26. public static IFormatter CreateFormatter(Type type)
  27. {
  28. try
  29. {
  30. typeof(Serializer)
  31. .GetMethod("PrepareSerializer")
  32. .MakeGenericMethod(type)
  33. .Invoke(null, null);
  34. }
  35. catch (TargetInvocationException tie)
  36. {
  37. var message = string.Format("Failed to prepare ProtoBuf serializer for '{0}'.", type);
  38. throw new InvalidOperationException(message, tie.InnerException);
  39. }
  40. try
  41. {
  42. return (IFormatter)typeof(Serializer)
  43. .GetMethod("CreateFormatter")
  44. .MakeGenericMethod(type)
  45. .Invoke(null, null);
  46. }
  47. catch (TargetInvocationException tie)
  48. {
  49. var message = string.Format("Failed to create ProtoBuf formatter for '{0}'.", type);
  50. throw new InvalidOperationException(message, tie.InnerException);
  51. }
  52. }
  53. }
  54. }