Advertisement
Guest User

Network/Process Traffic Monitor in VBNet - By Elektro

a guest
Sep 16th, 2015
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 43.43 KB | None | 0 0
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 16-September-2015
  4. ' ***********************************************************************
  5. ' <copyright file="NetworkUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Public Members Summary "
  11.  
  12. #Region " SubClasses "
  13.  
  14. ' NetworkUtil.NetworkTrafficMonitor
  15. ' NetworkUtil.ProcessTrafficMonitor
  16.  
  17. #End Region
  18.  
  19. #Region " Events "
  20.  
  21. ' NetworkUtil.NetworkTrafficMonitor.TrafficChanged(Object, NetworkTrafficMonitor.TrafficChangedEventArgs)
  22. ' NetworkUtil.ProcessTrafficMonitor.TrafficChanged(Object, NetworkTrafficMonitor.TrafficChangedEventArgs)
  23.  
  24. #End Region
  25.  
  26. #Region " Enumerations "
  27.  
  28. ' NetworkUtil.ProcessTrafficMonitor.UpdateBehavior As Integer
  29.  
  30. #End Region
  31.  
  32. #Region " Properties "
  33.  
  34. ' NetworkUtil.NetworkInterfaceNames As IEnumerable(Of String)
  35.  
  36. ' NetworkUtil.NetworkTrafficMonitor.InterfaceName As string
  37. ' NetworkUtil.NetworkTrafficMonitor.IsActive As Boolean
  38. ' NetworkUtil.NetworkTrafficMonitor.UpdateBehavior As NetworkTrafficMonitor.UpdateBehaviorEnum
  39. ' NetworkUtil.NetworkTrafficMonitor.UpdateInterval As Integer
  40.  
  41. ' NetworkUtil.ProcessTrafficMonitor.ProcessId As Integer
  42. ' NetworkUtil.ProcessTrafficMonitor.IsActive As Boolean
  43. ' NetworkUtil.ProcessTrafficMonitor.UpdateBehavior As NetworkTrafficMonitor.UpdateBehaviorEnum
  44. ' NetworkUtil.ProcessTrafficMonitor.UpdateInterval As Integer
  45.  
  46. #End Region
  47.  
  48. #Region " Methods "
  49.  
  50. ' NetworkUtil.NetworkTrafficMonitor.New(String)
  51. ' NetworkUtil.NetworkTrafficMonitor.Start
  52. ' NetworkUtil.NetworkTrafficMonitor.Stop
  53. ' NetworkUtil.NetworkTrafficMonitor.Dispose
  54.  
  55. ' NetworkUtil.ProcessTrafficMonitor.New(Integer)
  56. ' NetworkUtil.ProcessTrafficMonitor.Start
  57. ' NetworkUtil.ProcessTrafficMonitor.Stop
  58. ' NetworkUtil.ProcessTrafficMonitor.Dispose
  59.  
  60. #End Region
  61.  
  62. #Region " Functions "
  63.  
  64. ' NetworkUtil.NetworkTrafficMonitor.GetAvaliableInterfaceNames As IEnumerable(Of String)
  65. ' NetworkUtil.NetworkTrafficMonitor.GetBytesReceived As Single
  66. ' NetworkUtil.NetworkTrafficMonitor.GetBytesSent As Single
  67.  
  68. ' NetworkUtil.ProcessTrafficMonitor.GetBytesReceived As Single
  69. ' NetworkUtil.ProcessTrafficMonitor.GetBytesSent As Single
  70.  
  71. #End Region
  72.  
  73. #End Region
  74.  
  75. #Region " Option Statements "
  76.  
  77. Option Strict On
  78. Option Explicit On
  79. Option Infer Off
  80.  
  81. #End Region
  82.  
  83. #Region " Imports "
  84.  
  85. Imports System
  86. Imports System.Collections.Generic
  87. Imports System.ComponentModel
  88. Imports System.Diagnostics
  89. Imports System.Linq
  90. Imports System.Net.NetworkInformation
  91. Imports System.Windows.Forms
  92.  
  93. #End Region
  94.  
  95. Public NotInheritable Class NetworkUtil
  96.  
  97. #Region " Poperties "
  98.  
  99.     ''' ----------------------------------------------------------------------------------------------------
  100.     ''' <summary>
  101.     ''' Gets the current network interface names.
  102.     ''' </summary>
  103.     ''' ----------------------------------------------------------------------------------------------------
  104.     ''' <value>
  105.     ''' An <see cref="IEnumerable(Of String)"/> that enumerates the network interface names.
  106.     ''' </value>
  107.     ''' ----------------------------------------------------------------------------------------------------
  108.     Public Shared ReadOnly Property NetworkInterfaceNames As IEnumerable(Of String)
  109.  
  110.         <DebuggerStepThrough>
  111.         <DebuggerHidden>
  112.         Get
  113.             Return From ni As NetworkInterface In NetworkInterface.GetAllNetworkInterfaces()
  114.                    Select ni.Description
  115.         End Get
  116.     End Property
  117.  
  118. #End Region
  119.  
  120. #Region " Network Traffic Monitor "
  121.  
  122.     ''' ----------------------------------------------------------------------------------------------------
  123.     ''' <summary>
  124.     ''' Monitorizes the traffic of a network interface.
  125.     ''' </summary>
  126.     ''' ----------------------------------------------------------------------------------------------------
  127.     Public Class NetworkTrafficMonitor : Implements IDisposable
  128.  
  129. #Region " Objects / Read-Only vars. "
  130.  
  131.         ''' ----------------------------------------------------------------------------------------------------
  132.         ''' <summary>
  133.         ''' The performance counter that monitors the bytes sent.
  134.         ''' </summary>
  135.         ''' ----------------------------------------------------------------------------------------------------
  136.         Protected bytesSentPerformanceCounter As PerformanceCounter
  137.  
  138.         ''' ----------------------------------------------------------------------------------------------------
  139.         ''' <summary>
  140.         ''' The performance counter that monitors the bytes received.
  141.         ''' </summary>
  142.         ''' ----------------------------------------------------------------------------------------------------
  143.         Protected bytesReceivedPerformanceCounter As PerformanceCounter
  144.  
  145.         ''' ----------------------------------------------------------------------------------------------------
  146.         ''' <summary>
  147.         ''' The name of the Performance Counters category.
  148.         ''' </summary>
  149.         ''' ----------------------------------------------------------------------------------------------------
  150.         Protected ReadOnly categoryName As String = "Network Interface"
  151.  
  152.         ''' ----------------------------------------------------------------------------------------------------
  153.         ''' <summary>
  154.         ''' The name of the Performance Counter that retrieves the bytes sent.
  155.         ''' </summary>
  156.         ''' ----------------------------------------------------------------------------------------------------
  157.         Protected ReadOnly counterNameBytesSent As String = "Bytes Sent/sec"
  158.  
  159.         ''' ----------------------------------------------------------------------------------------------------
  160.         ''' <summary>
  161.         ''' The name of the Performance Counter that retrieves the bytes received.
  162.         ''' </summary>
  163.         ''' ----------------------------------------------------------------------------------------------------
  164.         Protected ReadOnly counterNameBytesReceived As String = "Bytes Received/sec"
  165.  
  166.         ''' ----------------------------------------------------------------------------------------------------
  167.         ''' <summary>
  168.         ''' Timer that manages the counters update interval.
  169.         ''' </summary>
  170.         ''' ----------------------------------------------------------------------------------------------------
  171.         Protected WithEvents trafficUpdateTimer As Timer
  172.  
  173. #End Region
  174.  
  175. #Region " Properties "
  176.  
  177.         ''' ----------------------------------------------------------------------------------------------------
  178.         ''' <summary>
  179.         ''' Gets the name of the network interface that is being monitored.
  180.         ''' </summary>
  181.         ''' ----------------------------------------------------------------------------------------------------
  182.         ''' <value>
  183.         ''' The name of the network interface that is being monitored.
  184.         ''' </value>
  185.         ''' ----------------------------------------------------------------------------------------------------
  186.         Public Overridable ReadOnly Property InterfaceName As String
  187.             Get
  188.                 Return Me.interfaceNameB
  189.             End Get
  190.         End Property
  191.         ''' ----------------------------------------------------------------------------------------------------
  192.         ''' <summary>
  193.         ''' ( Backing Field )
  194.         ''' The name of the network interface that is being monitored.
  195.         ''' </summary>
  196.         ''' ----------------------------------------------------------------------------------------------------
  197.         Protected ReadOnly interfaceNameB As String
  198.  
  199.         ''' ----------------------------------------------------------------------------------------------------
  200.         ''' <summary>
  201.         ''' Gets a value that indicates whether the traffic monitor is active.
  202.         ''' </summary>
  203.         ''' ----------------------------------------------------------------------------------------------------
  204.         ''' <value>
  205.         ''' A value that indicates whether the traffic monitor is active.
  206.         ''' </value>
  207.         ''' ----------------------------------------------------------------------------------------------------
  208.         Public Overridable ReadOnly Property IsActive As Boolean
  209.             Get
  210.                 Return Me.isActiveB
  211.             End Get
  212.         End Property
  213.         ''' ----------------------------------------------------------------------------------------------------
  214.         ''' <summary>
  215.         ''' ( Backing Field )
  216.         ''' A value that indicates whether the traffic monitor is active.
  217.         ''' </summary>
  218.         ''' ----------------------------------------------------------------------------------------------------
  219.         Protected isActiveB As Boolean = False
  220.  
  221.         ''' ----------------------------------------------------------------------------------------------------
  222.         ''' <summary>
  223.         ''' Gets a value, in milliseconds, that determines when the monitor will update the traffic values.
  224.         ''' </summary>
  225.         ''' ----------------------------------------------------------------------------------------------------
  226.         ''' <value>
  227.         ''' A value, in milliseconds, that determines when the monitor will update the traffic values.
  228.         ''' </value>
  229.         ''' ----------------------------------------------------------------------------------------------------
  230.         Public Overridable Property UpdateInterval As Integer
  231.             Get
  232.                 Return Me.updateIntervalB
  233.             End Get
  234.             <DebuggerStepThrough>
  235.             <DebuggerHidden>
  236.             Set(ByVal value As Integer)
  237.                 Me.updateIntervalB = value
  238.                 Me.trafficUpdateTimer.Interval = value
  239.             End Set
  240.         End Property
  241.         ''' ----------------------------------------------------------------------------------------------------
  242.         ''' <summary>
  243.         ''' ( Backing Field )
  244.         ''' A value, in milliseconds, that determines when the monitor will update the traffic values.
  245.         ''' </summary>
  246.         ''' ----------------------------------------------------------------------------------------------------
  247.         Protected updateIntervalB As Integer = 1000
  248.  
  249.         ''' ----------------------------------------------------------------------------------------------------
  250.         ''' <summary>
  251.         ''' Gets or sets a value that controls the behavior of the <see cref="TrafficChanged"/> event.
  252.         ''' </summary>
  253.         ''' ----------------------------------------------------------------------------------------------------
  254.         ''' <value>
  255.         ''' A value that controls the behavior of the <see cref="TrafficChanged"/> event.
  256.         ''' </value>
  257.         ''' ----------------------------------------------------------------------------------------------------
  258.         Public Property UpdateBehavior As UpdateBehaviorEnum = UpdateBehaviorEnum.FireAlwaysAfterTick
  259.  
  260. #End Region
  261.  
  262. #Region " Enumerations "
  263.  
  264.         ''' <summary>
  265.         ''' Specifies a behavior of the <see cref="TrafficChanged"/> event
  266.         ''' </summary>
  267.         Public Enum UpdateBehaviorEnum As Integer
  268.  
  269.             ''' <summary>
  270.             ''' Fires the <see cref="TrafficChanged"/> event always when the specified <see cref="UpdateInterval"/> time ticks.
  271.             ''' </summary>
  272.             FireAlwaysAfterTick = 0I
  273.  
  274.             ''' <summary>
  275.             ''' Fires the <see cref="TrafficChanged"/> event only if received or sent bytes changes,
  276.             ''' after the the specified <see cref="UpdateInterval"/> time ticks.
  277.             ''' </summary>
  278.             FireWhenTrafficChangesAfterTick = 1I
  279.  
  280.         End Enum
  281.  
  282. #End Region
  283.  
  284. #Region " Events "
  285.  
  286.         ''' ----------------------------------------------------------------------------------------------------
  287.         ''' <summary>
  288.         ''' Occurs when network traffic changed.
  289.         ''' </summary>
  290.         ''' ----------------------------------------------------------------------------------------------------
  291.         Protected Friend Event TrafficChanged As EventHandler(Of TrafficChangedEventArgs)
  292.  
  293. #Region " Traffic Changd Args "
  294.  
  295.         ''' ----------------------------------------------------------------------------------------------------
  296.         ''' <summary>
  297.         ''' Contains the event-data of a <see cref="TrafficChanged"/> event.
  298.         ''' </summary>
  299.         ''' ----------------------------------------------------------------------------------------------------
  300.         Protected Friend NotInheritable Class TrafficChangedEventArgs : Inherits EventArgs
  301.  
  302. #Region " Properties "
  303.  
  304.             ''' ----------------------------------------------------------------------------------------------------
  305.             ''' <summary>
  306.             ''' Gets the bytes sent.
  307.             ''' </summary>
  308.             ''' ----------------------------------------------------------------------------------------------------
  309.             ''' <value>
  310.             ''' The bytes sent.
  311.             ''' </value>
  312.             ''' ----------------------------------------------------------------------------------------------------
  313.             Public ReadOnly Property BytesSent As Single
  314.                 Get
  315.                     Return Me.bytesSentB
  316.                 End Get
  317.             End Property
  318.             ''' ----------------------------------------------------------------------------------------------------
  319.             ''' <summary>
  320.             ''' ( Backing Field )
  321.             ''' Gets the bytes sent.
  322.             ''' </summary>
  323.             ''' ----------------------------------------------------------------------------------------------------
  324.             Private ReadOnly bytesSentB As Single
  325.  
  326.             ''' ----------------------------------------------------------------------------------------------------
  327.             ''' <summary>
  328.             ''' Gets the bytes received.
  329.             ''' </summary>
  330.             ''' ----------------------------------------------------------------------------------------------------
  331.             ''' <value>
  332.             ''' The bytes received.
  333.             ''' </value>
  334.             ''' ----------------------------------------------------------------------------------------------------
  335.             Public ReadOnly Property BytesReceived As Single
  336.                 Get
  337.                     Return Me.bytesReceivedB
  338.                 End Get
  339.             End Property
  340.             ''' ----------------------------------------------------------------------------------------------------
  341.             ''' <summary>
  342.             ''' ( Backing Field )
  343.             ''' Gets the bytes received.
  344.             ''' </summary>
  345.             ''' ----------------------------------------------------------------------------------------------------
  346.             Private ReadOnly bytesReceivedB As Single
  347.  
  348.             ''' ----------------------------------------------------------------------------------------------------
  349.             ''' <summary>
  350.             ''' Gets the difference between the last and the current amount of bytes sent.
  351.             ''' For upload speed measuring purposes.
  352.             ''' </summary>
  353.             ''' ----------------------------------------------------------------------------------------------------
  354.             ''' <value>
  355.             ''' The difference between the last and the current amount of bytes sent.
  356.             ''' </value>
  357.             ''' ----------------------------------------------------------------------------------------------------
  358.             Public ReadOnly Property DiffBytesSent As Single
  359.                 Get
  360.                     Return Me.diffBytesSentB
  361.                 End Get
  362.             End Property
  363.             ''' ----------------------------------------------------------------------------------------------------
  364.             ''' <summary>
  365.             ''' ( Backing Field )
  366.             ''' The difference between the last and the current amount of bytes sent.
  367.             ''' </summary>
  368.             ''' ----------------------------------------------------------------------------------------------------
  369.             Private ReadOnly diffBytesSentB As Single
  370.  
  371.             ''' ----------------------------------------------------------------------------------------------------
  372.             ''' <summary>
  373.             ''' Gets the difference between the last and the current amount of bytes received.
  374.             ''' For download speed measuring purposes.
  375.             ''' </summary>
  376.             ''' ----------------------------------------------------------------------------------------------------
  377.             ''' <value>
  378.             ''' The difference between the last and the current amount of bytes received.
  379.             ''' </value>
  380.             ''' ----------------------------------------------------------------------------------------------------
  381.             Public ReadOnly Property DiffBytesReceived As Single
  382.                 Get
  383.                     Return Me.diffBytesReceivedB
  384.                 End Get
  385.             End Property
  386.             ''' ----------------------------------------------------------------------------------------------------
  387.             ''' <summary>
  388.             ''' ( Backing Field )
  389.             ''' The difference between the last and the current amount of bytes received.
  390.             ''' </summary>
  391.             ''' ----------------------------------------------------------------------------------------------------
  392.             Private ReadOnly diffBytesReceivedB As Single
  393.  
  394. #End Region
  395.  
  396. #Region " Constructors "
  397.  
  398.             ''' ----------------------------------------------------------------------------------------------------
  399.             ''' <summary>
  400.             ''' Initializes a new instance of the <see cref="TrafficChangedEventArgs"/> class.
  401.             ''' </summary>
  402.             ''' ----------------------------------------------------------------------------------------------------
  403.             ''' <param name="bytesSent">
  404.             ''' The bytes sent.
  405.             ''' </param>
  406.             '''
  407.             ''' <param name="bytesReceived">
  408.             ''' The bytes received.
  409.             ''' </param>
  410.             '''
  411.             ''' <param name="diffBytesSent">
  412.             ''' The difference between the last and the current amount of bytes sent.
  413.             ''' </param>
  414.             '''
  415.             ''' <param name="diffBytesReceived">
  416.             ''' The difference between the last and the current amount of bytes received.
  417.             ''' </param>
  418.             ''' ----------------------------------------------------------------------------------------------------
  419.             Public Sub New(ByVal bytesSent As Single,
  420.                            ByVal bytesReceived As Single,
  421.                            ByVal diffBytesSent As Single,
  422.                            ByVal diffBytesReceived As Single)
  423.  
  424.                 Me.bytesSentB = bytesSent
  425.                 Me.bytesReceivedB = bytesReceived
  426.                 Me.diffBytesSentB = diffBytesSent
  427.                 Me.diffBytesReceivedB = DiffBytesReceived
  428.  
  429.             End Sub
  430.  
  431.             ''' <summary>
  432.             ''' Prevents a default instance of the <see cref="TrafficChangedEventArgs"/> class from being created.
  433.             ''' </summary>
  434.             Private Sub New()
  435.             End Sub
  436.  
  437. #End Region
  438.  
  439.         End Class
  440.  
  441. #End Region
  442.  
  443. #End Region
  444.  
  445. #Region " Constructors "
  446.  
  447.         ''' ----------------------------------------------------------------------------------------------------
  448.         ''' <summary>
  449.         ''' Initializes a new instance of the <see cref="NetworkTrafficMonitor"/> class.
  450.         ''' </summary>
  451.         ''' ----------------------------------------------------------------------------------------------------
  452.         ''' <param name="interfaceName">
  453.         ''' The name of the interface to monitor.
  454.         ''' </param>
  455.         ''' ----------------------------------------------------------------------------------------------------
  456.         ''' <exception cref="NotImplementedException">
  457.         ''' Performance Counters doesn't include the category.
  458.         ''' </exception>
  459.         '''
  460.         ''' <exception cref="ArgumentException">
  461.         ''' The specified interface is not avaliable or doesn't exist.;interfaceName
  462.         ''' </exception>
  463.         ''' ----------------------------------------------------------------------------------------------------
  464.         <DebuggerStepThrough>
  465.         <DebuggerHidden>
  466.         Public Sub New(ByVal interfaceName As String)
  467.  
  468.             If Not Me.IsCategoryAvaliable(Me.categoryName) Then
  469.                 Throw New NotImplementedException(message:=String.Format("Performance Counters doesn't include the category '{0}'.",
  470.                                                                          Me.categoryName))
  471.  
  472.             ElseIf Not Me.IsInterfaceAvaliable(interfaceName) Then
  473.                 Throw New ArgumentException(message:="The specified interface is not avaliable or doesn't exist.",
  474.                                              paramname:="interfacename")
  475.  
  476.             Else
  477.                 Me.interfaceNameB = interfaceName
  478.                 Me.trafficUpdateTimer = New Timer
  479.  
  480.             End If
  481.  
  482.         End Sub
  483.  
  484.         ''' ----------------------------------------------------------------------------------------------------
  485.         ''' <summary>
  486.         ''' Initializes a new instance of the <see cref="NetworkTrafficMonitor"/> class.
  487.         ''' </summary>
  488.         ''' ----------------------------------------------------------------------------------------------------
  489.         ''' <param name="categoryName">
  490.         ''' The name of the performance category.
  491.         ''' </param>
  492.         '''
  493.         ''' <param name="counterNameBytesSent">
  494.         ''' The name of the Performance Counter that retrieves the bytes sent.
  495.         ''' </param>
  496.         '''
  497.         ''' <param name="counterNameBytesReceived">
  498.         ''' The name of the Performance Counter that retrieves the bytes received.
  499.         ''' </param>
  500.         ''' ----------------------------------------------------------------------------------------------------
  501.         ''' <exception cref="NotImplementedException">
  502.         ''' Performance Counters doesn't include the category.
  503.         ''' </exception>
  504.         ''' ----------------------------------------------------------------------------------------------------
  505.         <DebuggerStepThrough>
  506.         <DebuggerHidden>
  507.         Protected Sub New(ByVal categoryName As String,
  508.                           ByVal counterNameBytesSent As String,
  509.                           ByVal counterNameBytesReceived As String)
  510.  
  511.             If Not Me.IsCategoryAvaliable(categoryName) Then
  512.                 Throw New NotImplementedException(message:=String.Format("Performance Counters doesn't include the category '{0}'.",
  513.                                                                          categoryName))
  514.             End If
  515.  
  516.             Me.categoryName = categoryName
  517.             Me.counterNameBytesSent = counterNameBytesSent
  518.             Me.counterNameBytesReceived = counterNameBytesReceived
  519.  
  520.             Me.trafficUpdateTimer = New Timer
  521.  
  522.         End Sub
  523.  
  524.         ''' ----------------------------------------------------------------------------------------------------
  525.         ''' <summary>
  526.         ''' Prevents a default instance of the <see cref="NetworkTrafficMonitor"/> class from being created.
  527.         ''' </summary>
  528.         ''' ----------------------------------------------------------------------------------------------------
  529.         Private Sub New()
  530.         End Sub
  531.  
  532. #End Region
  533.  
  534. #Region " Shared Methods "
  535.  
  536.         ''' ----------------------------------------------------------------------------------------------------
  537.         ''' <summary>
  538.         ''' Gets the avaliable network interface names.
  539.         ''' </summary>
  540.         ''' ----------------------------------------------------------------------------------------------------
  541.         ''' <returns>
  542.         ''' An <see cref="IEnumerable(Of String)"/> that enumerates the avaliable network interface names.
  543.         ''' </returns>
  544.         ''' ----------------------------------------------------------------------------------------------------
  545.         <DebuggerStepThrough>
  546.         <DebuggerHidden>
  547.         Public Shared Function GetAvaliableInterfaceNames() As IEnumerable(Of String)
  548.  
  549.             If PerformanceCounterCategory.Exists("Network Interface") Then
  550.                 Return New PerformanceCounterCategory("Network Interface").GetInstanceNames
  551.  
  552.             Else
  553.                 Return Nothing
  554.  
  555.             End If
  556.  
  557.         End Function
  558.  
  559. #End Region
  560.  
  561. #Region " Public Methods "
  562.  
  563.         ''' ----------------------------------------------------------------------------------------------------
  564.         ''' <summary>
  565.         ''' Initializes the traffic monitoring.
  566.         ''' </summary>
  567.         ''' ----------------------------------------------------------------------------------------------------
  568.         <DebuggerStepThrough>
  569.         <DebuggerHidden>
  570.         Public Overridable Sub Start()
  571.  
  572.             Me.InitializeMonitor()
  573.  
  574.         End Sub
  575.  
  576.         ''' ----------------------------------------------------------------------------------------------------
  577.         ''' <summary>
  578.         ''' Finalizes the traffic monitoring.
  579.         ''' </summary>
  580.         ''' ----------------------------------------------------------------------------------------------------
  581.         <DebuggerStepThrough>
  582.         <DebuggerHidden>
  583.         Public Overridable Sub [Stop]()
  584.  
  585.             Me.isActiveB = False
  586.             If Me.trafficUpdateTimer IsNot Nothing Then
  587.                 Me.trafficUpdateTimer.Enabled = False
  588.             End If
  589.  
  590.         End Sub
  591.  
  592.         ''' ----------------------------------------------------------------------------------------------------
  593.         ''' <summary>
  594.         ''' Gets the bytes sent.
  595.         ''' </summary>
  596.         ''' ----------------------------------------------------------------------------------------------------
  597.         ''' <returns>
  598.         ''' The bytes sent.
  599.         ''' </returns>
  600.         ''' ----------------------------------------------------------------------------------------------------
  601.         <DebuggerStepThrough>
  602.         <DebuggerHidden>
  603.         Public Overridable Function GetBytesSent() As Single
  604.  
  605.             If Me.isActiveB Then
  606.                 Return Me.bytesSentPerformanceCounter.RawValue
  607.             Else
  608.                 Return Nothing
  609.             End If
  610.  
  611.         End Function
  612.  
  613.         ''' ----------------------------------------------------------------------------------------------------
  614.         ''' <summary>
  615.         ''' Gets the bytes received.
  616.         ''' </summary>
  617.         ''' ----------------------------------------------------------------------------------------------------
  618.         ''' <returns>
  619.         ''' The bytes received.
  620.         ''' </returns>
  621.         ''' ----------------------------------------------------------------------------------------------------
  622.         <DebuggerStepThrough>
  623.         <DebuggerHidden>
  624.         Public Overridable Function GetBytesReceived() As Single
  625.  
  626.             If Me.isActiveB Then
  627.                 Return Me.bytesReceivedPerformanceCounter.RawValue
  628.             Else
  629.                 Return Nothing
  630.             End If
  631.  
  632.         End Function
  633.  
  634. #End Region
  635.  
  636. #Region " Private Methods "
  637.  
  638.         ''' ----------------------------------------------------------------------------------------------------
  639.         ''' <summary>
  640.         ''' Determines whether the specified interface is avaliable.
  641.         ''' </summary>
  642.         ''' ----------------------------------------------------------------------------------------------------
  643.         ''' <param name="interfaceName">
  644.         ''' The name of the interface.
  645.         ''' </param>
  646.         ''' ----------------------------------------------------------------------------------------------------
  647.         ''' <returns>
  648.         ''' <see langword="True"/> if interface is avaliable; otherwise, <see langword="False"/>.
  649.         ''' </returns>
  650.         ''' ----------------------------------------------------------------------------------------------------
  651.         <DebuggerStepThrough>
  652.         <DebuggerHidden>
  653.         Protected Function IsInterfaceAvaliable(ByVal interfaceName As String) As Boolean
  654.  
  655.             Return (From name As String In NetworkTrafficMonitor.GetAvaliableInterfaceNames
  656.                     Where name.Equals(interfaceName, StringComparison.OrdinalIgnoreCase)).Any
  657.  
  658.         End Function
  659.  
  660.         ''' ----------------------------------------------------------------------------------------------------
  661.         ''' <summary>
  662.         ''' Determines whether the specified performance counter category is avaliable.
  663.         ''' </summary>
  664.         ''' ----------------------------------------------------------------------------------------------------
  665.         ''' <param name="categoryName">
  666.         ''' The name of the category.
  667.         ''' </param>
  668.         ''' ----------------------------------------------------------------------------------------------------
  669.         ''' <returns>
  670.         ''' <see langword="True"/> if category is avaliable; otherwise, <see langword="False"/>.
  671.         ''' </returns>
  672.         ''' ----------------------------------------------------------------------------------------------------
  673.         <DebuggerStepThrough>
  674.         <DebuggerHidden>
  675.         Protected Function IsCategoryAvaliable(ByVal categoryName As String) As Boolean
  676.  
  677.             Return PerformanceCounterCategory.Exists(categoryName)
  678.  
  679.         End Function
  680.  
  681.         ''' ----------------------------------------------------------------------------------------------------
  682.         ''' <summary>
  683.         ''' Gets the avaliable instance names of the specified performance counter category.
  684.         ''' </summary>
  685.         ''' ----------------------------------------------------------------------------------------------------
  686.         ''' <returns>
  687.         ''' An <see cref="IEnumerable(Of String)"/> that enumerates the avaliable instance names.
  688.         ''' </returns>
  689.         ''' ----------------------------------------------------------------------------------------------------
  690.         <DebuggerStepThrough>
  691.         <DebuggerHidden>
  692.         Protected Overridable Function GetAvaliableInstanceNames(ByVal categoryName As String) As IEnumerable(Of String)
  693.  
  694.             If Me.IsCategoryAvaliable(categoryName) Then
  695.                 Return New PerformanceCounterCategory(categoryName).GetInstanceNames
  696.  
  697.             Else
  698.                 Return Nothing
  699.  
  700.             End If
  701.  
  702.         End Function
  703.  
  704.         ''' ----------------------------------------------------------------------------------------------------
  705.         ''' <summary>
  706.         ''' Initializes the performance counters.
  707.         ''' </summary>
  708.         ''' ----------------------------------------------------------------------------------------------------
  709.         <DebuggerStepThrough>
  710.         <DebuggerHidden>
  711.         Protected Overridable Sub InitializeMonitor()
  712.  
  713.             If Not Me.isActiveB Then
  714.  
  715.                 If Me.IsInterfaceAvaliable(Me.interfaceNameB) Then
  716.  
  717.                     Me.bytesSentPerformanceCounter = New PerformanceCounter
  718.                     With bytesSentPerformanceCounter
  719.                         .CategoryName = Me.categoryName
  720.                         .CounterName = Me.counterNameBytesSent
  721.                         .InstanceName = Me.interfaceNameB
  722.                         .[ReadOnly] = True
  723.                     End With
  724.  
  725.                     Me.bytesReceivedPerformanceCounter = New PerformanceCounter
  726.                     With bytesReceivedPerformanceCounter
  727.                         .CategoryName = Me.categoryName
  728.                         .CounterName = Me.counterNameBytesReceived
  729.                         .InstanceName = Me.interfaceNameB
  730.                         .[ReadOnly] = True
  731.                     End With
  732.  
  733.                     Me.isActiveB = True
  734.                     Me.trafficUpdateTimer.Enabled = True
  735.  
  736.                 End If
  737.  
  738.             End If
  739.  
  740.         End Sub
  741.  
  742.         ''' ----------------------------------------------------------------------------------------------------
  743.         ''' <summary>
  744.         ''' Finalizes the performance counters.
  745.         ''' </summary>
  746.         ''' ----------------------------------------------------------------------------------------------------
  747.         <DebuggerStepThrough>
  748.         <DebuggerHidden>
  749.         Protected Overridable Sub FinalizeMonitor()
  750.  
  751.             Me.isActiveB = False
  752.  
  753.             If Me.trafficUpdateTimer IsNot Nothing Then
  754.                 Me.trafficUpdateTimer.Enabled = False
  755.                 Me.trafficUpdateTimer.Dispose()
  756.             End If
  757.  
  758.             If Me.bytesSentPerformanceCounter IsNot Nothing Then
  759.                 Me.bytesSentPerformanceCounter.RemoveInstance()
  760.                 Me.bytesSentPerformanceCounter.Close()
  761.             End If
  762.  
  763.             If Me.bytesReceivedPerformanceCounter IsNot Nothing Then
  764.                 Me.bytesReceivedPerformanceCounter.RemoveInstance()
  765.                 Me.bytesReceivedPerformanceCounter.Close()
  766.             End If
  767.  
  768.         End Sub
  769.  
  770. #End Region
  771.  
  772. #Region " Event-Handlers "
  773.  
  774.         ''' ----------------------------------------------------------------------------------------------------
  775.         ''' <summary>
  776.         ''' Handles the <see cref="Timer.Tick"/> event of the <see cref="TrafficUpdateTimer"/> control.
  777.         ''' </summary>
  778.         ''' ----------------------------------------------------------------------------------------------------
  779.         ''' <param name="sender">
  780.         ''' The source of the event.
  781.         ''' </param>
  782.         ''' ----------------------------------------------------------------------------------------------------
  783.         ''' <param name="e">
  784.         ''' The <see cref="EventArgs"/> instance containing the event data.
  785.         ''' </param>
  786.         ''' ----------------------------------------------------------------------------------------------------
  787.         <DebuggerStepThrough>
  788.         <DebuggerHidden>
  789.         Protected Overridable Sub TrafficUpdateTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
  790.         Handles trafficUpdateTimer.Tick
  791.  
  792.             If (TrafficChangedEvent IsNot Nothing) Then
  793.  
  794.                 Static isFirstUpdate As Boolean = True
  795.  
  796.                 Static lastBytesSent As Single
  797.                 Static lastBytesReceived As Single
  798.  
  799.                 Dim currentBytesSent As Single = Me.GetBytesSent
  800.                 Dim currentBytesReceived As Single = Me.GetBytesReceived
  801.  
  802.                 Dim diffBytessSent As Single = If(isFirstUpdate, 0, (currentBytesSent - lastBytesSent))
  803.                 Dim diffBytesReceived As Single = If(isFirstUpdate, 0, (currentBytesReceived - lastBytesReceived))
  804.  
  805.                 Dim needUpdate As Boolean = False
  806.  
  807.                 If (currentBytesSent <> lastBytesSent) OrElse (currentBytesReceived <> lastBytesReceived) Then
  808.                     needUpdate = True
  809.                     isFirstUpdate = False
  810.                 End If
  811.  
  812.                 lastBytesSent = currentBytesSent
  813.                 lastBytesReceived = currentBytesReceived
  814.  
  815.                 If (Me.UpdateBehavior = UpdateBehaviorEnum.FireAlwaysAfterTick) OrElse
  816.                    (needUpdate AndAlso Me.UpdateBehavior = UpdateBehaviorEnum.FireWhenTrafficChangesAfterTick) Then
  817.  
  818.                     RaiseEvent TrafficChanged(Me, New TrafficChangedEventArgs(currentBytesSent, currentBytesReceived,
  819.                                                                               diffBytessSent, diffBytesReceived))
  820.                 End If
  821.  
  822.             End If
  823.  
  824.         End Sub
  825.  
  826. #End Region
  827.  
  828. #Region " IDisposable Implementation "
  829.  
  830.         ''' ----------------------------------------------------------------------------------------------------
  831.         ''' <summary>
  832.         ''' To detect redundant calls when disposing.
  833.         ''' </summary>
  834.         ''' ----------------------------------------------------------------------------------------------------
  835.         Protected isDisposed As Boolean = False
  836.  
  837.         ''' ----------------------------------------------------------------------------------------------------
  838.         ''' <summary>
  839.         ''' Releases all resources used by this instance.
  840.         ''' </summary>
  841.         ''' ----------------------------------------------------------------------------------------------------
  842.         ''' <remarks>
  843.         ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  844.         ''' </remarks>
  845.         ''' ----------------------------------------------------------------------------------------------------
  846.         <DebuggerStepThrough>
  847.         Public Sub Dispose() Implements IDisposable.Dispose
  848.             Me.Dispose(isDisposing:=True)
  849.             GC.SuppressFinalize(obj:=Me)
  850.         End Sub
  851.  
  852.         ''' ----------------------------------------------------------------------------------------------------
  853.         ''' <summary>
  854.         ''' Releases unmanaged and - optionally - managed resources.
  855.         ''' </summary>
  856.         ''' ----------------------------------------------------------------------------------------------------
  857.         ''' <param name="isDisposing">
  858.         ''' <c>True</c> to release both managed and unmanaged resources;
  859.         ''' <c>False</c> to release only unmanaged resources.
  860.         ''' </param>
  861.         ''' ----------------------------------------------------------------------------------------------------
  862.         <DebuggerStepThrough>
  863.         Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)
  864.  
  865.             If (Not Me.isDisposed) AndAlso (isDisposing) Then
  866.                 Me.FinalizeMonitor()
  867.             End If
  868.  
  869.             Me.isDisposed = True
  870.  
  871.         End Sub
  872.  
  873. #End Region
  874.  
  875.     End Class
  876.  
  877. #End Region
  878.  
  879. #Region " Process Traffic Monitor "
  880.  
  881.     ''' ----------------------------------------------------------------------------------------------------
  882.     ''' <summary>
  883.     ''' Monitorizes the network traffic of a process.
  884.     ''' </summary>
  885.     ''' ----------------------------------------------------------------------------------------------------
  886.     Public Class ProcessTrafficMonitor : Inherits NetworkTrafficMonitor
  887.  
  888. #Region " Hidden Base Members "
  889.  
  890.         <EditorBrowsable(EditorBrowsableState.Never)>
  891.         Friend Shadows InterfaceName As Object
  892.  
  893.         <EditorBrowsable(EditorBrowsableState.Never)>
  894.         Private Shadows getAvaliableInterfaceNames As Object
  895.  
  896. #End Region
  897.  
  898. #Region " Properties "
  899.  
  900.         ''' ----------------------------------------------------------------------------------------------------
  901.         ''' <summary>
  902.         ''' Gets the name of the process that is being monitored.
  903.         ''' </summary>
  904.         ''' ----------------------------------------------------------------------------------------------------
  905.         ''' <value>
  906.         ''' The name of the process that is being monitored.
  907.         ''' </value>
  908.         ''' ----------------------------------------------------------------------------------------------------
  909.         Public Overridable ReadOnly Property ProcessId As Integer
  910.             Get
  911.                 Return Me.processIdB
  912.             End Get
  913.         End Property
  914.         ''' ----------------------------------------------------------------------------------------------------
  915.         ''' <summary>
  916.         ''' ( Backing Field )
  917.         ''' The name of the process that is being monitored.
  918.         ''' </summary>
  919.         ''' ----------------------------------------------------------------------------------------------------
  920.         Protected ReadOnly processIdB As Integer
  921.  
  922. #End Region
  923.  
  924. #Region " Constructors "
  925.  
  926.         ''' ----------------------------------------------------------------------------------------------------
  927.         ''' <summary>
  928.         ''' Initializes a new instance of the <see cref="ProcessTrafficMonitor"/> class.
  929.         ''' </summary>
  930.         ''' ----------------------------------------------------------------------------------------------------
  931.         ''' <param name="processId">
  932.         ''' The PID of the process to monitor.
  933.         ''' Note that the process should have the performance counters feature enabled to be able to use the counters.
  934.         ''' </param>
  935.         ''' ----------------------------------------------------------------------------------------------------
  936.         ''' <remarks>
  937.         ''' The application's configuration file (app.config) should look like this:
  938.         '''
  939.         ''' <code>
  940.         ''' <![CDATA[<?xml version="1.0" encoding="utf-8"?>
  941.         ''' <configuration>
  942.         ''' ...
  943.         '''   <system.net>
  944.         '''     <settings>
  945.         '''       <performanceCounters enabled="true"/>
  946.         '''     </settings>
  947.         '''   </system.net>
  948.         ''' ...
  949.         ''' </configuration>]]>
  950.         ''' </code>
  951.         '''
  952.         ''' MSDN Documentation: <see href="http://msdn.microsoft.com/en-us/library/ms229151%28v=vs.110%29.aspx"/>
  953.         ''' </remarks>
  954.         ''' ----------------------------------------------------------------------------------------------------
  955.         <DebuggerStepThrough>
  956.         <DebuggerHidden>
  957.         Public Sub New(ByVal processId As Integer)
  958.  
  959.             MyBase.New(categoryName:=".NET CLR Networking 4.0.0.0",
  960.                        counterNameBytesSent:="Bytes Sent",
  961.                        counterNameBytesReceived:="Bytes Received")
  962.  
  963.             Me.processIdB = processId
  964.  
  965.         End Sub
  966.  
  967. #End Region
  968.  
  969. #Region " Private Methods "
  970.  
  971.         ''' ----------------------------------------------------------------------------------------------------
  972.         ''' <summary>
  973.         ''' Initializes the performance counters.
  974.         ''' </summary>
  975.         ''' ----------------------------------------------------------------------------------------------------
  976.         <DebuggerStepThrough>
  977.         <DebuggerHidden>
  978.         Protected Overrides Sub InitializeMonitor()
  979.  
  980.             If Not MyBase.isActiveB Then
  981.  
  982.                 Dim instanceNames As IEnumerable(Of String) =
  983.                     From name As String In MyBase.GetAvaliableInstanceNames(MyBase.categoryName)
  984.                     Where name.Contains(String.Format("p{0}", Me.processIdB))
  985.  
  986.                 If instanceNames.Any() Then
  987.  
  988.                     MyBase.bytesSentPerformanceCounter = New PerformanceCounter
  989.                     With MyBase.bytesSentPerformanceCounter
  990.                         .CategoryName = MyBase.categoryName
  991.                         .CounterName = MyBase.counterNameBytesSent
  992.                         .InstanceName = instanceNames.First
  993.                         .[ReadOnly] = True
  994.                     End With
  995.  
  996.                     MyBase.bytesReceivedPerformanceCounter = New PerformanceCounter
  997.                     With MyBase.bytesReceivedPerformanceCounter
  998.                         .CategoryName = MyBase.categoryName
  999.                         .CounterName = MyBase.counterNameBytesReceived
  1000.                         .InstanceName = instanceNames.First
  1001.                         .[ReadOnly] = True
  1002.                     End With
  1003.  
  1004.                     MyBase.isActiveB = True
  1005.                     MyBase.trafficUpdateTimer.Enabled = True
  1006.  
  1007.                 End If
  1008.  
  1009.             End If
  1010.  
  1011.         End Sub
  1012.  
  1013. #End Region
  1014.  
  1015.     End Class
  1016.  
  1017. #End Region
  1018.  
  1019. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement