Declaration expected in VB dll - vb.net

First of all thanking everyone....
I am currently working on VB. I am using Visual Studio 2008.
The piece of code below is a console application which builds without any error.
Imports System.Net
Module Module1
Public Sub Main()
Dim address As IPAddress
Dim remoteIP As System.Net.IPEndPoint
Dim socketAddress As System.Net.SocketAddress
Try
address = IPAddress.Parse("192.168.0.187")
remoteIP = New System.Net.IPEndPoint(address, 0)
socketAddress = remoteIP.Serialize()
Console.WriteLine("Address Family :" & remoteIP.AddressFamily.ToString())
Console.WriteLine("IP :" & remoteIP.Address.ToString() & "Port :" & remoteIP.Port.ToString())
Console.WriteLine("Socket address :" & socketAddress.ToString())
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
End Try
End Sub
End Module
In the next program which is a dll the same gives error saying "Declaration Expected for addr, remoteIP and socketAddr"
Imports System.Net
Public Class Class1
End Class
Public Class ethernet
Dim addr As IPAddress
Dim remoteIP As System.Net.IPEndPoint
Dim socketAddr As System.Net.SocketAddress
addr = IPAddress.Parse("192.168.0.187")
remoteIP = New System.Net.IPEndPoint(addr,0)
socketAddr = remoteIP.Serialize()
End Class
Can anybody tell me why is this happening...

Your code in the second class ethernet is not contained within a Method, therefore you are only declaring the addr, remoteIP and socketAddr variables.
To make that work just put the code in a method, like:
Public Class ethernet
Public Function SerializeSocket(address As String) As System.Net.SocketAddress
Dim addr As IPAddress = IPAddress.Parse("192.168.0.187")
Dim remoteIP As System.Net.IPEndPoint = New System.Net.IPEndPoint(addr,0)
Return remoteIP.Serialize()
End Sub
End Class

Related

VB.net TCP Non-Blocking State

I have code that sending string from client to server with TCP Connection.
But i dont know how to convert it to NonBlocking TCP State Connection.
i have try to put socket.Blocking = FALSE, but that code give me an error.
Socket Error Code: 10035
Exception Title: A non-blocking socket operation could not be completed immediately
Heres my code for sending string from client to server.
Server Code :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim soket As Socket
Sub Main()
Try
Dim alamatIP As IPAddress = IPAddress.Parse("127.0.0.1")
Dim tcpListener As New TcpListener(alamatIP, 8000)
'soket.Blocking = False - THIS WILL GIVE ME AN ERROR
tcpListener.Start()
System.Console.WriteLine("Server port 8000...")
Dim myendpoint As IPEndPoint
myendpoint = CType(tcpListener.LocalEndpoint, IPEndPoint)
System.Console.WriteLine("IP : " + myendpoint.Address.ToString + " and port is " + myendpoint.Port.ToString)
System.Console.WriteLine("Waiting for connection !")
soket = tcpListener.AcceptSocket()
myendpoint = CType(soket.RemoteEndPoint(), IPEndPoint)
System.Console.WriteLine("Receiving from " + myendpoint.Address.ToString())
Dim bitData(100) As Byte
Dim newString As String = ""
Do
Try
Dim size As Integer = soket.Receive(bitData)
newString = Encoding.ASCII.GetString(bitData)
Console.WriteLine(newString)
Array.Clear(bitData, 0, bitData.Length)
Catch ex As Exception
Console.Write(ex.ToString())
End Try
Loop While newString <> "exit"
soket.Close()
tcpListener.Stop()
Catch ex As Exception
Console.WriteLine("Error ..." + ex.ToString())
End Try
Console.ReadLine()
End Sub
End Module
Client Code :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Imports System.Threading
Module Module1
Sub Main()
Try
Dim tcpClient As New TcpClient 'creating the client
Console.WriteLine("Connecting....")
tcpClient.Connect("127.0.0.1", 8000) 'connecting the client the server
'port is same as in the server
Console.WriteLine("Connected")
Console.WriteLine("Enter the string to be transmitted : ")
Dim strMessage As String
Dim stm As Stream
Dim counter As Integer = 0
Do
stm = tcpClient.GetStream() 'getting the stream of the client
Dim ascenc As New ASCIIEncoding
strMessage = Console.ReadLine()
Dim byteData() As Byte = ascenc.GetBytes(strMessage)
Console.WriteLine("Transmitted ")
stm.Write(byteData, 0, byteData.Length())
Loop While strMessage <> "exit"
tcpClient.Close() 'closing the connection
Catch ex As Exception
Console.WriteLine("Error..." + ex.StackTrace.ToString()) 'writing the exception into the console
End Try
End Sub
End Module
Thanks for any help.
When you attempt to read from a non-blocking socket or write to it and the operation cannot be completed right now, then the socket is supposed to signal an error. In VB it means it is supposed to raise an exception. For example, this happens when your machine hasn't received any data but you try to Read something.
Before trying an operation on a non-blocking socket, call Select or Poll in order to make sure it is ready for the operation.

Receive many file with server

I use a program to receive file that client send with specific port.
The problem is when a lot of client send file to this server, it wait to receive file in order, it receive files consecutive.
Now i need help to change this code that it received files Parallel.
For example 10 client, send file to this server.it receive all file in order, but i need it receive them Parallel.
I hope you understand what i want.
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Module Module1
Public destinationfolder As String
Dim rcf As New RecievedFile
Public port As String
Sub Main()
Console.Title = "B64S Server"
Console.WindowHeight = 30
DrawGraphics(2)
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine(" Created by: Turbocharged Chameleon")
DrawGraphics(2) ''draws some graphics from another sub
DrawGraphics(0)
DrawGraphics(2)
Console.ForegroundColor = ConsoleColor.White
Console.WriteLine("Destination Folder:")
destinationfolder = Console.ReadLine() ''reads line for destination folder
Console.WriteLine("Port:")
port = Console.ReadLine() ''reads line and sets the port
If Directory.Exists(destinationfolder) = False Then
MsgBox("destination folder doesn't exist!")
End ''ends program if folder doesn't exist
End If
Console.Clear()
''wait
DrawGraphics(1)
rcf.Threader = New Thread(New System.Threading.ThreadStart(AddressOf rcf.enter code hereRecieve))
rcf.Threader.Start() ''starts listening on port for incoming data
End Sub
Private Sub DrawGraphics(ByVal int As Integer)
If int = 0 Then
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM")
Console.WriteLine("MMMMMMMMMMMMMM$,.........$MMMMOMMMMMMMMM")
Console.WriteLine("MMMMMMMMMMM8,,......... .. M....MMMMMMM")
ElseIf int = 1 Then
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("MMMMMMMMMMMMMMMII+++:::::==+++??$$$MMMMM")
Console.WriteLine("MMMMMMMMMMII???~~.............~~$$$MMMMM")
Console.WriteLine("MMMMMMMMMMII???~~.............~~$$$MMMMM")
ElseIf int = 2 Then
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("----------------------------------------")
End If
End Sub
End Module
and Recieved File Class:
Public Class RecievedFile
Public Threader As Thread
Dim TCPListener As TcpListener
Dim Socket As Socket
Sub Recieve()
Try
TCPListener = New TcpListener(IPAddress.Any, port)
TCPListener.Start()
While True
Try
Socket = TCPListener.AcceptSocket
Dim MyNetworkStream As NetworkStream = New NetworkStream(Socket)
Dim mystreamreader As StreamReader = New StreamReader(MyNetworkStream)
Console.WriteLine("Recieving file...")
Dim str As String = mystreamreader.ReadToEnd
Console.WriteLine(str)
Dim fn As String = str.Remove(str.IndexOf("#"))
Dim filenamelength As Integer = fn.Length
Dim b64string As String = str.Substring(str.IndexOf("#") + 1)
Console.WriteLine("BS64")
Dim binaryData() As Byte = Convert.FromBase64String(b64string)
Console.WriteLine("done")
If My.Computer.FileSystem.FileExists(destinationfolder & "\" & fn) Then
System.IO.File.Delete(destinationfolder & "\" & fn)
Dim fs As New FileStream(destinationfolder & "\" & fn, FileMode.CreateNew)
fs.Write(binaryData, 0, binaryData.Length)
fs.Close()
Console.WriteLine("Recieved file: " & fn)
Else
Dim fs As New FileStream(destinationfolder & "\" & fn, FileMode.CreateNew)
fs.Write(binaryData, 0, binaryData.Length)
fs.Close()
Console.WriteLine("Recieved file: " & fn)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End While
Catch ex2 As Exception
MsgBox(ex2.Message)
End Try
End Sub
End Class
Maybe pass the receiver part of the code into a new instance of a background worker?
That might allow each stream to come in on its own thread.
I haven't tried, but that was just the first thought that came to mind.

Visual Basic Com Port doesn't Receive

I'm Trying to communicate with a com port using a visual basic console application. The com port never receives data, and times out every time. I've confirmed with a different program written in python that the com port and device are working correctly. I am sure that I am just missing something since I am new to VB. I've tried opening the com port using two method, neither of which returned an error (the first method I used is commented out). Below is my script.
Imports System
Imports System.IO.Ports
Imports System.IO
Module Module1
Function ReceiveSerialData(ByVal data As String) As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim add As String = "Com6"
'Dim port As New SerialPort("Com6", 9600, Parity.None, 8, StopBits.One)
Dim port As SerialPort = My.Computer.Ports.OpenSerialPort("COM6", 9600, Parity.None, 8, StopBits.One)
Try
Dim state As Boolean = (port.IsOpen)
If state = False Then
Console.Write("Opening Port" + vbNewLine)
port.Open()
End If
port.ReadTimeout = 5000
port.Write("z")
Dim cat As String = port.ReadLine()
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If port IsNot Nothing Then port.Close()
End Try
Console.Write(returnStr)
Return returnStr
End Function
Sub Main()
Console.WriteLine("Enter Command for Telescope!:")
Dim stdin As TextReader = Console.In
Dim sInput As String = stdin.ReadLine
Console.Write("Sending Command " + sInput + "." + vbNewLine)
Dim sent As String
sent = "z"
Dim recv As String
recv = ReceiveSerialData(sent)
Console.Write(recv)
End Sub
End Module

How to modify existing REST web service to work with SSL

I have the following simple REST service running based on the code found on MSDN - code below.
How can I modify this to be able to use transport security - SSL ?
I've been googling around for a solution, but it seems that most examples are mentioning to modify web.config file, but this example doesn't even have that... Thanks for any help with this one!
Imports System
Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Web
Imports System.Text
<ServiceContract()> _
Public Interface IService
<OperationContract()> _
<WebGet()> _
Function EchoWithGet(ByVal s As String) As String
<OperationContract()> _
<WebInvoke()> _
Function EchoWithPost(ByVal s As String) As String
end interface
Public Class Service
Implements IService
Public Function EchoWithGet(ByVal s As String) As String Implements IService.EchoWithGet
Return "You said " + s
End Function
Public Function EchoWithPost(ByVal s As String) As String Implements IService.EchoWithPost
Return "You said " + s
End Function
End Class
Module program
Sub Main()
Dim host As WebServiceHost = New WebServiceHost(GetType(Service), New Uri("http://localhost:8000/"))
Try
Dim ep As ServiceEndpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "")
host.Open()
Using cf As New ChannelFactory(Of IService)(New WebHttpBinding(), "http://localhost:8000")
cf.Endpoint.Behaviors.Add(New WebHttpBehavior())
Dim channel As IService = cf.CreateChannel()
Dim s As String
Console.WriteLine("Calling EchoWithGet via HTTP GET: ")
s = channel.EchoWithGet("Hello, world")
Console.WriteLine(" Output: {0}", s)
Console.WriteLine("")
Console.WriteLine("This can also be accomplished by navigating to")
Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!")
Console.WriteLine("in a web browser while this sample is running.")
Console.WriteLine("")
Console.WriteLine("Calling EchoWithPost via HTTP POST: ")
s = channel.EchoWithPost("Hello, world")
Console.WriteLine(" Output: {0}", s)
Console.WriteLine("")
End Using
Console.WriteLine("Press <ENTER> to terminate")
Console.ReadLine()
host.Close()
Catch cex As CommunicationException
Console.WriteLine("An exception occurred: {0}", cex.Message)
host.Abort()
End Try
End Sub
End Module
Adding the following solved my problem and all traffic goes through HTTPS. I hope this will help someone in the future.
Dim binding As New WebHttpBinding
binding.Security.Mode = WebHttpSecurityMode.Transport
Dim store As New X509Store(StoreName.My, StoreLocation.LocalMachine)
store.Open(OpenFlags.ReadWrite)
Dim cert = store.Certificates.Find(X509FindType.FindBySubjectName, "localhost", False)(0)
store.Close()
Dim bindPortToCertificate As New Process
bindPortToCertificate.StartInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "netsh.exe")
bindPortToCertificate.StartInfo.Arguments = String.Format("http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={{{2}}}", 22370, cert.Thumbprint, Guid.NewGuid())
bindPortToCertificate.Start()
bindPortToCertificate.WaitForExit()

Socket program freezes on load

The program freezes on load. At first it was working as it was supposed to, but after I cleaned and built the solution, it only freezes on load. The weird part is that it only freezes and it does not show the exception message for the catch.
here is the class file I used
Imports System.Net ' for IPAddress
Imports System.Net.Sockets 'for TcpListener
Public Class clientSocket
Dim aString As String
Dim port As Integer 'this is the port number
Dim localAddr As IPAddress ' this is the IP address
Dim client As TcpClient ' This is for the TCP/IP Protocol
Dim clientListener As TcpListener
Public Function startSocket() As String
Try
'define the two values for your Server
port = 1234
localAddr = IPAddress.Loopback 'loopbak = 127.0.0.1 = myself
clientListener = New TcpListener(localAddr, 4321)
client = New TcpClient(localAddr.ToString, port)
Return "Connected to the server"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function receive() As String
Try
clientListener.Start()
Dim mySocket As Socket
mySocket = clientListener.AcceptSocket()
Dim recieveBuff(225) As Byte
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
Dim str As String = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
Return str
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
str = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
clientListener.Stop()
Catch exp As Exception
Return "Exception: " + exp.Message
End Try
End Function
End Class
Or use BeginAcceptSocket, but you'll have to move your receive code to the callback.
mySocket = clientListener.AcceptSocket()
These lines block further action untill a socket has been acepted, it will block your code until a socket has been accepted. Use thread to prevent blocking