PageRenderTime 41ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/SignalR/Hubs/ReflectionHelper.cs

https://github.com/kpmrafeeq/SignalR
C# | 58 lines | 48 code | 10 blank | 0 comment | 3 complexity | 0a59cafad04d24a1b95038e372817c0c MD5 | raw file
Possible License(s): MIT
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace SignalR.Hubs
  6. {
  7. public static class ReflectionHelper
  8. {
  9. private static readonly Type[] _excludeTypes = new[] { typeof(Hub), typeof(object) };
  10. private static readonly Type[] _excludeInterfaces = new[] { typeof(IHub), typeof(IDisconnect), typeof(IConnected) };
  11. public static IEnumerable<MethodInfo> GetExportedHubMethods(Type type)
  12. {
  13. if (!typeof(IHub).IsAssignableFrom(type))
  14. {
  15. return Enumerable.Empty<MethodInfo>();
  16. }
  17. var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  18. var getMethods = properties.Select(p => p.GetGetMethod());
  19. var setMethods = properties.Select(p => p.GetSetMethod());
  20. var allPropertyMethods = getMethods.Concat(setMethods);
  21. var allInterfaceMethods = _excludeInterfaces.SelectMany(i => GetInterfaceMethods(type, i));
  22. var allExcludes = allPropertyMethods.Concat(allInterfaceMethods);
  23. var actualMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance);
  24. return actualMethods.Except(allExcludes)
  25. .Where(m => !_excludeTypes.Contains(m.DeclaringType));
  26. }
  27. private static IEnumerable<MethodInfo> GetInterfaceMethods(Type type, Type iface)
  28. {
  29. if (!iface.IsAssignableFrom(type))
  30. {
  31. return Enumerable.Empty<MethodInfo>();
  32. }
  33. return type.GetInterfaceMap(iface).TargetMethods;
  34. }
  35. public static TResult GetAttributeValue<TAttribute, TResult>(ICustomAttributeProvider source, Func<TAttribute, TResult> valueGetter)
  36. where TAttribute : Attribute
  37. {
  38. var attributes = source.GetCustomAttributes(typeof(TAttribute), false)
  39. .Cast<TAttribute>()
  40. .ToList();
  41. if (attributes.Any())
  42. {
  43. return valueGetter(attributes[0]);
  44. }
  45. return default(TResult);
  46. }
  47. }
  48. }