PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/Code/Platform/Channels/Extensions/ObjectExtensions.cs

http://github.com/waseems/inbox2_desktop
C# | 77 lines | 66 code | 11 blank | 0 comment | 10 complexity | eda4b5b9d94087b8c30dffd6d296eba6 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Xml.Serialization;
  9. using Inbox2.Platform.Channels.Entities;
  10. using Inbox2.Platform.Interfaces;
  11. namespace Inbox2.Platform.Channels.Extensions
  12. {
  13. public static class ObjectExtensions
  14. {
  15. public static IEnumerable<PropertyValue> GetProperties(this object o)
  16. {
  17. if (o != null)
  18. {
  19. PropertyDescriptorCollection props = TypeDescriptor.GetProperties(o);
  20. foreach (PropertyDescriptor prop in props)
  21. {
  22. object val = prop.GetValue(o);
  23. if (val != null)
  24. {
  25. yield return new PropertyValue { Name = prop.Name, Value = val };
  26. }
  27. }
  28. }
  29. }
  30. }
  31. public sealed class PropertyValue
  32. {
  33. private object value;
  34. public string Name { get; set; }
  35. public object Value
  36. {
  37. get
  38. {
  39. if (value == null)
  40. return null;
  41. if (value is DateTime)
  42. return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
  43. if (value is Boolean)
  44. return ((bool)value) ? 1 : 0;
  45. if (value is SourceAddress)
  46. return ((SourceAddress) value).ToString(true);
  47. if (value is IPersistXml)
  48. {
  49. using (MemoryStream ms = new MemoryStream())
  50. {
  51. XmlSerializer ser = new XmlSerializer(value.GetType());
  52. ser.Serialize(ms, value);
  53. ms.Seek(0, SeekOrigin.Begin);
  54. using (StreamReader sr = new StreamReader(ms))
  55. return sr.ReadToEnd();
  56. }
  57. }
  58. return value.ToString();
  59. }
  60. set
  61. {
  62. this.value = value;
  63. }
  64. }
  65. }
  66. }