ClassMigrationHelper.cs 2.3 KB

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