Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.69 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Runtime.InteropServices;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Lextm.SharpSnmpLib;
  12. using Lextm.SharpSnmpLib.Messaging;
  13. using Lextm.SharpSnmpLib.Security;
  14.  
  15. namespace SandboxForGetAsync
  16. {
  17. internal static class Program
  18. {
  19. private static readonly NumberGenerator RequestCounter = new NumberGenerator(0, 5000);
  20. private static readonly IPEndPoint RemoteEp = new IPEndPoint(IPAddress.Parse("10.161.227.164"), 161);
  21. private static readonly OctetString Community = new OctetString("public");
  22. private static readonly ObjectIdentifier Oid = new ObjectIdentifier("1.3.6.1.2.1.1.1.0");
  23. private const int TestCount = 100;
  24.  
  25. internal static int Main(string[] args)
  26. {
  27. try
  28. {
  29. return Program.InternalMainAsync(args).Result;
  30. }
  31. catch (Exception ex)
  32. {
  33. Console.Error.WriteLine(ex);
  34. return Marshal.GetHRForException(ex);
  35. }
  36. finally
  37. {
  38. Console.WriteLine("hit any key to exit...");
  39. // shapshot(#3) here on dotMemory GUI.
  40. Console.ReadLine();
  41. }
  42. }
  43.  
  44. private static async Task<int> InternalMainAsync(string[] args)
  45. {
  46. // await Program.PrepareTestMemory1();
  47. await Program.PrepareTestMemory2();
  48.  
  49. Console.WriteLine("hit any key to start test 1...");
  50. // shapshot(#1) here on dotMemory GUI.
  51. Console.ReadLine();
  52.  
  53. // await Program.TestMemory1();
  54. await Program.TestMemory2();
  55.  
  56. Console.WriteLine("hit any key to start test 2...");
  57. // shapshot(#2) here on dotMemory GUI.
  58. Console.ReadLine();
  59.  
  60. // await Program.TestMemory1();
  61. await Program.TestMemory2();
  62.  
  63. return 0;
  64. }
  65.  
  66. #region Test1 (SnmpClient sample)
  67.  
  68. private static async Task PrepareTestMemory1()
  69. {
  70. await Program.TestToCallSnmpClient1(-1);
  71. }
  72.  
  73. private static async Task TestMemory1()
  74. {
  75. // Running this code on Host-A
  76. // The Snmp Agent on Host-B, but an agent is not listening...
  77.  
  78. var tasks = Enumerable.Range(0, Program.TestCount).Select(async (_, index) => await Program.TestToCallSnmpClient1(index));
  79. var allTasks = Task.WhenAll(tasks);
  80. try
  81. {
  82. await allTasks.ConfigureAwait(false);
  83. }
  84. catch (Exception ex)
  85. {
  86. Console.WriteLine("{0}", ex.InnerException);
  87. }
  88. }
  89.  
  90. private static async Task TestToCallSnmpClient1(int index)
  91. {
  92. // request: RemoteEP=Host-B:161 Community="public", Oid="1.3.6.1.2.1.1.1.0"
  93. var requestId = Program.RequestCounter.NextId;
  94. var message = new GetRequestMessage(requestId, VersionCode.V1, Program.Community, new List<Variable> { new Variable(Program.Oid) });
  95.  
  96. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10))) // timeout 10 sec
  97. using (var client = new SnmpClient())
  98. {
  99. try
  100. {
  101. var response = await client.GetResponseAsync(message, Program.RemoteEp, cts.Token);
  102. var responseVariablesText = string.Join(
  103. ", ",
  104. response.Variables()
  105. .Select(variable => string.Format("[OID={0} Data={1}]", variable.Id, variable.Data)));
  106. Console.WriteLine("{0:d3}({1}):{2}", index, requestId, responseVariablesText);
  107. }
  108. catch (OperationCanceledException ex)
  109. {
  110. Console.WriteLine("{0:d3}({1}):{2}", index, requestId, ex.Message);
  111. }
  112. catch (Exception ex)
  113. {
  114. Console.WriteLine("{0:d3}({1}):{2}", index, requestId, ex.Message);
  115. }
  116. finally
  117. {
  118. }
  119. }
  120. }
  121.  
  122. #endregion
  123.  
  124. #region Test2 (Extension Method sample)
  125.  
  126. private static async Task PrepareTestMemory2()
  127. {
  128. await Program.TestToCallSnmpClient2(-1);
  129. }
  130. private static async Task TestMemory2()
  131. {
  132. // Running this code on Host-A
  133. // The Snmp Agent on Host-B, but an agent is not listening...
  134.  
  135. var tasks = Enumerable.Range(0, Program.TestCount).Select(async (_, index) => await Program.TestToCallSnmpClient2(index));
  136. var allTasks = Task.WhenAll(tasks);
  137. try
  138. {
  139. await allTasks.ConfigureAwait(false);
  140. }
  141. catch (Exception ex)
  142. {
  143. Console.WriteLine("{0}", ex.InnerException);
  144. }
  145. }
  146. private static async Task TestToCallSnmpClient2(int index)
  147. {
  148. // request: RemoteEP=Host-B:161 Community="public", Oid="1.3.6.1.2.1.1.1.0"
  149. var requestId = Program.RequestCounter.NextId;
  150. var message = new GetRequestMessage(requestId, VersionCode.V1, Program.Community, new List<Variable> { new Variable(Program.Oid) });
  151.  
  152. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10))) // timeout 10 sec
  153. {
  154. try
  155. {
  156. var response = await message.GetResponseAsync(Program.RemoteEp, cts.Token);
  157. var responseVariablesText = string.Join(
  158. ", ",
  159. response.Variables()
  160. .Select(variable => string.Format("[OID={0} Data={1}]", variable.Id, variable.Data)));
  161. Console.WriteLine("{0:d3}({1}):{2}", index, requestId, responseVariablesText);
  162. }
  163. catch (OperationCanceledException ex)
  164. {
  165. Console.WriteLine("{0:d3}({1}):{2}", index, requestId, ex.Message);
  166. }
  167. catch (Exception ex)
  168. {
  169. Console.WriteLine("{0:d3}({1}):{2}", index, requestId, ex.Message);
  170. }
  171. finally
  172. {
  173. }
  174. }
  175. }
  176.  
  177. #endregion
  178.  
  179. #region Extension Methods
  180.  
  181. internal static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
  182. {
  183. var tcs = new TaskCompletionSource<bool>();
  184. using (cancellationToken.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(true), tcs))
  185. {
  186. var completedTask = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
  187. if (task != completedTask)
  188. {
  189. throw new OperationCanceledException(cancellationToken);
  190. }
  191. }
  192.  
  193. return await task.ConfigureAwait(false);
  194. }
  195.  
  196. //public static IDisposable CreateTimeoutScope(this IDisposable disposable, TimeSpan timeSpan)
  197. //{
  198. // var cancellationTokenSource = new CancellationTokenSource(timeSpan);
  199. // var cancellationTokenRegistration = cancellationTokenSource.Token.Register(disposable.Dispose);
  200. // return new DisposableScope(
  201. // () =>
  202. // {
  203. // cancellationTokenRegistration.Dispose();
  204. // cancellationTokenSource.Dispose();
  205. // disposable.Dispose();
  206. // });
  207. //}
  208.  
  209. //private sealed class DisposableScope : IDisposable
  210. //{
  211. // private readonly Action closeScopeAction;
  212. // public DisposableScope(Action closeScopeAction)
  213. // {
  214. // this.closeScopeAction = closeScopeAction;
  215. // }
  216. // public void Dispose()
  217. // {
  218. // this.closeScopeAction();
  219. // }
  220. //}
  221.  
  222. #endregion
  223.  
  224. #region SnmpClient for sample
  225.  
  226. private class SnmpClient : IDisposable
  227. {
  228. private readonly CancellationTokenSource cts;
  229. private long disposableState;
  230.  
  231. public SnmpClient()
  232. {
  233. this.cts = new CancellationTokenSource();
  234. }
  235.  
  236. ~SnmpClient()
  237. {
  238. this.Dispose(false);
  239. }
  240.  
  241. public bool IsDisposed
  242. {
  243. get { return Interlocked.Read(ref this.disposableState) == 1L; }
  244. }
  245.  
  246. public void Dispose()
  247. {
  248. this.Dispose(true);
  249. GC.SuppressFinalize(this);
  250. }
  251.  
  252. protected virtual void DisposeManagedInstances()
  253. {
  254. this.cts.Cancel();
  255. this.cts.Dispose();
  256. }
  257.  
  258. protected virtual void DisposeUnmanagedInstances()
  259. {
  260. }
  261.  
  262. private void Dispose(bool disposing)
  263. {
  264. if (Interlocked.CompareExchange(ref this.disposableState, 1L, 0L) == 0L)
  265. {
  266. Debug.Print("!! {0}.Dispose...", this.GetType().FullName);
  267. if (disposing)
  268. {
  269. this.DisposeManagedInstances();
  270. }
  271.  
  272. this.DisposeUnmanagedInstances();
  273. }
  274. }
  275.  
  276. public async Task<ISnmpMessage> GetResponseAsync(ISnmpMessage request, IPEndPoint remoteEndPoint, CancellationToken cancellationToken)
  277. {
  278. using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(this.cts.Token, cancellationToken))
  279. using (var client = UdpClientWrapper.CreateClient())
  280. {
  281. var sendingBytes = request.ToBytes();
  282. var sendingTask = client.SendAsync(sendingBytes, sendingBytes.Length, remoteEndPoint);
  283. var sentBytesSize = await sendingTask.WithCancellation(linkedCts.Token).ConfigureAwait(false);
  284.  
  285. var receivingTask = client.ReceiveAsync();
  286. var receiveResult = await receivingTask.WithCancellation(linkedCts.Token).ConfigureAwait(false);
  287.  
  288. var reply = receiveResult.Buffer;
  289. var registry = new UserRegistry();
  290. var response = MessageFactory.ParseMessages(reply, 0, receiveResult.Buffer.Length, registry)[0];
  291.  
  292. var responseCode = response.TypeCode();
  293. if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
  294. {
  295. var requestId = request.MessageId();
  296. var responseId = response.MessageId();
  297. if (responseId != requestId)
  298. {
  299. throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), remoteEndPoint.Address);
  300. }
  301.  
  302. return response;
  303. }
  304.  
  305. throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), remoteEndPoint.Address);
  306. }
  307. }
  308. }
  309.  
  310. #endregion
  311.  
  312. #region UdpClientWrapper for sample
  313.  
  314. private class UdpClientWrapper : UdpClient
  315. {
  316. private UdpClientWrapper()
  317. : base(AddressFamily.InterNetwork)
  318. {
  319. }
  320.  
  321. public static UdpClientWrapper CreateClient()
  322. {
  323. return new UdpClientWrapper();
  324. }
  325.  
  326. protected override void Dispose(bool disposing)
  327. {
  328. Debug.Print("!! {0}.Dispose...", this.GetType().FullName);
  329. base.Dispose(disposing);
  330. }
  331. }
  332.  
  333. #endregion
  334.  
  335. #region Extension Method version for sample
  336.  
  337. private static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint remoteEndPoint, CancellationToken cancellationToken)
  338. {
  339. using (var client = UdpClientWrapper.CreateClient())
  340. {
  341. var sendingBytes = request.ToBytes();
  342. var sendingTask = client.SendAsync(sendingBytes, sendingBytes.Length, remoteEndPoint);
  343. var sentBytesSize = await sendingTask.WithCancellation(cancellationToken).ConfigureAwait(false);
  344.  
  345. var receivingTask = client.ReceiveAsync();
  346. var receiveResult = await receivingTask.WithCancellation(cancellationToken).ConfigureAwait(false);
  347.  
  348. var reply = receiveResult.Buffer;
  349. var registry = new UserRegistry();
  350. var response = MessageFactory.ParseMessages(reply, 0, receiveResult.Buffer.Length, registry)[0];
  351.  
  352. var responseCode = response.TypeCode();
  353. if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
  354. {
  355. var requestId = request.MessageId();
  356. var responseId = response.MessageId();
  357. if (responseId != requestId)
  358. {
  359. throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), remoteEndPoint.Address);
  360. }
  361.  
  362. return response;
  363. }
  364.  
  365. throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), remoteEndPoint.Address);
  366. }
  367. }
  368.  
  369. #endregion
  370. }
  371. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement