diff options
| author | WWWesten <4700006+WWWesten@users.noreply.github.com> | 2021-11-01 23:43:29 +0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-11-01 23:43:29 +0500 |
| commit | 0a14279e2a21bcb9654a06a2d49e1e4f0cc5329c (patch) | |
| tree | e1b1bd603b011ca98e5793e356326bf4a35a7050 /Jellyfin.Api/Helpers/ClassMigrationHelper.cs | |
| parent | f2817fef743eeb75a00782ceea363b2d3e7dc9f2 (diff) | |
| parent | 76eeb8f655424d295e73ced8349c6fefee6ddb12 (diff) | |
Merge branch 'jellyfin:master' into master
Diffstat (limited to 'Jellyfin.Api/Helpers/ClassMigrationHelper.cs')
| -rw-r--r-- | Jellyfin.Api/Helpers/ClassMigrationHelper.cs | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs new file mode 100644 index 000000000..a911a3324 --- /dev/null +++ b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs @@ -0,0 +1,71 @@ +using System; +using System.Reflection; + +namespace Jellyfin.Api.Helpers +{ + /// <summary> + /// A static class for copying matching properties from one object to another. + /// TODO: remove at the point when a fixed migration path has been decided upon. + /// </summary> + public static class ClassMigrationHelper + { + /// <summary> + /// Extension for 'Object' that copies the properties to a destination object. + /// </summary> + /// <param name="source">The source.</param> + /// <param name="destination">The destination.</param> + public static void CopyProperties(this object source, object destination) + { + // If any this null throw an exception. + if (source == null || destination == null) + { + throw new Exception("Source or/and Destination Objects are null"); + } + + // Getting the Types of the objects. + Type typeDest = destination.GetType(); + Type typeSrc = source.GetType(); + + // Iterate the Properties of the source instance and populate them from their destination counterparts. + PropertyInfo[] srcProps = typeSrc.GetProperties(); + foreach (PropertyInfo srcProp in srcProps) + { + if (!srcProp.CanRead) + { + continue; + } + + var targetProperty = typeDest.GetProperty(srcProp.Name); + if (targetProperty == null) + { + continue; + } + + if (!targetProperty.CanWrite) + { + continue; + } + + var obj = targetProperty.GetSetMethod(true); + if (obj != null && obj.IsPrivate) + { + continue; + } + + var target = targetProperty.GetSetMethod(); + if (target != null && (target.Attributes & MethodAttributes.Static) != 0) + { + continue; + } + + if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType)) + { + continue; + } + + // Passed all tests, lets set the value. + targetProperty.SetValue(destination, srcProp.GetValue(source, null), null); + } + } + } +} |
