Session.NET35.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System.Linq;
  2. using System;
  3. using Renci.SshNet.Messages;
  4. using System.Threading;
  5. using System.Reflection;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. namespace Renci.SshNet
  9. {
  10. /// <summary>
  11. /// Provides functionality to connect and interact with SSH server.
  12. /// </summary>
  13. public partial class Session
  14. {
  15. private static readonly Dictionary<Type, MethodInfo> _handlers;
  16. static Session()
  17. {
  18. _handlers = new Dictionary<Type, MethodInfo>();
  19. foreach (var method in typeof(Session).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic).Where(x => x.Name == "HandleMessage"))
  20. {
  21. if (method.IsGenericMethod) continue;
  22. var args = method.GetParameters();
  23. if (args.Length != 1) continue;
  24. var argType = args[0].ParameterType;
  25. if (!argType.IsSubclassOf(typeof(Message))) continue;
  26. _handlers.Add(argType, method);
  27. }
  28. }
  29. /// <summary>
  30. /// Handles SSH messages.
  31. /// </summary>
  32. /// <param name="message">The message.</param>
  33. partial void HandleMessageCore(Message message)
  34. {
  35. Debug.Assert(message != null);
  36. MethodInfo method;
  37. if (_handlers.TryGetValue(message.GetType(), out method))
  38. {
  39. try
  40. {
  41. method.Invoke(this, new object[] { message });
  42. }
  43. catch (TargetInvocationException ex)
  44. {
  45. throw ex.InnerException ?? ex;
  46. }
  47. }
  48. else
  49. {
  50. HandleMessage(message);
  51. }
  52. }
  53. partial void ExecuteThread(Action action)
  54. {
  55. ThreadPool.QueueUserWorkItem((o) => { action(); });
  56. }
  57. partial void InternalRegisterMessage(string messageName)
  58. {
  59. lock (this._messagesMetadata)
  60. {
  61. foreach (var m in from m in this._messagesMetadata where m.Name == messageName select m)
  62. {
  63. m.Enabled = true;
  64. m.Activated = true;
  65. }
  66. }
  67. }
  68. partial void InternalUnRegisterMessage(string messageName)
  69. {
  70. lock (this._messagesMetadata)
  71. {
  72. foreach (var m in from m in this._messagesMetadata where m.Name == messageName select m)
  73. {
  74. m.Enabled = false;
  75. m.Activated = false;
  76. }
  77. }
  78. }
  79. }
  80. }