Solved

Convert C# code to vb.net

Posted on 2008-10-31
10
385 Views
Last Modified: 2013-12-17
Dear experts,
                      Please convert this C# code to vb.net, expecially the part where the variables are declared in UInteger.

Thanks in advance.
using System;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
 
	
	/*===================================================================
	 *  class: Ping
	 *===================================================================*/
	#region Ping
 
	public class Ping
	{
		/*_______________________________________________________________*/
		// methods: Construction
		#region 
 
		// Constructor
		public Ping()
		{
			// create command field
			pingCommand = new byte[8];
			pingCommand[0] = 8;			// Type
			pingCommand[1] = 0;			// Subtype
			pingCommand[2] = 0;			// Checksum
			pingCommand[3] = 0;	
			pingCommand[4] = 1;			// Identifier
			pingCommand[5] = 0;
			pingCommand[6] = 0;			// Sequence number
			pingCommand[7] = 0;
 
			// create result field
			pingResult = new byte[pingCommand.Length + 1000];	// returned IP Header + optional data
		}
		#endregion
 
 
		/*_______________________________________________________________*/
		// methods: Open, Close, Send
		#region 
 
		// Open
		public void Open()
		{
			// create socket and connect
			socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
			isOpen = true;
			
			// create read complete event
			readComplete = new ManualResetEvent(false);
		}
 
		// Close
		public void Close()
		{
			// clear open flag
			isOpen = false;
 
			// close socket
			socket.Close();
 
			// close event
			readComplete.Close();
		}
 
		// Send
		public TimeSpan Send(string address, TimeSpan timeout)
		{
			// empty result buffer
			while (socket.Available > 0) 
				socket.Receive(pingResult, Math.Min(socket.Available, pingResult.Length), SocketFlags.None);
			
			// reset event
			readComplete.Reset();
 
			// save start time
			DateTime timeSend = DateTime.Now;
 
			// complete ping command
			pingCommand[6] = lastSequenceNr++;
			SetChecksum(pingCommand);
 
			// send ping command, start receive command
			int iSend = socket.SendTo(pingCommand, new IPEndPoint(IPAddress.Parse(address), 0));
			socket.BeginReceive(pingResult, 0, pingResult.Length, SocketFlags.None,	new AsyncCallback(CallBack), null);
 
			// wait until data received or timeout
			if (readComplete.WaitOne(timeout, false))
			{
				// check result
				if ((pingResult[20] == 0) &&
					(pingCommand[4] == pingResult[24]) && (pingCommand[5] == pingResult[25]) &&
					(pingCommand[6] == pingResult[26]) && (pingCommand[7] == pingResult[27]))
					// return time delay
					return DateTime.Now.Subtract(timeSend);
			}
 
			// return timeout
			return TimeSpan.MaxValue; 
		}
		#endregion
 
	
		/*_______________________________________________________________*/
		// methods: CallBack
		#region 
 
		protected void CallBack(IAsyncResult result)
		{
			if (isOpen)
			{
				try	{ socket.EndReceive(result); } catch (Exception) { }
				readComplete.Set();
			}
		}
		#endregion
 
 
		/*_______________________________________________________________*/
		// methods: SetChecksum
		#region 
 
		protected void SetChecksum(byte[] tel)
		{
			// reset old checksum
			tel[2] = 0;
			tel[3] = 0;
 
			// calculate new checksum
			uint cs = 0;
			for (int i = 0; i < pingCommand.Length; i = i+2)
				cs += BitConverter.ToUInt16(pingCommand, i);
			cs = ~((cs & 0xffffu) + (cs >> 16));
 
			// set new checksum
			tel[2] = (byte) cs;
			tel[3] = (byte) (cs >> 8);
		}
		#endregion
 
 
 
		/*...............................................................*/
		// fields
 
		// socket and event
		protected Socket socket;
		protected bool isOpen;
		protected ManualResetEvent readComplete;
		protected byte lastSequenceNr = 0;
 
		// ping command and result fields
		protected byte[] pingCommand;
		protected byte[] pingResult;
	}
	#endregion

Open in new window

0
Comment
Question by:wongke9622
  • 3
  • 3
  • 3
  • +1
10 Comments
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 22848689
Ok, I didn't convert it by hand, I used an online conversion tool that can be found here:

http://www.developerfusion.com/tools/convert/csharp-to-vb/

It should be ok.
Imports System
Imports System.Data
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
 
 
'===================================================================
'         *  class: Ping
'         *===================================================================
 
#Region "Ping"
 
Public Class Ping
    '_______________________________________________________________
    
    ' methods: Construction
    #Region ""
    
    ' Constructor
    Public Sub New()
        ' create command field
        pingCommand = New Byte(7) {}
        pingCommand(0) = 8
        ' Type
        pingCommand(1) = 0
        ' Subtype
        pingCommand(2) = 0
        ' Checksum
        pingCommand(3) = 0
        pingCommand(4) = 1
        ' Identifier
        pingCommand(5) = 0
        pingCommand(6) = 0
        ' Sequence number
        pingCommand(7) = 0
        
        ' create result field
            ' returned IP Header + optional data
        pingResult = New Byte(pingCommand.Length + 999) {}
    End Sub
    #End Region
    
    
    '_______________________________________________________________
    
    ' methods: Open, Close, Send
    #Region ""
    
    ' Open
    Public Sub Open()
        ' create socket and connect
        socket = New Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)
        isOpen = True
        
        ' create read complete event
        readComplete = New ManualResetEvent(False)
    End Sub
    
    ' Close
    Public Sub Close()
        ' clear open flag
        isOpen = False
        
        ' close socket
        socket.Close()
        
        ' close event
        readComplete.Close()
    End Sub
    
    ' Send
    Public Function Send(address As String, timeout As TimeSpan) As TimeSpan
        ' empty result buffer
        While socket.Available > 0
            socket.Receive(pingResult, Math.Min(socket.Available, pingResult.Length), SocketFlags.None)
        End While
        
        ' reset event
        readComplete.Reset()
        
        ' save start time
        Dim timeSend As DateTime = DateTime.Now
        
        ' complete ping command
        pingCommand(6) = System.Math.Max(System.Threading.Interlocked.Increment(lastSequenceNr),lastSequenceNr - 1)
        SetChecksum(pingCommand)
        
        ' send ping command, start receive command
        Dim iSend As Integer = socket.SendTo(pingCommand, New IPEndPoint(IPAddress.Parse(address), 0))
        socket.BeginReceive(pingResult, 0, pingResult.Length, SocketFlags.None, New AsyncCallback(CallBack), Nothing)
        
        ' wait until data received or timeout
        If readComplete.WaitOne(timeout, False) Then
            ' check result
            If (pingResult(20) = 0) AndAlso (pingCommand(4) = pingResult(24)) AndAlso (pingCommand(5) = pingResult(25)) AndAlso (pingCommand(6) = pingResult(26)) AndAlso (pingCommand(7) = pingResult(27)) Then
                ' return time delay
                Return DateTime.Now.Subtract(timeSend)
            End If
        End If
        
        ' return timeout
        Return TimeSpan.MaxValue
    End Function
    #End Region
    
    
    '_______________________________________________________________
    
    ' methods: CallBack
    #Region ""
    
    Protected Sub CallBack(result As IAsyncResult)
        If isOpen Then
            Try
                socket.EndReceive(result)
            Catch generatedExceptionName As Exception
            End Try
            readComplete.[Set]()
        End If
    End Sub
    #End Region
    
    
    '_______________________________________________________________
    
    ' methods: SetChecksum
    #Region ""
    
    Protected Sub SetChecksum(tel As Byte())
        ' reset old checksum
        tel(2) = 0
        tel(3) = 0
        
        ' calculate new checksum
        Dim cs As UInteger = 0
        Dim i As Integer = 0
        While i < pingCommand.Length
            cs += BitConverter.ToUInt16(pingCommand, i)
            i = i + 2
        End While
        cs = Not ((cs And &Hffff) + (cs >> 16))
        
        ' set new checksum
        tel(2) = CByte(cs)
        tel(3) = CByte((cs >> 8))
    End Sub
    #End Region
    
    
    
    '...............................................................
    
    ' fields
    
    ' socket and event
    Protected socket As Socket
    Protected isOpen As Boolean
    Protected readComplete As ManualResetEvent
    Protected lastSequenceNr As Byte = 0
    
    ' ping command and result fields
    Protected pingCommand As Byte()
    Protected pingResult As Byte()
End Class
#End Region

Open in new window

0
 
LVL 13

Assisted Solution

by:SameerJagdale
SameerJagdale earned 250 total points
ID: 22849713

Imports System
Imports System.Data
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
 
 
'===================================================================
'         *  class: Ping
'         *===================================================================
 
#Region "Ping"
 
Public Class Ping
    '_______________________________________________________________
 
    ' methods: Construction
#Region ""
 
    ' Constructor
    Public Sub New()
        ' create command field
        pingCommand = New Byte(7) {}
        pingCommand(0) = 8
        ' Type
        pingCommand(1) = 0
        ' Subtype
        pingCommand(2) = 0
        ' Checksum
        pingCommand(3) = 0
        pingCommand(4) = 1
        ' Identifier
        pingCommand(5) = 0
        pingCommand(6) = 0
        ' Sequence number
        pingCommand(7) = 0
 
        ' create result field
        ' returned IP Header + optional data
        pingResult = New Byte(pingCommand.Length + 999) {}
    End Sub
#End Region
 
 
    '_______________________________________________________________
 
    ' methods: Open, Close, Send
#Region ""
 
    ' Open
    Public Sub Open()
        ' create socket and connect
        socket = New Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)
        isOpen = True
 
        ' create read complete event
        readComplete = New ManualResetEvent(False)
    End Sub
 
    ' Close
    Public Sub Close()
        ' clear open flag
        isOpen = False
 
        ' close socket
        socket.Close()
 
        ' close event
        readComplete.Close()
    End Sub
 
    ' Send
    Public Function Send(ByVal address As String, ByVal timeout As TimeSpan) As TimeSpan
        ' empty result buffer
        While socket.Available > 0
            socket.Receive(pingResult, Math.Min(socket.Available, pingResult.Length), SocketFlags.None)
        End While
 
        ' reset event
        readComplete.Reset()
 
        ' save start time
        Dim timeSend As DateTime = DateTime.Now
 
        ' complete ping command
        pingCommand(6) = lastSequenceNr + 1
        SetChecksum(pingCommand)
 
        ' send ping command, start receive command
        Dim iSend As Integer = socket.SendTo(pingCommand, New IPEndPoint(IPAddress.Parse(address), 0))
        socket.BeginReceive(pingResult, 0, pingResult.Length, SocketFlags.None, New AsyncCallback(AddressOf CallBack), Nothing)
 
        ' wait until data received or timeout
        If readComplete.WaitOne(timeout, False) Then
            ' check result
            If (pingResult(20) = 0) AndAlso (pingCommand(4) = pingResult(24)) AndAlso (pingCommand(5) = pingResult(25)) AndAlso (pingCommand(6) = pingResult(26)) AndAlso (pingCommand(7) = pingResult(27)) Then
                ' return time delay
                Return DateTime.Now.Subtract(timeSend)
            End If
        End If
 
        ' return timeout
        Return TimeSpan.MaxValue
    End Function
#End Region
 
 
    '_______________________________________________________________
 
    ' methods: CallBack
#Region ""
 
    Protected Sub CallBack(ByVal result As IAsyncResult)
        If isOpen Then
            Try
                socket.EndReceive(result)
            Catch generatedExceptionName As Exception
            End Try
            readComplete.[Set]()
        End If
    End Sub
#End Region
 
 
    '_______________________________________________________________
 
    ' methods: SetChecksum
#Region ""
 
    Protected Sub SetChecksum(ByVal tel As Byte())
        ' reset old checksum
        tel(2) = 0
        tel(3) = 0
 
        ' calculate new checksum
        Dim cs As UInteger = 0
        Dim i As Integer = 0
        While i < pingCommand.Length
            cs += BitConverter.ToUInt16(pingCommand, i)
            i = i + 2
        End While
        cs = Not ((cs And &HFFFF) + (cs >> 16))
 
        ' set new checksum
        tel(2) = CByte(cs)
        tel(3) = CByte((cs >> 8))
    End Sub
#End Region
 
 
 
    '...............................................................
 
    ' fields
 
    ' socket and event
    Protected socket As Socket
    Protected isOpen As Boolean
    Protected readComplete As ManualResetEvent
    Protected lastSequenceNr As Byte = 0
 
    ' ping command and result fields
    Protected pingCommand As Byte()
    Protected pingResult As Byte()
End Class
#End Region

Open in new window

0
 
LVL 41

Assisted Solution

by:graye
graye earned 250 total points
ID: 22852926
Since we're all posting our favorite Ping class implementation, I'll post mine too!  :)
'http://www.dataidee.com/ping/ping.htm
 
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
 
'
' A class that uses a ICMP ping to verify if a remote PC is alive
'
 
Public Class Ping
 
#If V7 Then
    ' socket and event
    Private pingSocket As Socket
    Private isOpen As Boolean
    Private readComplete As ManualResetEvent
    Private lastSequenceNr As Byte
 
    ' ping command and result fields
    Private pingCommand As Byte()
    Private pingResult As Byte()
 
    Public Sub New()
 
        ' create command field
        ReDim pingCommand(7)
        pingCommand(0) = 8      ' type
        pingCommand(1) = 0      ' subtype
        pingCommand(2) = 0      ' checksum
        pingCommand(3) = 0
        pingCommand(4) = 1      ' identifier
        pingCommand(5) = 0
        pingCommand(6) = 0      ' sequence number
        pingCommand(7) = 0
 
        ' create result field
        ReDim pingResult(pingCommand.Length + 1000)
    End Sub
 
    Public Sub Open()
 
        'create socket and connect
        pingSocket = New Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)
        isOpen = True
 
        ' create read complete event
        readComplete = New ManualResetEvent(False)
    End Sub
 
    Public Sub Close()
        ' clear open flag
        isOpen = False
 
        ' close socket
        pingSocket.Close()
 
        ' close event
        readComplete.Close()
    End Sub
 
    Public Function Ping(ByVal RemoteAddress As String) As Integer
        Return Ping(RemoteAddress, 1000)
    End Function
 
    Public Function Ping(ByVal RemoteAddress As String, ByVal MilliSeconds As Integer) As Integer
        Dim ts_in, ts_out As TimeSpan
        Dim ExplicitOpen As Boolean = False
        Static PreviousAddress As String
        Dim i As Integer
 
        If isOpen = False Then
            Open()
            ExplicitOpen = True
        End If
 
        If PreviousAddress <> RemoteAddress Then
            ' start a new sequence number
            lastSequenceNr = 0
            PreviousAddress = RemoteAddress
        End If
 
        ts_in = New TimeSpan(0, 0, 0, 0, MilliSeconds)
        ' you get 3 tries
        For i = 0 To 2
            ts_out = Send(RemoteAddress, ts_in)
            If ts_out.CompareTo(TimeSpan.MaxValue) < 0 Then
                Exit For
            End If
        Next
 
        If ExplicitOpen Then
            Close()
        End If
 
        If ts_out.CompareTo(TimeSpan.MaxValue) = 0 Then
            Return MilliSeconds + 1
        Else
            Return CInt(ts_out.TotalMilliseconds)
        End If
 
    End Function
 
    Public Function Send(ByVal address As String, ByVal timeout As TimeSpan) As TimeSpan
        Dim timeSend As DateTime
        Dim iSend As Integer
 
        ' empty result buffer
        While (pingSocket.Available > 0)
            pingSocket.Receive(pingResult, Math.Min(pingSocket.Available, pingResult.Length), SocketFlags.None)
        End While
 
        'reset event
        readComplete.Reset()
 
        ' save start time
        timeSend = DateTime.Now
 
        ' complete ping command
        pingCommand(6) = lastSequenceNr
        lastSequenceNr += CByte(1)
        SetChecksum(pingCommand)
 
        ' send ping command, start receive command
        Try
            If address.ToLower.IndexOfAny("abcdefghijklmnopqrstuvwxyz-".ToCharArray) >= 0 Then
                iSend = pingSocket.SendTo(pingCommand, New IPEndPoint(Dns.GetHostByName(address).AddressList(0), 0))
            Else
                iSend = pingSocket.SendTo(pingCommand, New IPEndPoint(IPAddress.Parse(address), 0))
            End If
 
            If iSend <> pingCommand.Length Then
                Return TimeSpan.MaxValue
            End If
        Catch ex As Exception
            Return TimeSpan.MaxValue
        End Try
        pingSocket.BeginReceive(pingResult, 0, pingResult.Length, SocketFlags.None, New AsyncCallback(AddressOf CallBack), Nothing)
 
        ' wait until data received or timeout
        If (readComplete.WaitOne(timeout, False)) Then
            ' check result
            If ((pingResult(20) = 0) And _
                (pingCommand(4) = pingResult(24)) And (pingCommand(5) = pingResult(25)) And _
                (pingCommand(6) = pingResult(26)) And (pingCommand(7) = pingResult(27))) Then
 
                'return time delay
                Return DateTime.Now.Subtract(timeSend)
            End If
        End If
 
        ' return timeout
        Return TimeSpan.MaxValue
    End Function
 
    Private Sub CallBack(ByVal result As IAsyncResult)
        If isOpen Then
            Try
                pingSocket.EndReceive(result)
            Catch ex As Exception
            End Try
            Try
                readComplete.Set()
            Catch ex As Exception
            End Try
        End If
    End Sub
 
    Private Sub SetChecksum(ByRef tel() As Byte)
        Dim i, cs As Integer
 
        ' reset old checksum
        tel(2) = 0
        tel(3) = 0
 
        ' calculate new checksum
        For i = 0 To pingCommand.Length - 1 Step 2
            cs += BitConverter.ToInt16(pingCommand, i)
        Next
        cs = Not ((cs And &HFFFF) + (cs \ &H10000))
 
        ' set new checksum
        tel(2) = BitConverter.GetBytes(cs)(0)
        tel(3) = BitConverter.GetBytes(cs)(1)
    End Sub
#Else
 
    Public Function Ping(ByVal RemoteAddress As String) As Integer
        Return Ping(RemoteAddress, 1000)
    End Function
 
    ' Doing a ping operation on .Net 2.0 is a lot easier
    Public Function Ping(ByVal RemoteAddress As String, ByVal MilliSeconds As Integer) As Integer
        Dim i As Integer
 
        ' we try  up to 3 times
        Try
            For i = 0 To 2
                If My.Computer.Network.Ping(RemoteAddress, MilliSeconds) Then
                    Return 0
                End If
            Next
        Catch ex As Exception
        End Try
 
        Return Integer.MaxValue
    End Function
#End If
End Class

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:wongke9622
ID: 22864434
Thanks guys, the online code conversion does not work because I did that before I posted my question here. There is no UInteger type in vb version as in c# version. Anyways, I will check with what "Grave" has recommended and let you know. Let me see if the bitconverter accepts the int16 data type. Anyways thanks again. Will be back soon.
0
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 22864890
i was able to compile the code i had posted.
0
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 22864894
you can replace UInteger with System.UInt32.
0
 
LVL 41

Expert Comment

by:graye
ID: 22866524
Look closely.... the question is about VB.Net 2003 (aka .Net Framework 1.1).   VB didn't get full support for unsigned types until .Net 2.0.
0
 
LVL 41

Expert Comment

by:graye
ID: 22870864
Oops, I forgot to mention that my sample has a "V7" pre-processor variable that allows that code to be used in .Net 1.1 or .Net 2.0.    So, to get it to compile in .Net 1.1, you'd just have to add a line somewhere at the top that says:
#Const V7 = True
0
 

Author Comment

by:wongke9622
ID: 22927608
Sorry guys for the late reply, I was busy with my stuffs. Will get back to you within this week. Thanks for your support anyways.
0
 

Accepted Solution

by:
wongke9622 earned 0 total points
ID: 22965386
Though I haven't tested your code guys, I will split the points for now. Will get back to you though if there is any problem.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question