Helpers.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System;
  2. using System.IO;
  3. using System.Linq.Expressions;
  4. using System.Reflection;
  5. namespace QuestPDF.Helpers
  6. {
  7. internal static class Helpers
  8. {
  9. internal static byte[] LoadEmbeddedResource(string resourceName)
  10. {
  11. using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
  12. using var reader = new BinaryReader(stream);
  13. return reader.ReadBytes((int) stream.Length);
  14. }
  15. private static PropertyInfo? ToPropertyInfo<T, TValue>(this Expression<Func<T, TValue>> selector)
  16. {
  17. return (selector.Body as MemberExpression)?.Member as PropertyInfo;
  18. }
  19. internal static string? GetPropertyName<T, TValue>(this Expression<Func<T, TValue>> selector) where TValue : class
  20. {
  21. return selector.ToPropertyInfo()?.Name;
  22. }
  23. internal static TValue? GetPropertyValue<T, TValue>(this T target, Expression<Func<T, TValue>> selector) where TValue : class
  24. {
  25. return selector.ToPropertyInfo()?.GetValue(target) as TValue;
  26. }
  27. internal static void SetPropertyValue<T, TValue>(this T target, Expression<Func<T, TValue>> selector, TValue value)
  28. {
  29. var property = selector.ToPropertyInfo() ?? throw new Exception("Expected property with getter and setter.");
  30. property?.SetValue(target, value);
  31. }
  32. }
  33. }