2020-10-08 18:00:55 +00:00
|
|
|
using System;
|
|
|
|
using System.Reflection;
|
|
|
|
|
2020-11-21 16:14:00 +00:00
|
|
|
namespace Jellyfin.Api.Helpers
|
2020-10-08 18:00:55 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
2020-11-21 13:27:27 +00:00
|
|
|
/// 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.
|
2020-10-08 18:00:55 +00:00
|
|
|
/// </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)
|
|
|
|
{
|
2020-11-21 13:27:27 +00:00
|
|
|
// If any this null throw an exception.
|
2020-10-08 18:00:55 +00:00
|
|
|
if (source == null || destination == null)
|
|
|
|
{
|
2021-11-08 19:39:02 +00:00
|
|
|
throw new ArgumentException("Source or/and Destination Objects are null");
|
2020-10-08 18:00:55 +00:00
|
|
|
}
|
|
|
|
|
2020-11-21 13:27:27 +00:00
|
|
|
// Getting the Types of the objects.
|
2020-10-08 18:00:55 +00:00
|
|
|
Type typeDest = destination.GetType();
|
|
|
|
Type typeSrc = source.GetType();
|
|
|
|
|
2020-11-21 13:27:27 +00:00
|
|
|
// Iterate the Properties of the source instance and populate them from their destination counterparts.
|
2020-10-08 18:00:55 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2020-11-21 13:27:27 +00:00
|
|
|
// Passed all tests, lets set the value.
|
2020-10-08 18:00:55 +00:00
|
|
|
targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|