ClassMigrationHelper.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Reflection;
  3. namespace Jellyfin.Api.Helpers
  4. {
  5. /// <summary>
  6. /// A static class for copying matching properties from one object to another.
  7. /// TODO: remove at the point when a fixed migration path has been decided upon.
  8. /// </summary>
  9. public static class ClassMigrationHelper
  10. {
  11. /// <summary>
  12. /// Extension for 'Object' that copies the properties to a destination object.
  13. /// </summary>
  14. /// <param name="source">The source.</param>
  15. /// <param name="destination">The destination.</param>
  16. public static void CopyProperties(this object source, object destination)
  17. {
  18. // If any this null throw an exception.
  19. if (source == null || destination == null)
  20. {
  21. throw new Exception("Source or/and Destination Objects are null");
  22. }
  23. // Getting the Types of the objects.
  24. Type typeDest = destination.GetType();
  25. Type typeSrc = source.GetType();
  26. // Iterate the Properties of the source instance and populate them from their destination counterparts.
  27. PropertyInfo[] srcProps = typeSrc.GetProperties();
  28. foreach (PropertyInfo srcProp in srcProps)
  29. {
  30. if (!srcProp.CanRead)
  31. {
  32. continue;
  33. }
  34. var targetProperty = typeDest.GetProperty(srcProp.Name);
  35. if (targetProperty == null)
  36. {
  37. continue;
  38. }
  39. if (!targetProperty.CanWrite)
  40. {
  41. continue;
  42. }
  43. var obj = targetProperty.GetSetMethod(true);
  44. if (obj != null && obj.IsPrivate)
  45. {
  46. continue;
  47. }
  48. var target = targetProperty.GetSetMethod();
  49. if (target != null && (target.Attributes & MethodAttributes.Static) != 0)
  50. {
  51. continue;
  52. }
  53. if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType))
  54. {
  55. continue;
  56. }
  57. // Passed all tests, lets set the value.
  58. targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
  59. }
  60. }
  61. }
  62. }