Results 1 to 10 of 10

Thread: Calling C# class from VB.NET

  1. #1

    Thread Starter
    Hyperactive Member MetallicaD's Avatar
    Join Date
    Feb 2001
    Location
    Tallahassee, FL
    Posts
    488

    Calling C# class from VB.NET

    Hello all.. I have class in C# that I would like to instantiate via VB.NET... now can I do this? I add the .cs file into my vb.net project, but I cant create an object.

    Any Ideas?
    Thanks,
    -mcd
    [vbcode]
    '*****************************
    MsgBox "MCD :: [email protected]", vbInformation + vbOKOnly, "User"
    '*****************************
    [/vbcode]

  2. #2
    Lively Member
    Join Date
    Aug 2002
    Location
    outerspace
    Posts
    126
    i would make it into a component and then add a referance to that component in your vb.net project then you can access the class
    "All those who wonder are not lost" -j.r.r tolkien

  3. #3
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    hmmm..I THINK you may have to create a C# project within the same solution then add the class and add a refernce to that project..or simply compile the C# class into a dll then set a reference to it.

    If you need help compiling the class..just paste it here in a reply and I will write quick command line compiler command to compile it to a dll.
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  4. #4

    Thread Starter
    Hyperactive Member MetallicaD's Avatar
    Join Date
    Feb 2001
    Location
    Tallahassee, FL
    Posts
    488
    Here is the code.. i would actually like to get this into VB.NET so I can manipulate it a bit within my app.. I have seen some c# to VB.NET converters.. but they arent perfect..


    using System;
    using System.Net;
    using System.Net.Sockets;

    namespace PingTest
    {
    public delegate void Reply(string host, long milliseconds, long bytes);
    public delegate void Error(string description);
    public delegate void Timeout();
    public class Ping
    {
    private const int SOCKET_ERROR = -1;
    private const int ICMP_ECHO = 8;

    public event Reply OnReply;
    public event Error OnError;
    public event Timeout OnTimeout;

    private System.Windows.Forms.Timer m_timer;
    private bool m_recd;
    private EndPoint m_endPoint;
    private EndPoint m_epServer;
    private Socket m_socket;
    private int m_dwStart=0;

    public Ping()
    {

    }
    private void OnTick(object sender, System.EventArgs e)
    {
    OnTimeout();
    m_timer.Stop();
    m_timer.Dispose();
    m_timer=null;
    }
    public void PingIt(string host, int timeout)
    {
    m_timer=new System.Windows.Forms.Timer();
    m_timer.Tick+=new EventHandler(OnTick);
    m_timer.Interval=timeout;
    m_timer.Start();
    PingHost(host);
    }

    private void PingHost(string host)
    {
    //Declare the IPHostEntry
    IPHostEntry serverHE, fromHE;
    int nBytes = 0;
    //Initilize a Socket of the Type ICMP
    m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);

    // Get the server endpoint
    try
    {
    serverHE = Dns.GetHostByName(host);
    }
    catch(Exception)
    {
    Console.WriteLine("Host not found"); // fail
    OnError("Host not found");
    m_timer.Stop();
    return ;
    }

    // Convert the server IP_EndPoint to an EndPoint
    IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0], 0);
    m_epServer = (ipepServer);

    // Set the receiving endpoint to the client machine
    fromHE = Dns.GetHostByName(Dns.GetHostName());
    IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0], 0);
    m_endPoint = (ipEndPointFrom);

    int PacketSize = 0;
    IcmpPacket packet = new IcmpPacket();
    // Construct the packet to send
    packet.Type = ICMP_ECHO; //8
    packet.SubCode = 0;
    packet.CheckSum = UInt16.Parse("0");
    packet.Identifier = UInt16.Parse("45");
    packet.SequenceNumber = UInt16.Parse("0");
    int PingData = 32; // sizeof(IcmpPacket) - 8;
    packet.Data = new Byte[PingData];
    //Initilize the Packet.Data
    for (int i = 0; i < PingData; i++)
    {
    packet.Data[i] = (byte)'#';
    }

    //Variable to hold the total Packet size
    PacketSize = PingData + 8;
    Byte [] icmp_pkt_buffer = new Byte[ PacketSize ];
    Int32 Index = 0;
    //Call a Methos Serialize which counts
    //The total number of Bytes in the Packet
    Index = Serialize(
    packet,
    icmp_pkt_buffer,
    PacketSize,
    PingData );
    //Error in Packet Size
    if( Index == -1 )
    {
    Console.WriteLine("Error in Making Packet");
    OnError("Error in Making Packet");
    m_timer.Stop();
    return ;
    }

    // now get this critter into a UInt16 array

    //Get the Half size of the Packet
    Double double_length = Convert.ToDouble(Index);
    Double dtemp = Math.Ceiling( double_length / 2);
    int cksum_buffer_length = Convert.ToInt32(dtemp);
    //Create a Byte Array
    UInt16 [] cksum_buffer = new UInt16[cksum_buffer_length];
    //Code to initilize the Uint16 array
    int icmp_header_buffer_index = 0;
    for( int i = 0; i < cksum_buffer_length; i++ )
    {
    cksum_buffer[i] =
    BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index);
    icmp_header_buffer_index += 2;
    }
    //Call a method which will return a checksum
    UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length);
    //Save the checksum to the Packet
    packet.CheckSum = u_cksum;

    // Now that we have the checksum, serialize the packet again
    Byte [] sendbuf = new Byte[ PacketSize ];
    //again check the packet size
    Index = Serialize(
    packet,
    sendbuf,
    PacketSize,
    PingData );
    //if there is a error report it
    if( Index == -1 )
    {
    Console.WriteLine("Error in Making Packet");
    OnError("Error in Making Packet");
    m_timer.Stop();
    return ;
    }

    m_dwStart = System.Environment.TickCount; // Start timing
    //send the Pack over the socket
    if ((nBytes = m_socket.SendTo(sendbuf, PacketSize, 0, m_epServer)) == SOCKET_ERROR)
    {
    Console.WriteLine("Socket Error cannot Send Packet");
    OnError("Socket Error cannot Send Packet");
    m_timer.Stop();
    }
    // Initialize the buffers. The receive buffer is the size of the
    // ICMP header plus the IP header (20 bytes)
    nBytes = 0;
    //Receive the bytes
    bool m_recd =false ;

    BeginReceiving();

    //close the socket
    }
    private void BeginReceiving()
    {
    Byte [] ReceiveBuffer = new Byte[256];
    if(!m_recd)
    {
    m_socket.BeginReceiveFrom(ReceiveBuffer, 0, 256, 0, ref m_endPoint, new AsyncCallback(EndPing), null);
    }
    }
    private void EndPing(System.IAsyncResult res)
    {
    int nBytes=m_socket.EndReceiveFrom(res, ref m_endPoint);
    int dwStop = 0;
    int timeout=0 ;
    if (nBytes == SOCKET_ERROR)
    {
    Console.WriteLine("Host not Responding") ;
    OnError("Host not Responding");
    m_timer.Stop();
    m_recd=true ;
    m_socket.Close();
    }
    else if(nBytes>0)
    {
    dwStop = System.Environment.TickCount - m_dwStart; // stop timing
    Console.WriteLine("Reply from "+m_epServer.ToString()+" in "+dwStop+"MS :Bytes Received"+nBytes);
    m_timer.Stop();
    OnReply(m_epServer.ToString(), dwStop, nBytes);
    m_recd=true;
    m_socket.Close();
    }
    timeout=System.Environment.TickCount - m_dwStart;
    if(timeout>1000)
    {
    Console.WriteLine("Time Out") ;
    OnTimeout();
    m_socket.Close();
    m_recd=true;
    }
    m_timer.Stop();
    }

    /// <summary>
    /// This method get the Packet and calculates the total size
    /// of the Pack by converting it to byte array
    /// </summary>
    public Int32 Serialize( IcmpPacket packet, Byte [] Buffer, Int32 PacketSize, Int32 PingData )
    {
    Int32 cbReturn = 0;
    // serialize the struct into the array
    int Index=0;

    Byte [] b_type = new Byte[1];
    b_type[0] = (packet.Type);

    Byte [] b_code = new Byte[1];
    b_code[0] = (packet.SubCode);

    Byte [] b_cksum = BitConverter.GetBytes(packet.CheckSum);
    Byte [] b_id = BitConverter.GetBytes(packet.Identifier);
    Byte [] b_seq = BitConverter.GetBytes(packet.SequenceNumber);

    // Console.WriteLine("Serialize type ");
    Array.Copy( b_type, 0, Buffer, Index, b_type.Length );
    Index += b_type.Length;

    // Console.WriteLine("Serialize code ");
    Array.Copy( b_code, 0, Buffer, Index, b_code.Length );
    Index += b_code.Length;

    // Console.WriteLine("Serialize cksum ");
    Array.Copy( b_cksum, 0, Buffer, Index, b_cksum.Length );
    Index += b_cksum.Length;

    // Console.WriteLine("Serialize id ");
    Array.Copy( b_id, 0, Buffer, Index, b_id.Length );
    Index += b_id.Length;

    Array.Copy( b_seq, 0, Buffer, Index, b_seq.Length );
    Index += b_seq.Length;

    // copy the data
    Array.Copy( packet.Data, 0, Buffer, Index, PingData );
    Index += PingData;
    if( Index != PacketSize/* sizeof(IcmpPacket) */)
    {
    cbReturn = -1;
    return cbReturn;
    }

    cbReturn = Index;
    return cbReturn;
    }
    /// <summary>
    /// This Method has the algorithm to make a checksum
    /// </summary>
    public UInt16 checksum( UInt16[] buffer, int size )
    {
    Int32 cksum = 0;
    int counter;

    counter = 0;

    while ( size > 0 )
    {

    UInt16 val = buffer[counter];

    cksum += Convert.ToInt32( buffer[counter] );
    counter += 1;
    size -= 1;
    }

    cksum = (cksum >> 16) + (cksum & 0xffff);
    cksum += (cksum >> 16);
    return (UInt16)(~cksum);
    }
    } // class ping
    /// <summary>
    /// Class that holds the Pack information
    /// </summary>
    public class IcmpPacket
    {
    public Byte Type; // type of message
    public Byte SubCode; // type of sub code
    public UInt16 CheckSum; // ones complement checksum of struct
    public UInt16 Identifier; // identifier
    public UInt16 SequenceNumber; // sequence number
    public Byte [] Data;


    }
    }
    [vbcode]
    '*****************************
    MsgBox "MCD :: [email protected]", vbInformation + vbOKOnly, "User"
    '*****************************
    [/vbcode]

  5. #5
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    That C# class has to be compiled into a dll first, then you can reference it.
    Dont gain the world and lose your soul

  6. #6
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    hold on ..I saw someone had converted that class to VB..let me go find it..
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  7. #7
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    crud..its not indented..but here it is

    Code:
        Option Explicit On 
        Imports System 
        Imports System.Net 
        Imports System.Net.Sockets 
        '* Class clsPing 
        '* 
        '*Author : Paulo S. Silva Jr. 
        '* Date : September 2002 
        '* Objective : Ping a host and return basic informations 
        '* 
        '* Class Properties 
        '* 
        '*+------------+-------------+-------------------------------------------------+ 
        '*| Name| Type| Description | 
        '*+------------+-------------+-------------------------------------------------+ 
        '*| DataSize| Integer | Size of the data to be send to the host | 
        '*| Identifier | Integer | Identifier of ping packet| 
        '*| Sequence| Integer | Sequence of the packet | 
        '*| LocalHost | IPHostEntry | Info for Local Computer | 
        '*| Host| Object | Host Entry for the remote computer | 
        '*+------------+-------------+-------------------------------------------------+ 
        '* 
        '* Class Methods 
        '* 
        '*+-------------------+----------------------------------------------------+ 
        '*| Name | Description| 
        '*+-------------------+----------------------------------------------------+ 
        '*| PingHost | Pings the specified host| 
        '*+-------------------+----------------------------------------------------+ 
        '* 
        '* Parts of the code based on information from Visual Studio Magazine 
        '* more info : http://www.fawcette.com/vsm/2002_03/...qa/default.asp 
        '* 
        Public Class clsPing 
        Public Structure stcError 
        Dim Number As Integer 
        Dim Description As String 
        End Structure 
        Public Const PING_SUCCESS As Long = 0 
        Public Const PING_ERROR As Long = (-1) 
        Public Const PING_ERROR_BASE As Long = &H8000 
        Public Const PING_ERROR_HOST_NOT_FOUND As Long = PING_ERROR_BASE + 1 
        Public Const PING_ERROR_SOCKET_DIDNT_SEND As Long = PING_ERROR_BASE + 2 
        Public Const PING_ERROR_HOST_NOT_RESPONDING As Long = PING_ERROR_BASE + 3 
        Public Const PING_ERROR_TIME_OUT As Long = PING_ERROR_BASE + 4 
        Private Const ICMP_ECHO As Integer = 8 
        Private Const SOCKET_ERROR As Integer = -1 
        Private udtError As stcError 
        Private Const intPortICMP As Integer = 7 
        Private Const intBufferHeaderSize As Integer = 8 
        Private Const intPackageHeaderSize As Integer = 28 
        Private intDataSize As Byte 
        Private ipheLocalHost As System.Net.IPHostEntry 
        Private ipheHost As System.Net.IPHostEntry 
        Public Property DataSize() As Byte 
        Get 
        Return intDataSize 
        End Get 
        Set(ByVal Value As Byte) 
        intDataSize = Value 
        End Set 
        End Property 
        Public ReadOnly Property Identifier() As Byte 
        Get 
        Return 0 
        End Get 
        End Property 
        Public ReadOnly Property Sequence() As Byte 
        Get 
        Return 0 
        End Get 
        End Property 
        Public ReadOnly Property LocalHost() As System.Net.IPHostEntry 
        Get 
        Return ipheLocalHost 
        End Get 
        End Property 
        Public Property Host() As Object 
        Get 
        Return ipheHost 
        End Get 
        Set(ByVal Value As Object) 
        If (Value.GetType.ToString.ToLower = "system.string") Then 
        '* 
        '* Find the Host's IP address 
        '* 
        Try 
        ipheHost = System.Net.Dns.GetHostByName(Value) 
        Catch 
        ipheHost = Nothing 
        udtError.Number = PING_ERROR_HOST_NOT_FOUND 
        udtError.Description = "Host " & _
        ipheHost.HostName & " not found." 
        End Try 
        ElseIf (Value.GetType.ToString.ToLower = "system.net.iphostentry") Then 
        ipheHost = (Value) 
        Else 
        ipheHost = Nothing 
        End If 
        End Set 
        End Property 
        '* 
        '* Class Constructor 
        '* 
        Public Sub New() 
        '* 
        '* Initializes the parameters 
        '* 
        intDataSize = 32 
        udtError = New stcError() 
        '* 
        '* Get local IP and transform in EndPoint 
        '* 
        ipheLocalHost = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()) 
        '* 
        '* Defines Host 
        '* 
        ipheHost = Nothing 
        End Sub 
        '* 
        '*Function : PingHost 
        '* Author : Paulo dos Santos Silva Jr 
        '*Date : 05/09/2002 
        '* Objective : Pings a specified host 
        '* 
        '* Parameters : Host as String 
        '* 
        '*Returns : Response time in milliseconds 
        '* (-1) if error 
        '* 
        Public Function Ping() As Long 
        Dim intCount As Integer 
        Dim aReplyBuffer(255) As Byte 
        Dim intNBytes As Integer = 0 
        Dim intEnd As Integer 
        Dim intStart As Integer 
        Dim epFrom As System.Net.EndPoint 
        Dim epServer As System.Net.EndPoint 
        Dim ipepServer As System.Net.IPEndPoint 
        '* 
        '* Transforms the IP address in EndPoint 
        '* 
        ipepServer = New System.Net.IPEndPoint(ipheHost.AddressList(0), 0) 
        epServer = CType(ipepServer, System.Net.EndPoint) 
        epFrom = New System.Net.IPEndPoint(ipheLocalHost.AddressList(0), 0) 
        '* 
        '* Builds the packet to send 
        '* 
        DataSize = Convert.ToByte(DataSize + intBufferHeaderSize) 
        '* 
        '* The packet must by an even number, 
        ‘* so if the DataSize is and odd number adds one 
        '* 
        If (DataSize Mod 2 = 1) Then 
        DataSize += Convert.ToByte(1) 
        End If 
        Dim aRequestBuffer(DataSize - 1) As Byte 
        '* 
        '* --- ICMP Echo Header Format --- 
        '* (first 8 bytes of the data buffer) 
        '* 
        '* Buffer (0) ICMP Type Field 
        '* Buffer (1) ICMP Code Field 
        '* (must be 0 for Echo and Echo Reply) 
        '* Buffer (2) checksum hi 
        '* (must be 0 before checksum calc) 
        '* Buffer (3) checksum lo 
        '* (must be 0 before checksum calc) 
        '* Buffer (4) ID hi 
        '* Buffer (5) ID lo 
        '* Buffer (6) sequence hi 
        '* Buffer (7) sequence lo 
        '* Buffer (8)..(n) Ping Data 
        '* 
        '* 
        '* Set Type Field 
        '* 
        aRequestBuffer(0) = Convert.ToByte(ICMPType.Echo) 
        '* 
        '* Set ID field 
        '* 
        BitConverter.GetBytes(Identifier).CopyTo(aRequestBuffer, 4) 
        '* 
        '* Set Sequence 
        '* 
        BitConverter.GetBytes(Sequence).CopyTo(aRequestBuffer, 6) 
        '* 
        '* Load some data into buffer 
        '* 
        Dim i As Integer 
        For i = 8 To DataSize - 1 
        aRequestBuffer(i) = Convert.ToByte(i Mod 8) 
        Next i 
        '* 
        '* Calculate Checksum 
        '* 
        Call CreateChecksum(aRequestBuffer, _
        DataSize, _
        aRequestBuffer(2), _
        aRequestBuffer(3)) 
        '* 
        '* Try send the packet 
        '* 
        Try 
        '* 
        '* Create the socket 
        '* 
        Dim sckSocket As New System.Net.Sockets.Socket( _ 
        Net.Sockets.AddressFamily.InterNetwork, _ 
        Net.Sockets.SocketType.Raw, _ 
        Net.Sockets.ProtocolType.Icmp) 
        sckSocket.Blocking = False 
        '* 
        '* Records the Start Time 
        '* 
        intStart = System.Environment.TickCount 
        sckSocket.SendTo(aRequestBuffer, _
        0, _
        DataSize, _
        SocketFlags.None, _
        ipepServer) 
        intNBytes = sckSocket.ReceiveFrom(aReplyBuffer, _
        SocketFlags.None, _
        epServer) 
        intEnd = System.Environment.TickCount 
        If (intNBytes > 0) Then 
        '* 
        '* Informs on GetLastError the state of the server 
        '* 
        udtError.Number = (aReplyBuffer(19) * &H100) + aReplyBuffer(20) 
        Select Case aReplyBuffer(20) 
        Case 0 : udtError.Description = "Success" 
        Case 1 : udtError.Description = "Buffer too Small" 
        Case 2 : udtError.Description = "Destination Unreahable" 
        Case 3 : udtError.Description = "Dest Host Not Reachable" 
        Case 4 : udtError.Description = "Dest Protocol Not Reachable" 
        Case 5 : udtError.Description = "Dest Port Not Reachable" 
        Case 6 : udtError.Description = "No Resources Available" 
        Case 7 : udtError.Description = "Bad Option" 
        Case 8 : udtError.Description = "Hardware Error" 
        Case 9 : udtError.Description = "Packet too Big" 
        Case 10 : udtError.Description = "Reqested Timed Out" 
        Case 11 : udtError.Description = "Bad Request" 
        Case 12 : udtError.Description = "Bad Route" 
        Case 13 : udtError.Description = "TTL Exprd In Transit" 
        Case 14 : udtError.Description = "TTL Exprd Reassemb" 
        Case 15 : udtError.Description = "Parameter Problem" 
        Case 16 : udtError.Description = "Source Quench" 
        Case 17 : udtError.Description = "Option too Big" 
        Case 18 : udtError.Description = "Bad Destination" 
        Case 19 : udtError.Description = "Address Deleted" 
        Case 20 : udtError.Description = "Spec MTU Change" 
        Case 21 : udtError.Description = "MTU Change" 
        Case 22 : udtError.Description = "Unload" 
        Case Else : udtError.Description = "General Failure" 
        End Select 
        End If 
        Return (intEnd - intStart) 
        Catch oExcept As Exception 
        ' 
        End Try 
        End Function 
        Public Function GetLastError() As stcError 
        Return udtError 
        End Function 
        ' ICMP requires a checksum that is the one's 
        ' complement of the one's complement sum of 
        ' all the 16-bit values in the data in the 
        ' buffer. 
        ' Use this procedure to load the Checksum 
        ' field of the buffer. 
        ' The Checksum Field (hi and lo bytes) must be 
        ' zero before calling this procedure. 
        Private Sub CreateChecksum(ByRef data() As Byte, _
        ByVal Size As Integer, _
        ByRef HiByte As Byte, _
        ByRef LoByte As Byte) 
        Dim i As Integer 
        Dim chk As Integer = 0 
        For i = 0 To Size - 1 Step 2 
        chk += Convert.ToInt32(data(i) * &H100 + data(i + 1)) 
        Next 
        chk = Convert.ToInt32((chk And &HFFFF&) + Fix(chk / &H10000&)) 
        chk += Convert.ToInt32(Fix(chk / &H10000&)) 
        chk = Not (chk) 
        HiByte = Convert.ToByte((chk And &HFF00) / &H100) 
        LoByte = Convert.ToByte(chk And &HFF) 
        End Sub 
        End Class
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  8. #8

    Thread Starter
    Hyperactive Member MetallicaD's Avatar
    Join Date
    Feb 2001
    Location
    Tallahassee, FL
    Posts
    488
    Cander, and everyone else, thanks for helping out here.. I had a different ICMP class that I was using to echo a network user, but it was always returning inaccurate results.. so I found this ping class and it seems to work perfectly...

    -mcd
    [vbcode]
    '*****************************
    MsgBox "MCD :: [email protected]", vbInformation + vbOKOnly, "User"
    '*****************************
    [/vbcode]

  9. #9

    Thread Starter
    Hyperactive Member MetallicaD's Avatar
    Join Date
    Feb 2001
    Location
    Tallahassee, FL
    Posts
    488
    Well, I used the code Cander posted and tweaked it alittle bit, but im getting odd results from my network.. our servers cache the host name and IP.. so it will return that the host was found, but will time out.. for some reason, when it times out, it throws an error instead of going through the long case statement...

    also, is there a way i can set the time out on this... i wouldnt mind if it attempted to ping for about 3 seconds to verify the machine is on the network and working..

    thanks for all the help so far!
    -mcd
    [vbcode]
    '*****************************
    MsgBox "MCD :: [email protected]", vbInformation + vbOKOnly, "User"
    '*****************************
    [/vbcode]

  10. #10
    Fanatic Member
    Join Date
    May 2001
    Posts
    525

    Question hmmm..

    I have no idea what I'm doing. How do I use Cander's code? I created a class file and pasted the code in there. Now I'm getting this Build Error "Name 'ICMPType' is not declared". What am I missing here? Do I need to compile it as a DLL? How do I do that? I only have VB.Net 2003 Standard.
    Last edited by jsun9; Jul 20th, 2004 at 12:21 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width