Advertisement
Guest User

Network/Process Traffic Monitor in VBNet - By Elektro

a guest
Sep 19th, 2015
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 62.49 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 " Enumerations "
  20.  
  21. ' NetworkUtil.NetworkTrafficMonitor.UpdateBehavior As Integer
  22. ' NetworkUtil.ProcessTrafficMonitor.UpdateBehavior As Integer
  23.  
  24. #End Region
  25.  
  26. #Region " Events "
  27.  
  28. ' NetworkUtil.NetworkStatusChanged(Object, NetworkUtil.NetworkStatusChangedArgs)
  29. ' NetworkUtil.NetworkTrafficMonitor.TrafficChanged(Object, NetworkTrafficMonitor.TrafficChangedEventArgs)
  30. ' NetworkUtil.ProcessTrafficMonitor.TrafficChanged(Object, NetworkTrafficMonitor.TrafficChangedEventArgs)
  31.  
  32. #End Region
  33.  
  34. #Region " Properties "
  35.  
  36. ' NetworkUtil.TcpConnections As IEnumerable(Of TcpConnectionInformation)
  37. ' NetworkUtil.IsNetworkAvailable As Boolean
  38. ' NetworkUtil.NetworkInterfaceNames As IEnumerable(Of String)
  39.  
  40. ' NetworkUtil.NetworkTrafficMonitor.InterfaceName As string
  41. ' NetworkUtil.NetworkTrafficMonitor.IsActive As Boolean
  42. ' NetworkUtil.NetworkTrafficMonitor.UpdateBehavior As NetworkTrafficMonitor.UpdateBehaviorEnum
  43. ' NetworkUtil.NetworkTrafficMonitor.UpdateInterval As Integer
  44.  
  45. ' NetworkUtil.ProcessTrafficMonitor.ProcessId As Integer
  46. ' NetworkUtil.ProcessTrafficMonitor.IsActive As Boolean
  47. ' NetworkUtil.ProcessTrafficMonitor.UpdateBehavior As NetworkTrafficMonitor.UpdateBehaviorEnum
  48. ' NetworkUtil.ProcessTrafficMonitor.UpdateInterval As Integer
  49.  
  50. #End Region
  51.  
  52. #Region " Methods "
  53.  
  54. ' NetworkUtil.NetworkTrafficMonitor.New(String)
  55. ' NetworkUtil.NetworkTrafficMonitor.Start
  56. ' NetworkUtil.NetworkTrafficMonitor.Stop
  57. ' NetworkUtil.NetworkTrafficMonitor.Dispose
  58.  
  59. ' NetworkUtil.ProcessTrafficMonitor.New(Integer)
  60. ' NetworkUtil.ProcessTrafficMonitor.Start
  61. ' NetworkUtil.ProcessTrafficMonitor.Stop
  62. ' NetworkUtil.ProcessTrafficMonitor.Dispose
  63.  
  64. #End Region
  65.  
  66. #Region " Functions "
  67.  
  68. ' NetworkUtil.NetworkTrafficMonitor.GetAvaliableInterfaceNames As IEnumerable(Of String)
  69. ' NetworkUtil.NetworkTrafficMonitor.GetBytesReceived As Single
  70. ' NetworkUtil.NetworkTrafficMonitor.GetBytesSent As Single
  71.  
  72. ' NetworkUtil.ProcessTrafficMonitor.GetBytesReceived As Single
  73. ' NetworkUtil.ProcessTrafficMonitor.GetBytesSent As Single
  74.  
  75. #End Region
  76.  
  77. #End Region
  78.  
  79. #Region " Option Statements "
  80.  
  81. Option Strict On
  82. Option Explicit On
  83. Option Infer Off
  84.  
  85. #End Region
  86.  
  87. #Region " Imports "
  88.  
  89. Imports System
  90. Imports System.Collections.Generic
  91. Imports System.ComponentModel
  92. Imports System.Diagnostics
  93. Imports System.Linq
  94. Imports System.Net.NetworkInformation
  95. Imports System.Runtime.CompilerServices
  96. Imports System.Windows.Forms
  97.  
  98. #End Region
  99.  
  100. #Region " Network Util "
  101.  
  102. ''' ----------------------------------------------------------------------------------------------------
  103. ''' <summary>
  104. ''' Contains related Network utilities.
  105. ''' </summary>
  106. ''' ----------------------------------------------------------------------------------------------------
  107. Public NotInheritable Class NetworkUtil
  108.  
  109. #Region " Properties "
  110.  
  111.     ''' ----------------------------------------------------------------------------------------------------
  112.     ''' <summary>
  113.     ''' Gets a value indicating whether at least one of the current network adapters is capable of connecting to Internet.
  114.     ''' </summary>
  115.     ''' ----------------------------------------------------------------------------------------------------
  116.     ''' <value>
  117.     ''' <c>True</c> if at least one of the current network adapters is capable of connecting to Internet;
  118.     ''' otherwise, <c>False</c>.
  119.     ''' </value>
  120.     ''' ----------------------------------------------------------------------------------------------------
  121.     Public Shared ReadOnly Property IsNetworkAvailable As Boolean
  122.         Get
  123.             Return NetworkUtil.GetNetworkAvailable
  124.         End Get
  125.     End Property
  126.  
  127.     ''' ----------------------------------------------------------------------------------------------------
  128.     ''' <summary>
  129.     ''' Gets the active TCP connctions.
  130.     ''' </summary>
  131.     ''' ----------------------------------------------------------------------------------------------------
  132.     ''' <example> This is a code example.
  133.     ''' <code>
  134.     ''' Dim tcpConnections As IEnumerable(Of TcpConnectionInformation) = NetworkUtil.TcpConnctions
  135.     '''
  136.     ''' For Each tcpInfo As TcpConnectionInformation In tcpConnections
  137.     '''
  138.     '''     Console.WriteLine("Local: {0}:{1} | Remote: {2}:{3} | State: {4}",
  139.     '''                       tcpInfo.LocalEndPoint.Address.ToString, tcpInfo.LocalEndPoint.Port.ToString,
  140.     '''                       tcpInfo.RemoteEndPoint.Address.ToString, tcpInfo.RemoteEndPoint.Port.ToString,
  141.     '''                       tcpInfo.State.ToString)
  142.     '''
  143.     ''' Next tcpInfo
  144.     ''' </code>
  145.     ''' </example>
  146.     ''' ----------------------------------------------------------------------------------------------------
  147.     ''' <value>The TCP connctions.</value>
  148.     ''' ----------------------------------------------------------------------------------------------------
  149.     Public Shared ReadOnly Property TcpConnctions As IEnumerable(Of NetworkInformation.TcpConnectionInformation)
  150.         Get
  151.             Return IPGlobalProperties.GetIPGlobalProperties.GetActiveTcpConnections.AsEnumerable
  152.         End Get
  153.     End Property
  154.  
  155.     ''' ----------------------------------------------------------------------------------------------------
  156.     ''' <summary>
  157.     ''' Gets the current network interface names.
  158.     ''' </summary>
  159.     ''' ----------------------------------------------------------------------------------------------------
  160.     ''' <value>
  161.     ''' An <see cref="IEnumerable(Of String)"/> that enumerates the network interface names.
  162.     ''' </value>
  163.     ''' ----------------------------------------------------------------------------------------------------
  164.     Public Shared ReadOnly Property NetworkInterfaceNames As IEnumerable(Of String)
  165.  
  166.         <DebuggerStepThrough>
  167.         <DebuggerHidden>
  168.         Get
  169.             Return From ni As NetworkInterface In NetworkInterface.GetAllNetworkInterfaces()
  170.                    Select ni.Description
  171.         End Get
  172.     End Property
  173.  
  174. #End Region
  175.  
  176. #Region " Events "
  177.  
  178.     Private Shared networkStatusHandler As NetworkStatusChangedArgs.NetworkStatusChangedDelegate
  179.  
  180.     ''' ----------------------------------------------------------------------------------------------------
  181.     ''' <summary>
  182.     ''' Occurs when the state of Internet connectivity changes.
  183.     ''' </summary>
  184.     ''' ----------------------------------------------------------------------------------------------------
  185.     ''' <example> This is a code example.
  186.     ''' <code>
  187.     ''' Public Class Form1
  188.     '''
  189.     '''     Private Sub Form1_Shown() Handles MyBase.Load
  190.     '''
  191.     '''         AddHandler NetworkUtil.NetworkStatusChanged, AddressOf DoNetworkStatusChanged
  192.     '''
  193.     '''     End Sub
  194.     '''
  195.     '''     Private Sub DoNetworkStatusChanged(ByVal sender As Object, e As NetworkUtil.NetworkStatusChangedArgs)
  196.     '''
  197.     '''         If e.IsAvailable Then
  198.     '''             Console.WriteLine("Network is available.")
  199.     '''
  200.     '''         Else
  201.     '''             Console.WriteLine("Network is not available.")
  202.     '''
  203.     '''         End If
  204.     '''
  205.     '''     End Sub
  206.     '''
  207.     ''' End Class
  208.     ''' </code>
  209.     ''' </example>
  210.     Public Shared Custom Event NetworkStatusChanged As NetworkStatusChangedArgs.NetworkStatusChangedDelegate
  211.  
  212.         <MethodImpl(MethodImplOptions.Synchronized)>
  213.         AddHandler(ByVal value As NetworkStatusChangedArgs.NetworkStatusChangedDelegate)
  214.  
  215.             If networkStatusHandler Is Nothing Then
  216.                 AddHandler NetworkChange.NetworkAvailabilityChanged, AddressOf DoNetworkAvailabilityChanged
  217.                 AddHandler NetworkChange.NetworkAddressChanged, AddressOf DoNetworkAddressChanged
  218.             End If
  219.  
  220.             networkStatusHandler = DirectCast([Delegate].Combine(networkStatusHandler, value), NetworkStatusChangedArgs.NetworkStatusChangedDelegate)
  221.  
  222.         End AddHandler
  223.  
  224.         <MethodImpl(MethodImplOptions.Synchronized)>
  225.         RemoveHandler(ByVal value As NetworkStatusChangedArgs.NetworkStatusChangedDelegate)
  226.  
  227.             networkStatusHandler = DirectCast([Delegate].Remove(networkStatusHandler, value), NetworkStatusChangedArgs.NetworkStatusChangedDelegate)
  228.  
  229.             If networkStatusHandler Is Nothing Then
  230.                 AddHandler NetworkChange.NetworkAvailabilityChanged, AddressOf DoNetworkAvailabilityChanged
  231.                 AddHandler NetworkChange.NetworkAddressChanged, AddressOf DoNetworkAddressChanged
  232.             End If
  233.  
  234.         End RemoveHandler
  235.  
  236.         <MethodImpl(MethodImplOptions.Synchronized)>
  237.         RaiseEvent(ByVal sender As Object, ByVal e As NetworkStatusChangedArgs)
  238.             NetworkUtil.networkStatusHandler(sender, e)
  239.         End RaiseEvent
  240.  
  241.     End Event
  242.  
  243. #Region " NetworkStatusChanged EventArgs "
  244.  
  245.     ''' ----------------------------------------------------------------------------------------------------
  246.     ''' <summary>
  247.     ''' Contains the event-data of a <see cref="NetworkStatusChanged"/> event.
  248.     ''' </summary>
  249.     ''' ----------------------------------------------------------------------------------------------------
  250.     Public NotInheritable Class NetworkStatusChangedArgs : Inherits EventArgs
  251.  
  252. #Region " Delegates "
  253.  
  254.         ''' ----------------------------------------------------------------------------------------------------
  255.         ''' <summary>
  256.         ''' Delegate NetworkStatusChangedHandler. Define the method signature for network status changes.
  257.         ''' </summary>
  258.         ''' ----------------------------------------------------------------------------------------------------
  259.         ''' <param name="sender">
  260.         ''' The source of the event.
  261.         ''' </param>
  262.         '''
  263.         ''' <param name="e">
  264.         ''' The <see cref="NetworkUtil.NetworkStatusChangedArgs"/> instance containing the event data.
  265.         ''' </param>
  266.         ''' ----------------------------------------------------------------------------------------------------
  267.         Public Delegate Sub NetworkStatusChangedDelegate(ByVal sender As Object, ByVal e As NetworkUtil.NetworkStatusChangedArgs)
  268.  
  269. #End Region
  270.  
  271. #Region " Properties "
  272.  
  273.         ''' <summary>
  274.         ''' Gets a <see langword="Boolean"/> value indicating the current state of internet connectivity.
  275.         ''' </summary>
  276.         Public ReadOnly Property IsAvailable() As Boolean
  277.             Get
  278.                 Return Me.isAvailableB
  279.             End Get
  280.         End Property
  281.         ''' <summary>
  282.         ''' ( Backing Field )
  283.         ''' A <see langword="Boolean"/> value indicating the current state of internet connectivity.
  284.         ''' </summary>
  285.         Private ReadOnly isAvailableB As Boolean
  286.  
  287. #End Region
  288.  
  289. #Region " Constructors "
  290.  
  291.         ''' ----------------------------------------------------------------------------------------------------
  292.         ''' <summary>
  293.         ''' Initializes a new instance of the <see cref="NetworkStatusChangedArgs"/> class.
  294.         ''' </summary>
  295.         ''' ----------------------------------------------------------------------------------------------------
  296.         ''' <param name="isAvailable">
  297.         ''' A <see langword="Boolean"/> value indicating the current state of Internet connectivity.
  298.         ''' </param>
  299.         ''' ----------------------------------------------------------------------------------------------------
  300.         Public Sub New(ByVal isAvailable As Boolean)
  301.             Me.isAvailableB = isAvailable
  302.         End Sub
  303.  
  304. #End Region
  305.  
  306.     End Class
  307.  
  308. #End Region
  309.  
  310. #End Region
  311.  
  312. #Region " Constructors "
  313.  
  314.     ''' <summary>
  315.     ''' Prevents a default instance of the <see cref="NetworkUtil"/> class from being created.
  316.     ''' </summary>
  317.     Private Sub New()
  318.     End Sub
  319.  
  320. #End Region
  321.  
  322. #Region " Event-Handlers "
  323.  
  324.     ''' ----------------------------------------------------------------------------------------------------
  325.     ''' <summary>
  326.     ''' Handles the <see cref="System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged"/> event.
  327.     ''' </summary>
  328.     ''' ----------------------------------------------------------------------------------------------------
  329.     ''' <param name="sender">
  330.     ''' The source of the event.
  331.     ''' </param>
  332.     '''
  333.     ''' <param name="e">
  334.     ''' The <see cref="System.Net.NetworkInformation.NetworkAvailabilityEventArgs"/> instance containing the event data.
  335.     ''' </param>
  336.     ''' ----------------------------------------------------------------------------------------------------
  337.     Private Shared Sub DoNetworkAvailabilityChanged(ByVal sender As Object, ByVal e As NetworkAvailabilityEventArgs)
  338.  
  339.         NetworkUtil.RaiseNetworkChange(sender)
  340.  
  341.     End Sub
  342.  
  343.     ''' ----------------------------------------------------------------------------------------------------
  344.     ''' <summary>
  345.     ''' Handles the <see cref="System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged"/> event.
  346.     ''' </summary>
  347.     ''' ----------------------------------------------------------------------------------------------------
  348.     ''' <param name="sender">
  349.     ''' The source of the event.
  350.     ''' </param>
  351.     '''
  352.     ''' <param name="e">
  353.     ''' The <see cref="EventArgs"/> instance containing the event data.
  354.     ''' </param>
  355.     ''' ----------------------------------------------------------------------------------------------------
  356.     Private Shared Sub DoNetworkAddressChanged(ByVal sender As Object, ByVal e As EventArgs)
  357.  
  358.         NetworkUtil.RaiseNetworkChange(sender)
  359.  
  360.     End Sub
  361.  
  362. #End Region
  363.  
  364. #Region " Private Methods "
  365.  
  366.     ''' ----------------------------------------------------------------------------------------------------
  367.     ''' <summary>
  368.     ''' Evaluate the online network adapters to determine if at least one of them is capable of connecting to Internet.
  369.     ''' </summary>
  370.     ''' ----------------------------------------------------------------------------------------------------
  371.     ''' <returns>
  372.     ''' <c>True</c> if at least one of the current network adapters is capable of connecting to Internet;
  373.     ''' otherwise, <c>False</c>.
  374.     ''' </returns>
  375.     ''' ----------------------------------------------------------------------------------------------------
  376.     Private Shared Function GetNetworkAvailable() As Boolean
  377.  
  378.         ' Only recognizes changes related to Internet adapters.
  379.         If NetworkInterface.GetIsNetworkAvailable() Then
  380.  
  381.             ' However, this will include all adapters.
  382.             Dim interfaces As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
  383.  
  384.             For Each ni As NetworkInterface In interfaces
  385.  
  386.                 ' Filter so we see only Internet adapters.
  387.                 If ni.OperationalStatus = OperationalStatus.Up Then
  388.  
  389.                     If (ni.NetworkInterfaceType <> NetworkInterfaceType.Tunnel) AndAlso
  390.                        (ni.NetworkInterfaceType <> NetworkInterfaceType.Loopback) Then
  391.  
  392.                         Dim statistics As IPv4InterfaceStatistics = ni.GetIPv4Statistics()
  393.  
  394.                         ' All testing seems to prove that once an interface comes online
  395.                         ' it has already accrued statistics for both received and sent...
  396.                         If (statistics.BytesReceived > 0) AndAlso (statistics.BytesSent > 0) Then
  397.                             Return True
  398.                         End If
  399.  
  400.                     End If
  401.  
  402.                 End If
  403.  
  404.             Next ni
  405.  
  406.         End If
  407.  
  408.         Return False
  409.  
  410.     End Function
  411.  
  412.     ''' ----------------------------------------------------------------------------------------------------
  413.     ''' <summary>
  414.     ''' Raises the network change event.
  415.     ''' </summary>
  416.     ''' ----------------------------------------------------------------------------------------------------
  417.     ''' <param name="sender">
  418.     ''' The source of the event.
  419.     ''' </param>
  420.     ''' ----------------------------------------------------------------------------------------------------
  421.     Private Shared Sub RaiseNetworkChange(ByVal sender As Object)
  422.  
  423.         Static isNetworkAvailable As Boolean = Not NetworkUtil.GetNetworkAvailable
  424.         Dim change As Boolean = NetworkUtil.GetNetworkAvailable()
  425.  
  426.         If (change <> isNetworkAvailable) Then
  427.  
  428.             isNetworkAvailable = change
  429.             RaiseEvent NetworkStatusChanged(sender, New NetworkStatusChangedArgs(change))
  430.  
  431.         End If
  432.  
  433.     End Sub
  434.  
  435. #End Region
  436.  
  437. #Region " Sub-Classes "
  438.  
  439. #Region " Network Traffic Monitor "
  440.  
  441.     ''' ----------------------------------------------------------------------------------------------------
  442.     ''' <summary>
  443.     ''' Monitorizes the traffic of a network interface.
  444.     ''' </summary>
  445.     ''' ----------------------------------------------------------------------------------------------------
  446.     ''' <example> This is a code example.
  447.     ''' <code>
  448.     ''' Public NotInheritable Class Form1 : Inherits Form
  449.     '''
  450.     '''     Dim WithEvents netMon As NetworkUtil.NetworkTrafficMonitor
  451.     '''
  452.     '''     Private Sub Form1_Load() Handles MyBase.Load
  453.     '''
  454.     '''         Me.netMon = New NetworkUtil.NetworkTrafficMonitor(NetworkUtil.NetworkTrafficMonitor.GetAvaliableInterfaceNames.First)
  455.     '''         Me.netMon.UpdateBehavior = NetworkUtil.NetworkTrafficMonitor.UpdateBehaviorEnum.FireAlwaysAfterTick
  456.     '''         Me.netMon.UpdateInterval = 1000 ' 1 sec
  457.     '''         Me.netMon.Start()
  458.     '''
  459.     '''     End Sub
  460.     '''
  461.     '''     ''' ----------------------------------------------------------------------------------------------------
  462.     '''     ''' <summary>
  463.     '''     ''' Handles the <see cref="NetworkUtil.NetworkTrafficMonitor.TrafficChanged"/> event of the netMon instance.
  464.     '''     ''' </summary>
  465.     '''     ''' ----------------------------------------------------------------------------------------------------
  466.     '''     ''' <param name="sender">T
  467.     '''     ''' The source of the event.
  468.     '''     ''' </param>
  469.     '''     '''
  470.     '''     ''' <param name="e">
  471.     '''     ''' The <see cref="NetworkUtil.NetworkTrafficMonitor.TrafficChangedEventArgs"/> instance containing the event data.
  472.     '''     ''' </param>
  473.     '''     ''' ----------------------------------------------------------------------------------------------------
  474.     '''     Private Sub NetMon_TrafficChanged(ByVal sender As Object, ByVal e As NetworkUtil.NetworkTrafficMonitor.TrafficChangedEventArgs) _
  475.     '''     Handles netMon.TrafficChanged
  476.     '''
  477.     '''         Me.LabelBytesReceived.Text = String.Format("Bytes received: {0} kb", (e.BytesReceived / 1024).ToString("n2"))
  478.     '''         Me.LabelDlSpeed.Text = String.Format("DL Speed: {0} kb/sec", (e.DiffBytesReceived / 1024).ToString("n2"))
  479.     '''
  480.     '''         Me.LabelBytesSent.Text = String.Format("Bytes sent: {0} kb", (e.BytesSent / 1024).ToString("n2"))
  481.     '''         Me.LabelUlSpeed.Text = String.Format("UL Speed: {0} kb/sec", (e.DiffBytesSent / 1024).ToString("n2"))
  482.     '''
  483.     '''     End Sub
  484.     '''
  485.     '''     Private Sub BtDownloadUrl_Click() Handles BtDownloadUrl.Click
  486.     '''
  487.     '''         Dim url As String = "http://download.thinkbroadband.com/10MB.zip"
  488.     '''         Dim client As New WebClient()
  489.     '''         client.DownloadFileAsync(New Uri(url), Path.GetTempFileName())
  490.     '''
  491.     '''     End Sub
  492.     '''
  493.     '''     Private Sub BtPauseMon_Click() Handles BtPauseMon.Click
  494.     '''
  495.     '''         If Me.netMon.IsActive Then
  496.     '''             Me.netMon.Stop()
  497.     '''         Else
  498.     '''             Me.netMon.Start()
  499.     '''         End If
  500.     '''
  501.     '''     End Sub
  502.     '''
  503.     ''' End Class
  504.     ''' </code>
  505.     ''' </example>
  506.     ''' ----------------------------------------------------------------------------------------------------
  507.     Public Class NetworkTrafficMonitor : Implements IDisposable
  508.  
  509. #Region " Objects / Read-Only vars. "
  510.  
  511.         ''' ----------------------------------------------------------------------------------------------------
  512.         ''' <summary>
  513.         ''' The performance counter that monitors the bytes sent.
  514.         ''' </summary>
  515.         ''' ----------------------------------------------------------------------------------------------------
  516.         Protected bytesSentPerformanceCounter As PerformanceCounter
  517.  
  518.         ''' ----------------------------------------------------------------------------------------------------
  519.         ''' <summary>
  520.         ''' The performance counter that monitors the bytes received.
  521.         ''' </summary>
  522.         ''' ----------------------------------------------------------------------------------------------------
  523.         Protected bytesReceivedPerformanceCounter As PerformanceCounter
  524.  
  525.         ''' ----------------------------------------------------------------------------------------------------
  526.         ''' <summary>
  527.         ''' The name of the Performance Counters category.
  528.         ''' </summary>
  529.         ''' ----------------------------------------------------------------------------------------------------
  530.         Protected ReadOnly categoryName As String = "Network Interface"
  531.  
  532.         ''' ----------------------------------------------------------------------------------------------------
  533.         ''' <summary>
  534.         ''' The name of the Performance Counter that retrieves the bytes sent.
  535.         ''' </summary>
  536.         ''' ----------------------------------------------------------------------------------------------------
  537.         Protected ReadOnly counterNameBytesSent As String = "Bytes Sent/sec"
  538.  
  539.         ''' ----------------------------------------------------------------------------------------------------
  540.         ''' <summary>
  541.         ''' The name of the Performance Counter that retrieves the bytes received.
  542.         ''' </summary>
  543.         ''' ----------------------------------------------------------------------------------------------------
  544.         Protected ReadOnly counterNameBytesReceived As String = "Bytes Received/sec"
  545.  
  546.         ''' ----------------------------------------------------------------------------------------------------
  547.         ''' <summary>
  548.         ''' Timer that manages the counters update interval.
  549.         ''' </summary>
  550.         ''' ----------------------------------------------------------------------------------------------------
  551.         Protected WithEvents trafficUpdateTimer As Timer
  552.  
  553. #End Region
  554.  
  555. #Region " Properties "
  556.  
  557.         ''' ----------------------------------------------------------------------------------------------------
  558.         ''' <summary>
  559.         ''' Gets the name of the network interface that is being monitored.
  560.         ''' </summary>
  561.         ''' ----------------------------------------------------------------------------------------------------
  562.         ''' <value>
  563.         ''' The name of the network interface that is being monitored.
  564.         ''' </value>
  565.         ''' ----------------------------------------------------------------------------------------------------
  566.         Public Overridable ReadOnly Property InterfaceName As String
  567.             Get
  568.                 Return Me.interfaceNameB
  569.             End Get
  570.         End Property
  571.         ''' ----------------------------------------------------------------------------------------------------
  572.         ''' <summary>
  573.         ''' ( Backing Field )
  574.         ''' The name of the network interface that is being monitored.
  575.         ''' </summary>
  576.         ''' ----------------------------------------------------------------------------------------------------
  577.         Protected ReadOnly interfaceNameB As String
  578.  
  579.         ''' ----------------------------------------------------------------------------------------------------
  580.         ''' <summary>
  581.         ''' Gets a value that indicates whether the traffic monitor is active.
  582.         ''' </summary>
  583.         ''' ----------------------------------------------------------------------------------------------------
  584.         ''' <value>
  585.         ''' A value that indicates whether the traffic monitor is active.
  586.         ''' </value>
  587.         ''' ----------------------------------------------------------------------------------------------------
  588.         Public Overridable ReadOnly Property IsActive As Boolean
  589.             Get
  590.                 Return Me.isActiveB
  591.             End Get
  592.         End Property
  593.         ''' ----------------------------------------------------------------------------------------------------
  594.         ''' <summary>
  595.         ''' ( Backing Field )
  596.         ''' A value that indicates whether the traffic monitor is active.
  597.         ''' </summary>
  598.         ''' ----------------------------------------------------------------------------------------------------
  599.         Protected isActiveB As Boolean = False
  600.  
  601.         ''' ----------------------------------------------------------------------------------------------------
  602.         ''' <summary>
  603.         ''' Gets a value, in milliseconds, that determines when the monitor will update the traffic values.
  604.         ''' </summary>
  605.         ''' ----------------------------------------------------------------------------------------------------
  606.         ''' <value>
  607.         ''' A value, in milliseconds, that determines when the monitor will update the traffic values.
  608.         ''' </value>
  609.         ''' ----------------------------------------------------------------------------------------------------
  610.         Public Overridable Property UpdateInterval As Integer
  611.             Get
  612.                 Return Me.updateIntervalB
  613.             End Get
  614.             <DebuggerStepThrough>
  615.             <DebuggerHidden>
  616.             Set(ByVal value As Integer)
  617.                 Me.updateIntervalB = value
  618.                 Me.trafficUpdateTimer.Interval = value
  619.             End Set
  620.         End Property
  621.         ''' ----------------------------------------------------------------------------------------------------
  622.         ''' <summary>
  623.         ''' ( Backing Field )
  624.         ''' A value, in milliseconds, that determines when the monitor will update the traffic values.
  625.         ''' </summary>
  626.         ''' ----------------------------------------------------------------------------------------------------
  627.         Protected updateIntervalB As Integer = 1000
  628.  
  629.         ''' ----------------------------------------------------------------------------------------------------
  630.         ''' <summary>
  631.         ''' Gets or sets a value that controls the behavior of the <see cref="TrafficChanged"/> event.
  632.         ''' </summary>
  633.         ''' ----------------------------------------------------------------------------------------------------
  634.         ''' <value>
  635.         ''' A value that controls the behavior of the <see cref="TrafficChanged"/> event.
  636.         ''' </value>
  637.         ''' ----------------------------------------------------------------------------------------------------
  638.         Public Property UpdateBehavior As UpdateBehaviorEnum = UpdateBehaviorEnum.FireAlwaysAfterTick
  639.  
  640. #End Region
  641.  
  642. #Region " Enumerations "
  643.  
  644.         ''' <summary>
  645.         ''' Specifies a behavior of the <see cref="TrafficChanged"/> event
  646.         ''' </summary>
  647.         Public Enum UpdateBehaviorEnum As Integer
  648.  
  649.             ''' <summary>
  650.             ''' Fires the <see cref="TrafficChanged"/> event always when the specified <see cref="UpdateInterval"/> time ticks.
  651.             ''' </summary>
  652.             FireAlwaysAfterTick = 0I
  653.  
  654.             ''' <summary>
  655.             ''' Fires the <see cref="TrafficChanged"/> event only if received or sent bytes changes,
  656.             ''' after the the specified <see cref="UpdateInterval"/> time ticks.
  657.             ''' </summary>
  658.             FireWhenTrafficChangesAfterTick = 1I
  659.  
  660.         End Enum
  661.  
  662. #End Region
  663.  
  664. #Region " Events "
  665.  
  666.         ''' ----------------------------------------------------------------------------------------------------
  667.         ''' <summary>
  668.         ''' Occurs when network traffic changed.
  669.         ''' </summary>
  670.         ''' ----------------------------------------------------------------------------------------------------
  671.         Protected Friend Event TrafficChanged As EventHandler(Of TrafficChangedEventArgs)
  672.  
  673. #Region " Traffic Changd Args "
  674.  
  675.         ''' ----------------------------------------------------------------------------------------------------
  676.         ''' <summary>
  677.         ''' Contains the event-data of a <see cref="TrafficChanged"/> event.
  678.         ''' </summary>
  679.         ''' ----------------------------------------------------------------------------------------------------
  680.         Protected Friend NotInheritable Class TrafficChangedEventArgs : Inherits EventArgs
  681.  
  682. #Region " Properties "
  683.  
  684.             ''' ----------------------------------------------------------------------------------------------------
  685.             ''' <summary>
  686.             ''' Gets the bytes sent.
  687.             ''' </summary>
  688.             ''' ----------------------------------------------------------------------------------------------------
  689.             ''' <value>
  690.             ''' The bytes sent.
  691.             ''' </value>
  692.             ''' ----------------------------------------------------------------------------------------------------
  693.             Public ReadOnly Property BytesSent As Single
  694.                 Get
  695.                     Return Me.bytesSentB
  696.                 End Get
  697.             End Property
  698.             ''' ----------------------------------------------------------------------------------------------------
  699.             ''' <summary>
  700.             ''' ( Backing Field )
  701.             ''' Gets the bytes sent.
  702.             ''' </summary>
  703.             ''' ----------------------------------------------------------------------------------------------------
  704.             Private ReadOnly bytesSentB As Single
  705.  
  706.             ''' ----------------------------------------------------------------------------------------------------
  707.             ''' <summary>
  708.             ''' Gets the bytes received.
  709.             ''' </summary>
  710.             ''' ----------------------------------------------------------------------------------------------------
  711.             ''' <value>
  712.             ''' The bytes received.
  713.             ''' </value>
  714.             ''' ----------------------------------------------------------------------------------------------------
  715.             Public ReadOnly Property BytesReceived As Single
  716.                 Get
  717.                     Return Me.bytesReceivedB
  718.                 End Get
  719.             End Property
  720.             ''' ----------------------------------------------------------------------------------------------------
  721.             ''' <summary>
  722.             ''' ( Backing Field )
  723.             ''' Gets the bytes received.
  724.             ''' </summary>
  725.             ''' ----------------------------------------------------------------------------------------------------
  726.             Private ReadOnly bytesReceivedB As Single
  727.  
  728.             ''' ----------------------------------------------------------------------------------------------------
  729.             ''' <summary>
  730.             ''' Gets the difference between the last and the current amount of bytes sent.
  731.             ''' For upload speed measuring purposes.
  732.             ''' </summary>
  733.             ''' ----------------------------------------------------------------------------------------------------
  734.             ''' <value>
  735.             ''' The difference between the last and the current amount of bytes sent.
  736.             ''' </value>
  737.             ''' ----------------------------------------------------------------------------------------------------
  738.             Public ReadOnly Property DiffBytesSent As Single
  739.                 Get
  740.                     Return Me.diffBytesSentB
  741.                 End Get
  742.             End Property
  743.             ''' ----------------------------------------------------------------------------------------------------
  744.             ''' <summary>
  745.             ''' ( Backing Field )
  746.             ''' The difference between the last and the current amount of bytes sent.
  747.             ''' </summary>
  748.             ''' ----------------------------------------------------------------------------------------------------
  749.             Private ReadOnly diffBytesSentB As Single
  750.  
  751.             ''' ----------------------------------------------------------------------------------------------------
  752.             ''' <summary>
  753.             ''' Gets the difference between the last and the current amount of bytes received.
  754.             ''' For download speed measuring purposes.
  755.             ''' </summary>
  756.             ''' ----------------------------------------------------------------------------------------------------
  757.             ''' <value>
  758.             ''' The difference between the last and the current amount of bytes received.
  759.             ''' </value>
  760.             ''' ----------------------------------------------------------------------------------------------------
  761.             Public ReadOnly Property DiffBytesReceived As Single
  762.                 Get
  763.                     Return Me.diffBytesReceivedB
  764.                 End Get
  765.             End Property
  766.             ''' ----------------------------------------------------------------------------------------------------
  767.             ''' <summary>
  768.             ''' ( Backing Field )
  769.             ''' The difference between the last and the current amount of bytes received.
  770.             ''' </summary>
  771.             ''' ----------------------------------------------------------------------------------------------------
  772.             Private ReadOnly diffBytesReceivedB As Single
  773.  
  774. #End Region
  775.  
  776. #Region " Constructors "
  777.  
  778.             ''' ----------------------------------------------------------------------------------------------------
  779.             ''' <summary>
  780.             ''' Initializes a new instance of the <see cref="TrafficChangedEventArgs"/> class.
  781.             ''' </summary>
  782.             ''' ----------------------------------------------------------------------------------------------------
  783.             ''' <param name="bytesSent">
  784.             ''' The bytes sent.
  785.             ''' </param>
  786.             '''
  787.             ''' <param name="bytesReceived">
  788.             ''' The bytes received.
  789.             ''' </param>
  790.             '''
  791.             ''' <param name="diffBytesSent">
  792.             ''' The difference between the last and the current amount of bytes sent.
  793.             ''' </param>
  794.             '''
  795.             ''' <param name="diffBytesReceived">
  796.             ''' The difference between the last and the current amount of bytes received.
  797.             ''' </param>
  798.             ''' ----------------------------------------------------------------------------------------------------
  799.             Public Sub New(ByVal bytesSent As Single,
  800.                            ByVal bytesReceived As Single,
  801.                            ByVal diffBytesSent As Single,
  802.                            ByVal diffBytesReceived As Single)
  803.  
  804.                 Me.bytesSentB = bytesSent
  805.                 Me.bytesReceivedB = bytesReceived
  806.                 Me.diffBytesSentB = diffBytesSent
  807.                 Me.diffBytesReceivedB = DiffBytesReceived
  808.  
  809.             End Sub
  810.  
  811.             ''' <summary>
  812.             ''' Prevents a default instance of the <see cref="TrafficChangedEventArgs"/> class from being created.
  813.             ''' </summary>
  814.             Private Sub New()
  815.             End Sub
  816.  
  817. #End Region
  818.  
  819.         End Class
  820.  
  821. #End Region
  822.  
  823. #End Region
  824.  
  825. #Region " Constructors "
  826.  
  827.         ''' ----------------------------------------------------------------------------------------------------
  828.         ''' <summary>
  829.         ''' Initializes a new instance of the <see cref="NetworkTrafficMonitor"/> class.
  830.         ''' </summary>
  831.         ''' ----------------------------------------------------------------------------------------------------
  832.         ''' <param name="interfaceName">
  833.         ''' The name of the interface to monitor.
  834.         ''' </param>
  835.         ''' ----------------------------------------------------------------------------------------------------
  836.         ''' <exception cref="NotImplementedException">
  837.         ''' Performance Counters doesn't include the category.
  838.         ''' </exception>
  839.         '''
  840.         ''' <exception cref="ArgumentException">
  841.         ''' The specified interface is not avaliable or doesn't exist.;interfaceName
  842.         ''' </exception>
  843.         ''' ----------------------------------------------------------------------------------------------------
  844.         <DebuggerStepThrough>
  845.         <DebuggerHidden>
  846.         Public Sub New(ByVal interfaceName As String)
  847.  
  848.             If Not Me.IsCategoryAvaliable(Me.categoryName) Then
  849.                 Throw New NotImplementedException(message:=String.Format("Performance Counters doesn't include the category '{0}'.",
  850.                                                                          Me.categoryName))
  851.  
  852.             ElseIf Not Me.IsInterfaceAvaliable(interfaceName) Then
  853.                 Throw New ArgumentException(message:="The specified interface is not avaliable or doesn't exist.",
  854.                                              paramname:="interfacename")
  855.  
  856.             Else
  857.                 Me.interfaceNameB = interfaceName
  858.                 Me.trafficUpdateTimer = New Timer
  859.  
  860.             End If
  861.  
  862.         End Sub
  863.  
  864.         ''' ----------------------------------------------------------------------------------------------------
  865.         ''' <summary>
  866.         ''' Initializes a new instance of the <see cref="NetworkTrafficMonitor"/> class.
  867.         ''' </summary>
  868.         ''' ----------------------------------------------------------------------------------------------------
  869.         ''' <param name="categoryName">
  870.         ''' The name of the performance category.
  871.         ''' </param>
  872.         '''
  873.         ''' <param name="counterNameBytesSent">
  874.         ''' The name of the Performance Counter that retrieves the bytes sent.
  875.         ''' </param>
  876.         '''
  877.         ''' <param name="counterNameBytesReceived">
  878.         ''' The name of the Performance Counter that retrieves the bytes received.
  879.         ''' </param>
  880.         ''' ----------------------------------------------------------------------------------------------------
  881.         ''' <exception cref="NotImplementedException">
  882.         ''' Performance Counters doesn't include the category.
  883.         ''' </exception>
  884.         ''' ----------------------------------------------------------------------------------------------------
  885.         <DebuggerStepThrough>
  886.         <DebuggerHidden>
  887.         Protected Sub New(ByVal categoryName As String,
  888.                           ByVal counterNameBytesSent As String,
  889.                           ByVal counterNameBytesReceived As String)
  890.  
  891.             If Not Me.IsCategoryAvaliable(categoryName) Then
  892.                 Throw New NotImplementedException(message:=String.Format("Performance Counters doesn't include the category '{0}'.",
  893.                                                                          categoryName))
  894.             End If
  895.  
  896.             Me.categoryName = categoryName
  897.             Me.counterNameBytesSent = counterNameBytesSent
  898.             Me.counterNameBytesReceived = counterNameBytesReceived
  899.  
  900.             Me.trafficUpdateTimer = New Timer
  901.  
  902.         End Sub
  903.  
  904.         ''' ----------------------------------------------------------------------------------------------------
  905.         ''' <summary>
  906.         ''' Prevents a default instance of the <see cref="NetworkTrafficMonitor"/> class from being created.
  907.         ''' </summary>
  908.         ''' ----------------------------------------------------------------------------------------------------
  909.         Private Sub New()
  910.         End Sub
  911.  
  912. #End Region
  913.  
  914. #Region " Shared Methods "
  915.  
  916.         ''' ----------------------------------------------------------------------------------------------------
  917.         ''' <summary>
  918.         ''' Gets the avaliable network interface names.
  919.         ''' </summary>
  920.         ''' ----------------------------------------------------------------------------------------------------
  921.         ''' <returns>
  922.         ''' An <see cref="IEnumerable(Of String)"/> that enumerates the avaliable network interface names.
  923.         ''' </returns>
  924.         ''' ----------------------------------------------------------------------------------------------------
  925.         <DebuggerStepThrough>
  926.         <DebuggerHidden>
  927.         Public Shared Function GetAvaliableInterfaceNames() As IEnumerable(Of String)
  928.  
  929.             If PerformanceCounterCategory.Exists("Network Interface") Then
  930.                 Return New PerformanceCounterCategory("Network Interface").GetInstanceNames
  931.  
  932.             Else
  933.                 Return Nothing
  934.  
  935.             End If
  936.  
  937.         End Function
  938.  
  939. #End Region
  940.  
  941. #Region " Public Methods "
  942.  
  943.         ''' ----------------------------------------------------------------------------------------------------
  944.         ''' <summary>
  945.         ''' Initializes the traffic monitoring.
  946.         ''' </summary>
  947.         ''' ----------------------------------------------------------------------------------------------------
  948.         <DebuggerStepThrough>
  949.         <DebuggerHidden>
  950.         Public Overridable Sub Start()
  951.  
  952.             Me.InitializeMonitor()
  953.  
  954.         End Sub
  955.  
  956.         ''' ----------------------------------------------------------------------------------------------------
  957.         ''' <summary>
  958.         ''' Finalizes the traffic monitoring.
  959.         ''' </summary>
  960.         ''' ----------------------------------------------------------------------------------------------------
  961.         <DebuggerStepThrough>
  962.         <DebuggerHidden>
  963.         Public Overridable Sub [Stop]()
  964.  
  965.             Me.isActiveB = False
  966.             If Me.trafficUpdateTimer IsNot Nothing Then
  967.                 Me.trafficUpdateTimer.Enabled = False
  968.             End If
  969.  
  970.         End Sub
  971.  
  972.         ''' ----------------------------------------------------------------------------------------------------
  973.         ''' <summary>
  974.         ''' Gets the bytes sent.
  975.         ''' </summary>
  976.         ''' ----------------------------------------------------------------------------------------------------
  977.         ''' <returns>
  978.         ''' The bytes sent.
  979.         ''' </returns>
  980.         ''' ----------------------------------------------------------------------------------------------------
  981.         <DebuggerStepThrough>
  982.         <DebuggerHidden>
  983.         Public Overridable Function GetBytesSent() As Single
  984.  
  985.             If Me.isActiveB Then
  986.                 Return Me.bytesSentPerformanceCounter.RawValue
  987.             Else
  988.                 Return Nothing
  989.             End If
  990.  
  991.         End Function
  992.  
  993.         ''' ----------------------------------------------------------------------------------------------------
  994.         ''' <summary>
  995.         ''' Gets the bytes received.
  996.         ''' </summary>
  997.         ''' ----------------------------------------------------------------------------------------------------
  998.         ''' <returns>
  999.         ''' The bytes received.
  1000.         ''' </returns>
  1001.         ''' ----------------------------------------------------------------------------------------------------
  1002.         <DebuggerStepThrough>
  1003.         <DebuggerHidden>
  1004.         Public Overridable Function GetBytesReceived() As Single
  1005.  
  1006.             If Me.isActiveB Then
  1007.                 Return Me.bytesReceivedPerformanceCounter.RawValue
  1008.             Else
  1009.                 Return Nothing
  1010.             End If
  1011.  
  1012.         End Function
  1013.  
  1014. #End Region
  1015.  
  1016. #Region " Private Methods "
  1017.  
  1018.         ''' ----------------------------------------------------------------------------------------------------
  1019.         ''' <summary>
  1020.         ''' Determines whether the specified interface is avaliable.
  1021.         ''' </summary>
  1022.         ''' ----------------------------------------------------------------------------------------------------
  1023.         ''' <param name="interfaceName">
  1024.         ''' The name of the interface.
  1025.         ''' </param>
  1026.         ''' ----------------------------------------------------------------------------------------------------
  1027.         ''' <returns>
  1028.         ''' <see langword="True"/> if interface is avaliable; otherwise, <see langword="False"/>.
  1029.         ''' </returns>
  1030.         ''' ----------------------------------------------------------------------------------------------------
  1031.         <DebuggerStepThrough>
  1032.         <DebuggerHidden>
  1033.         Protected Function IsInterfaceAvaliable(ByVal interfaceName As String) As Boolean
  1034.  
  1035.             Return (From name As String In NetworkTrafficMonitor.GetAvaliableInterfaceNames
  1036.                     Where name.Equals(interfaceName, StringComparison.OrdinalIgnoreCase)).Any
  1037.  
  1038.         End Function
  1039.  
  1040.         ''' ----------------------------------------------------------------------------------------------------
  1041.         ''' <summary>
  1042.         ''' Determines whether the specified performance counter category is avaliable.
  1043.         ''' </summary>
  1044.         ''' ----------------------------------------------------------------------------------------------------
  1045.         ''' <param name="categoryName">
  1046.         ''' The name of the category.
  1047.         ''' </param>
  1048.         ''' ----------------------------------------------------------------------------------------------------
  1049.         ''' <returns>
  1050.         ''' <see langword="True"/> if category is avaliable; otherwise, <see langword="False"/>.
  1051.         ''' </returns>
  1052.         ''' ----------------------------------------------------------------------------------------------------
  1053.         <DebuggerStepThrough>
  1054.         <DebuggerHidden>
  1055.         Protected Function IsCategoryAvaliable(ByVal categoryName As String) As Boolean
  1056.  
  1057.             Return PerformanceCounterCategory.Exists(categoryName)
  1058.  
  1059.         End Function
  1060.  
  1061.         ''' ----------------------------------------------------------------------------------------------------
  1062.         ''' <summary>
  1063.         ''' Gets the avaliable instance names of the specified performance counter category.
  1064.         ''' </summary>
  1065.         ''' ----------------------------------------------------------------------------------------------------
  1066.         ''' <returns>
  1067.         ''' An <see cref="IEnumerable(Of String)"/> that enumerates the avaliable instance names.
  1068.         ''' </returns>
  1069.         ''' ----------------------------------------------------------------------------------------------------
  1070.         <DebuggerStepThrough>
  1071.         <DebuggerHidden>
  1072.         Protected Overridable Function GetAvaliableInstanceNames(ByVal categoryName As String) As IEnumerable(Of String)
  1073.  
  1074.             If Me.IsCategoryAvaliable(categoryName) Then
  1075.                 Return New PerformanceCounterCategory(categoryName).GetInstanceNames
  1076.  
  1077.             Else
  1078.                 Return Nothing
  1079.  
  1080.             End If
  1081.  
  1082.         End Function
  1083.  
  1084.         ''' ----------------------------------------------------------------------------------------------------
  1085.         ''' <summary>
  1086.         ''' Initializes the performance counters.
  1087.         ''' </summary>
  1088.         ''' ----------------------------------------------------------------------------------------------------
  1089.         <DebuggerStepThrough>
  1090.         <DebuggerHidden>
  1091.         Protected Overridable Sub InitializeMonitor()
  1092.  
  1093.             If Not Me.isActiveB Then
  1094.  
  1095.                 If Me.IsInterfaceAvaliable(Me.interfaceNameB) Then
  1096.  
  1097.                     Me.bytesSentPerformanceCounter = New PerformanceCounter
  1098.                     With bytesSentPerformanceCounter
  1099.                         .CategoryName = Me.categoryName
  1100.                         .CounterName = Me.counterNameBytesSent
  1101.                         .InstanceName = Me.interfaceNameB
  1102.                         .[ReadOnly] = True
  1103.                     End With
  1104.  
  1105.                     Me.bytesReceivedPerformanceCounter = New PerformanceCounter
  1106.                     With bytesReceivedPerformanceCounter
  1107.                         .CategoryName = Me.categoryName
  1108.                         .CounterName = Me.counterNameBytesReceived
  1109.                         .InstanceName = Me.interfaceNameB
  1110.                         .[ReadOnly] = True
  1111.                     End With
  1112.  
  1113.                     Me.isActiveB = True
  1114.                     Me.trafficUpdateTimer.Enabled = True
  1115.  
  1116.                 End If
  1117.  
  1118.             End If
  1119.  
  1120.         End Sub
  1121.  
  1122.         ''' ----------------------------------------------------------------------------------------------------
  1123.         ''' <summary>
  1124.         ''' Finalizes the performance counters.
  1125.         ''' </summary>
  1126.         ''' ----------------------------------------------------------------------------------------------------
  1127.         <DebuggerStepThrough>
  1128.         <DebuggerHidden>
  1129.         Protected Overridable Sub FinalizeMonitor()
  1130.  
  1131.             Me.isActiveB = False
  1132.  
  1133.             If Me.trafficUpdateTimer IsNot Nothing Then
  1134.                 Me.trafficUpdateTimer.Enabled = False
  1135.                 Me.trafficUpdateTimer.Dispose()
  1136.             End If
  1137.  
  1138.             If Me.bytesSentPerformanceCounter IsNot Nothing Then
  1139.                 Me.bytesSentPerformanceCounter.RemoveInstance()
  1140.                 Me.bytesSentPerformanceCounter.Close()
  1141.             End If
  1142.  
  1143.             If Me.bytesReceivedPerformanceCounter IsNot Nothing Then
  1144.                 Me.bytesReceivedPerformanceCounter.RemoveInstance()
  1145.                 Me.bytesReceivedPerformanceCounter.Close()
  1146.             End If
  1147.  
  1148.         End Sub
  1149.  
  1150. #End Region
  1151.  
  1152. #Region " Event-Handlers "
  1153.  
  1154.         ''' ----------------------------------------------------------------------------------------------------
  1155.         ''' <summary>
  1156.         ''' Handles the <see cref="Timer.Tick"/> event of the <see cref="TrafficUpdateTimer"/> control.
  1157.         ''' </summary>
  1158.         ''' ----------------------------------------------------------------------------------------------------
  1159.         ''' <param name="sender">
  1160.         ''' The source of the event.
  1161.         ''' </param>
  1162.         ''' ----------------------------------------------------------------------------------------------------
  1163.         ''' <param name="e">
  1164.         ''' The <see cref="EventArgs"/> instance containing the event data.
  1165.         ''' </param>
  1166.         ''' ----------------------------------------------------------------------------------------------------
  1167.         <DebuggerStepThrough>
  1168.         <DebuggerHidden>
  1169.         Protected Overridable Sub TrafficUpdateTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
  1170.         Handles trafficUpdateTimer.Tick
  1171.  
  1172.             If (TrafficChangedEvent IsNot Nothing) Then
  1173.  
  1174.                 Static isFirstUpdate As Boolean = True
  1175.                 Dim needUpdate As Boolean = False
  1176.  
  1177.                 Static lastBytesSent As Single
  1178.                 Static lastBytesReceived As Single
  1179.  
  1180.                 Dim currentBytesSent As Single = Me.GetBytesSent
  1181.                 Dim currentBytesReceived As Single = Me.GetBytesReceived
  1182.  
  1183.                 Dim diffBytessSent As Single = If(isFirstUpdate, 0, (currentBytesSent - lastBytesSent))
  1184.                 Dim diffBytesReceived As Single = If(isFirstUpdate, 0, (currentBytesReceived - lastBytesReceived))
  1185.  
  1186.                 If (currentBytesSent <> lastBytesSent) OrElse (currentBytesReceived <> lastBytesReceived) Then
  1187.                     needUpdate = True
  1188.                 End If
  1189.  
  1190.                 lastBytesSent = currentBytesSent
  1191.                 lastBytesReceived = currentBytesReceived
  1192.  
  1193.                 If (Me.UpdateBehavior = UpdateBehaviorEnum.FireAlwaysAfterTick) OrElse (needUpdate) Then
  1194.  
  1195.                     isFirstUpdate = False
  1196.                     RaiseEvent TrafficChanged(Me, New TrafficChangedEventArgs(currentBytesSent, currentBytesReceived,
  1197.                                                                               diffBytessSent, diffBytesReceived))
  1198.                 End If
  1199.  
  1200.             End If
  1201.  
  1202.         End Sub
  1203.  
  1204. #End Region
  1205.  
  1206. #Region " IDisposable Implementation "
  1207.  
  1208.         ''' ----------------------------------------------------------------------------------------------------
  1209.         ''' <summary>
  1210.         ''' To detect redundant calls when disposing.
  1211.         ''' </summary>
  1212.         ''' ----------------------------------------------------------------------------------------------------
  1213.         Protected isDisposed As Boolean = False
  1214.  
  1215.         ''' ----------------------------------------------------------------------------------------------------
  1216.         ''' <summary>
  1217.         ''' Releases all resources used by this instance.
  1218.         ''' </summary>
  1219.         ''' ----------------------------------------------------------------------------------------------------
  1220.         ''' <remarks>
  1221.         ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1222.         ''' </remarks>
  1223.         ''' ----------------------------------------------------------------------------------------------------
  1224.         <DebuggerStepThrough>
  1225.         Public Sub Dispose() Implements IDisposable.Dispose
  1226.             Me.Dispose(isDisposing:=True)
  1227.             GC.SuppressFinalize(obj:=Me)
  1228.         End Sub
  1229.  
  1230.         ''' ----------------------------------------------------------------------------------------------------
  1231.         ''' <summary>
  1232.         ''' Releases unmanaged and - optionally - managed resources.
  1233.         ''' </summary>
  1234.         ''' ----------------------------------------------------------------------------------------------------
  1235.         ''' <param name="isDisposing">
  1236.         ''' <c>True</c> to release both managed and unmanaged resources;
  1237.         ''' <c>False</c> to release only unmanaged resources.
  1238.         ''' </param>
  1239.         ''' ----------------------------------------------------------------------------------------------------
  1240.         <DebuggerStepThrough>
  1241.         Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)
  1242.  
  1243.             If (Not Me.isDisposed) AndAlso (isDisposing) Then
  1244.                 Me.FinalizeMonitor()
  1245.             End If
  1246.  
  1247.             Me.isDisposed = True
  1248.  
  1249.         End Sub
  1250.  
  1251. #End Region
  1252.  
  1253.     End Class
  1254.  
  1255. #End Region
  1256.  
  1257. #Region " Process Traffic Monitor "
  1258.  
  1259.     ''' ----------------------------------------------------------------------------------------------------
  1260.     ''' <summary>
  1261.     ''' Monitorizes the network traffic of a process.
  1262.     ''' </summary>
  1263.     ''' ----------------------------------------------------------------------------------------------------
  1264.     ''' <example> This is a code example.
  1265.     ''' <code>
  1266.     ''' Public NotInheritable Class Form1 : Inherits Form
  1267.     '''
  1268.     '''     Dim WithEvents procNetMon As NetworkUtil.ProcessTrafficMonitor
  1269.     '''
  1270.     '''     Private Sub Form1_Load() Handles MyBase.Load
  1271.     '''
  1272.     '''         Me.procNetMon = New NetworkUtil.ProcessTrafficMonitor(Process.GetCurrentProcess.Id)
  1273.     '''         Me.procNetMon.UpdateBehavior = NetworkUtil.ProcessTrafficMonitor.UpdateBehaviorEnum.FireAlwaysAfterTick
  1274.     '''         Me.procNetMon.UpdateInterval = 1000 ' 1 sec
  1275.     '''         Me.procNetMon.Start()
  1276.     '''
  1277.     '''     End Sub
  1278.     '''
  1279.     '''     ''' ----------------------------------------------------------------------------------------------------
  1280.     '''     ''' <summary>
  1281.     '''     ''' Handles the <see cref="NetworkUtil.ProcessTrafficMonitor.TrafficChanged"/> event of the procNetMon instance.
  1282.     '''     ''' </summary>
  1283.     '''     ''' ----------------------------------------------------------------------------------------------------
  1284.     '''     ''' <param name="sender">T
  1285.     '''     ''' The source of the event.
  1286.     '''     ''' </param>
  1287.     '''     '''
  1288.     '''     ''' <param name="e">
  1289.     '''     ''' The <see cref="NetworkUtil.ProcessTrafficMonitor.TrafficChangedEventArgs"/> instance containing the event data.
  1290.     '''     ''' </param>
  1291.     '''     ''' ----------------------------------------------------------------------------------------------------
  1292.     '''     Private Sub ProcNetMon_TrafficChanged(ByVal sender As Object, ByVal e As NetworkUtil.ProcessTrafficMonitor.TrafficChangedEventArgs) _
  1293.     '''     Handles procNetMon.TrafficChanged
  1294.     '''
  1295.     '''         Me.LabelBytesReceived.Text = String.Format("Bytes received: {0} kb", (e.BytesReceived / 1024).ToString("n2"))
  1296.     '''         Me.LabelDlSpeed.Text = String.Format("DL Speed: {0} kb/sec", (e.DiffBytesReceived / 1024).ToString("n2"))
  1297.     '''
  1298.     '''         Me.LabelBytesSent.Text = String.Format("Bytes sent: {0} kb", (e.BytesSent / 1024).ToString("n2"))
  1299.     '''         Me.LabelUlSpeed.Text = String.Format("UL Speed: {0} kb/sec", (e.DiffBytesSent / 1024).ToString("n2"))
  1300.     '''
  1301.     '''     End Sub
  1302.     '''
  1303.     '''     Private Sub BtDownloadUrl_Click() Handles BtDownloadUrl.Click
  1304.     '''
  1305.     '''         Dim url As String = "http://download.thinkbroadband.com/10MB.zip"
  1306.     '''         Dim client As New WebClient()
  1307.     '''         client.DownloadFileAsync(New Uri(url), Path.GetTempFileName())
  1308.     '''
  1309.     '''     End Sub
  1310.     '''
  1311.     '''     Private Sub BtPauseMon_Click() Handles BtPauseMon.Click
  1312.     '''
  1313.     '''         If Me.procNetMon.IsActive Then
  1314.     '''             Me.procNetMon.Stop()
  1315.     '''         Else
  1316.     '''             Me.procNetMon.Start()
  1317.     '''         End If
  1318.     '''
  1319.     '''     End Sub
  1320.     '''
  1321.     ''' End Class
  1322.     ''' </code>
  1323.     ''' </example>
  1324.     ''' ----------------------------------------------------------------------------------------------------
  1325.     Public Class ProcessTrafficMonitor : Inherits NetworkTrafficMonitor
  1326.  
  1327. #Region " Hidden Base Members "
  1328.  
  1329.         <EditorBrowsable(EditorBrowsableState.Never)>
  1330.         Friend Shadows InterfaceName As Object
  1331.  
  1332.         <EditorBrowsable(EditorBrowsableState.Never)>
  1333.         Private Shadows getAvaliableInterfaceNames As Object
  1334.  
  1335. #End Region
  1336.  
  1337. #Region " Properties "
  1338.  
  1339.         ''' ----------------------------------------------------------------------------------------------------
  1340.         ''' <summary>
  1341.         ''' Gets the name of the process that is being monitored.
  1342.         ''' </summary>
  1343.         ''' ----------------------------------------------------------------------------------------------------
  1344.         ''' <value>
  1345.         ''' The name of the process that is being monitored.
  1346.         ''' </value>
  1347.         ''' ----------------------------------------------------------------------------------------------------
  1348.         Public Overridable ReadOnly Property ProcessId As Integer
  1349.             Get
  1350.                 Return Me.processIdB
  1351.             End Get
  1352.         End Property
  1353.         ''' ----------------------------------------------------------------------------------------------------
  1354.         ''' <summary>
  1355.         ''' ( Backing Field )
  1356.         ''' The name of the process that is being monitored.
  1357.         ''' </summary>
  1358.         ''' ----------------------------------------------------------------------------------------------------
  1359.         Protected ReadOnly processIdB As Integer
  1360.  
  1361. #End Region
  1362.  
  1363. #Region " Constructors "
  1364.  
  1365.         ''' ----------------------------------------------------------------------------------------------------
  1366.         ''' <summary>
  1367.         ''' Initializes a new instance of the <see cref="ProcessTrafficMonitor"/> class.
  1368.         ''' </summary>
  1369.         ''' ----------------------------------------------------------------------------------------------------
  1370.         ''' <param name="processId">
  1371.         ''' The PID of the process to monitor.
  1372.         ''' Note that the process should have the performance counters feature enabled to be able to use the counters.
  1373.         ''' </param>
  1374.         ''' ----------------------------------------------------------------------------------------------------
  1375.         ''' <remarks>
  1376.         ''' The application's configuration file (app.config) should look like this:
  1377.         '''
  1378.         ''' <code>
  1379.         ''' <configuration>
  1380.         ''' ...
  1381.         '''   <system.net>
  1382.         '''     <settings>
  1383.         '''       <performanceCounters enabled="true"/>
  1384.         '''     </settings>
  1385.         '''   </system.net>
  1386.         ''' ...
  1387.         ''' </configuration>
  1388.         ''' </code>
  1389.         '''
  1390.         ''' MSDN Documentation: <see href="http://msdn.microsoft.com/en-us/library/ms229151%28v=vs.110%29.aspx"/>
  1391.         ''' </remarks>
  1392.         ''' ----------------------------------------------------------------------------------------------------
  1393.         <DebuggerStepThrough>
  1394.         <DebuggerHidden>
  1395.         Public Sub New(ByVal processId As Integer)
  1396.  
  1397.             MyBase.New(categoryName:=".NET CLR Networking 4.0.0.0",
  1398.                        counterNameBytesSent:="Bytes Sent",
  1399.                        counterNameBytesReceived:="Bytes Received")
  1400.  
  1401.             Me.processIdB = processId
  1402.  
  1403.         End Sub
  1404.  
  1405. #End Region
  1406.  
  1407. #Region " Private Methods "
  1408.  
  1409.         ''' ----------------------------------------------------------------------------------------------------
  1410.         ''' <summary>
  1411.         ''' Initializes the performance counters.
  1412.         ''' </summary>
  1413.         ''' ----------------------------------------------------------------------------------------------------
  1414.         <DebuggerStepThrough>
  1415.         <DebuggerHidden>
  1416.         Protected Overrides Sub InitializeMonitor()
  1417.  
  1418.             If Not MyBase.isActiveB Then
  1419.  
  1420.                 Dim instanceNames As IEnumerable(Of String) =
  1421.                     From name As String In MyBase.GetAvaliableInstanceNames(MyBase.categoryName)
  1422.                     Where name.Contains(String.Format("p{0}", Me.processIdB))
  1423.  
  1424.                 If instanceNames.Any() Then
  1425.  
  1426.                     MyBase.bytesSentPerformanceCounter = New PerformanceCounter
  1427.                     With MyBase.bytesSentPerformanceCounter
  1428.                         .CategoryName = MyBase.categoryName
  1429.                         .CounterName = MyBase.counterNameBytesSent
  1430.                         .InstanceName = instanceNames.First
  1431.                         .[ReadOnly] = True
  1432.                     End With
  1433.  
  1434.                     MyBase.bytesReceivedPerformanceCounter = New PerformanceCounter
  1435.                     With MyBase.bytesReceivedPerformanceCounter
  1436.                         .CategoryName = MyBase.categoryName
  1437.                         .CounterName = MyBase.counterNameBytesReceived
  1438.                         .InstanceName = instanceNames.First
  1439.                         .[ReadOnly] = True
  1440.                     End With
  1441.  
  1442.                     MyBase.isActiveB = True
  1443.                     MyBase.trafficUpdateTimer.Enabled = True
  1444.  
  1445.                 End If
  1446.  
  1447.             End If
  1448.  
  1449.         End Sub
  1450.  
  1451. #End Region
  1452.  
  1453.     End Class
  1454.  
  1455. #End Region
  1456.  
  1457. #End Region
  1458.  
  1459. End Class
  1460.  
  1461. #End Region
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement