Session.NET35.cs 2.8 KB

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