Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a power on-off device to control. If the device is connected to the network, my code works fine. I remove the device from the network on purpose to test it as if the device malfunctions (like power off). And I find out that the System hangs.
I trace that the socket.accept does not execute - 'accept is ok' is not written to a log file. ex.message does not write as well.
My purpose is to send a message to support if there is any device malfunction.
Using gSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
WriteLog("Start. ")
Dim remoteSocket As Socket
Try
gSocket.SendTimeout = 5000
gSocket.ReceiveTimeout = 5000
gSocket.Bind(vEndPoint) ' vEndpoint is the local machine
WriteLog("bind is ok. ")
gSocket.Listen(10)
WriteLog("listen is ok. ")
remoteSocket = gSocket.Accept
WriteLog("accept is ok. ")
Catch ex As Exception
WriteLog(ex.Message)
Finally
End Try
How can I solve this?
I use BeginAccept to solve it.
Dim acceptResult As IAsyncResult = gSocket.BeginAccept(Nothing, Nothing)
Dim Success As Boolean = acceptResult.AsyncWaitHandle.WaitOne(vTimeout, True)
If Success Then
remoteSocket = gSocket.EndAccept(acceptResult)
WriteLog("beginaccept is ok. ")
Else
gSocket.Close()
WriteLog("beginaccept failed. ")
End If
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am looking for away to get this value:
I am building a program that will be installed on 100s of computers and servers. And i need to figure out how i can get the name of the anti virus in vb.net.
This can also be a powershell script. It is possible to read the output from a powershell script in vb.net
The problem is: With all the scripts that I could find any where it was not able to even get my own antivirus. There needs to be a way to read the information from the control panel right? Or is that impossible.
So after some searching i found this: with SecurityCenter2. For me this works
Dim IPAddress As String = "127.0.0.1"
Dim connectionOptions As New ConnectionOptions()
connectionOptions.EnablePrivileges = True
connectionOptions.Impersonation = ImpersonationLevel.Impersonate
Dim managementScope As New ManagementScope(String.Format("\\{0}\root\SecurityCenter2", IPAddress), connectionOptions)
managementScope.Connect()
Dim objectQuery As New ObjectQuery("SELECT * FROM AntivirusProduct")
Dim managementObjectSearcher As New ManagementObjectSearcher(managementScope, objectQuery)
Dim managementObjectCollection As ManagementObjectCollection = managementObjectSearcher.[Get]()
Dim antivirus As String = ""
If managementObjectCollection.Count > 0 Then
For Each item As ManagementObject In managementObjectCollection
antivirus = antivirus + item("displayName") + " - "
Next
antivirus = antivirus.Remove(antivirus.Count - 3, 3)
End If
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am making visual basic email software this software send attachment files and messages i want to send mails many companies i am adding To field but i want to add BCC and CC mail system also include but it don't have any idea how i code for this ..if any one have a good sense of this give me a idea ....
or any other way to add multiples mails system to with the attachment of Doc CV file .... i also need to know to add filter that someone not add any other format file to send .But mainly i need to know how to Add BCC blind carbon copy system in vb and CC carbon copy system..
Imports System.Net
Imports System.Net.Mail
Private mpMessage As MailMessage = Nothing
Private mpSMTPSvr As SmtpClient = Nothing
'------------------------------------------------------------------------
'-> Send The Message
'------------------------------------------------------------------------
MailerHost = "Addrss-of-your-emailer-host-server"
mpMessage = New System.Net.Mail.MailMessage()
mpMessage.Body = "Message body text goes here"
If Trim(SenderNameValue) <> "" Then
mpMessage.From = New System.Net.Mail.MailAddress("senderemail#hotmail.com", SenderNameValue)
mpMessage.Sender = New System.Net.Mail.MailAddress("senderemail#hotmail.com", SenderNameValue)
Else
mpMessage.From = New System.Net.Mail.MailAddress("senderemail#hotmail.com", "Name_Unspecified")
mpMessage.Sender = New System.Net.Mail.MailAddress("senderemail#hotmail.com", "Name_Unspecified")
End If
mpMessage.Priority = System.Net.Mail.MailPriority.High
mpMessage.Subject = "[WEB-REPONSE] - Correspondence via Website response form."
mpMessage.To.Add(Trim("recipient#yahoo.com"))
mpMessage.CC.Add(Trim("secretary#yahoo.com"))
mpMessage.BCC.Add(Trim("manager#yahoo.com"))
Try
mpSMTPSvr.Send(mpMessage)
SendStandardCommunicae = True
Catch ex As Net.Mail.SmtpException
ReturnErrorid = eEML_NETWORKERRORSENDINGEMAIL
ReturnErrorText = "A network error occurred whilst trying to send your message, please check your details for syntax errors and try again later.<br />If the error occurs consistently please contact the site administrator or use an alternative method of contact.<br /><br />"
ReturnErrorText = ReturnErrorText & "Extra Information:" & ex.Message
End Try
I'm currently talking to another computer to see what events they have occurring. I have setup a Wql Event query like so below:
Console.WriteLine("Polling...")
Try
Dim query As New WqlEventQuery("SELECT * FROM Lnl_AccessEvent")
Dim accessEventWatcher = New ManagementEventWatcher("SELECT * FROM Lnl_AccessEvent")
accessEventWatcher.Start()
accessEventWatcher.WaitForNextEvent()
Console.WriteLine("AccessEvent Occured.")
Catch ex As Exception
Console.WriteLine(ex.Message + " " + ex.StackTrace)
End Try
On the ".Start()" line, I get an exception stating "Invalid class" and "ManagementException". I know the connection is working since before this instance I'm able to connect and get the basic info from the remote computer's WMI, like IP address. The only solutions I have found is that has to do with my target build being only x86, but now it's at AnyCPU and still has this issue.
What is causing this error?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I'm wondering how I'd go about catching an error and then displaying its details in a custom ListBox or something. The idea is to allow a custom message to appear that's simple, like "Woops, something's went wrong!" but still be able to provide the information for troubleshooting. If someone could help me build this code I'd be really grateful.
So say I have code that could result in an error, like connecting to the internet. How would I be able to catch the error and display it in a separate form (pop-up window)?
I apologize if this seams really basic but I'm new to this stuff and I just don't like the normal error window.
Use following code to output error to user:
Try
'code
Catch ex As Exception
MessageBox.Show(string.Format("Error: {0}", ex.Message))
End Try
I'm wondering how I'd go about catching an error and then displaying
its details in a custom ListBox or something.
If you would like to add the error to a listbox:
Try
'code
Catch ex As Exception
listBox1.Items.Add("Whoops, something went wrong!")
End Try
In the end I ended up with this:
Try
'Code which may error
Catch ex As Exception
MessageBox.Show("Whoops! An error was encountered during the login-in stage. The Server may be offline, un-reachable or your Server Credentials may be in-correct. Please contact U.G Studio for further details. " & _
vbNewLine & "" & vbNewLine & String.Format("Error: {0}", ex.Message))
It allows me to display a custom message whilst still retaining the 'technical' information about the error.
Thanks for the help people!
Here is a code template to get you started:
Try
'Your code
Catch ex As Exception
MessageBox.Show("Woops, something's went wrong!")
'get troubleshooting info out of ex, stack trace perhaps
End Try
If you want something super simple, you could do this:
Try
'Try connecting to the internet
Catch ex As WebException
Dim message = String.Format(
"Encountered an error while connecting to internet: {0}", ex.Message)
MessageBox.Show(message)
End Try
But if you want something a bit more fancy, I'd recommend creating a new form with maybe a Label and RichTextBox on it. You could give it a constructor that takes the exception and will populate the form's controls. I'd use ToString on the exception to show details since this will print out a nice stacktrace and also print out any details of inner exceptions recursively:
Public Sub New(ex As Exception)
InitializeComponent() 'This call is required by Visual Studio.
Me.Label1.Text = String.Format(
"Encountered the following error: {0}", ex.Message)
Me.RichTextBox1.Text = ex.ToString()
End Sub
You could call it from your main form like this:
Try
'Try connecting to the internet
Catch ex As WebException
Dim errorForm = New ErrorForm(ex)
errorForm.Show()
End Try
You could write a function to use in place of MsgBox e.g.:
Public Function LogMsgBox(
ex As Exception,
Prompt As String,
Optional Buttons As MessageBoxButtons = MessageBoxButtons.OK,
Optional Title As String = "OIS Error",
Optional ProgrammerNote As String = "",
Optional SuppressMsgBox As Boolean = False,
Optional FormRef As Object = Nothing) As MsgBoxResult
In the function you can get as fancy as you like - most likely show a dialog box or form more to your liking.
It is handy to log errors so you get feedback on problems. Users just tend to click by problems and not report them.
Also look into Application Framework for VB - it can capture unhandled errors the users also fail to report.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Can anyone please share a simple code for VB 2008 to open a port. I would like it to be just like utorrent how you can change the listening port for data transfer. thanks a lot if you can help me!
As Avner indicated, uTorrent is not simple code. If you'd like to do anything on that level, then you've got a lot to do.
Here is a simple sample socket program you can build on.
Imports System.Net
Imports System.Net.Sockets
Module Module1
Sub Main()
Console.WriteLine("Enter the host name or IP Address to connect to:")
Dim hostName = Console.ReadLine().Trim()
If hostName.Length = 0 Then
' use the local computer if there is no host provided
hostName = Dns.GetHostName()
End If
Dim ipAddress As IPAddress = Nothing
' parse and select the first IPv4 address
For Each address In Dns.GetHostEntry(hostName).AddressList
If (address.AddressFamily = AddressFamily.InterNetwork) Then
ipAddress = address
Exit For
End If
Next
' you will have to check beyond this point to ensure
' there is a valid address before connecting
Dim client = New TcpClient()
Try
' attempt to connect on the address
client.Connect(ipAddress, 80)
' do whatever you want with the connection
Catch ex As SocketException
' error accessing the socket
Catch ex As ArgumentNullException
' address is null
' hopefully this will never happen
Catch ex As ArgumentOutOfRangeException
' port must be from 0 to 64k (&HFFFF)
' check and ensure you've used the right port
Catch ex As ObjectDisposedException
' the tcpClient has been disposed
' hopefully this will never happen
Catch ex As Exception
' any other exception I haven't dreamt of
Finally
' close the connection
' the TcpClient.Close() method does not actually close the
' underlying connection. You have to close it yourself.
' http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B821625
client.GetStream().Close()
' then close the client's connection
client.Close()
End Try
End Sub
End Module
Be aware that socket programming is quite complicated and you will have to thoroughly test your code for all edge cases.
Good luck!
uTorrent is anything but a "simple code". It's a complicated application with a lot of network logic going on beyond just opening a port and pushing bits in and out of it.
But your starting point for low-level communications handling would be the System.Net.Sockets namespace, which contains the Socket class. It allows low-level control such as opening a port, listening for connections and handling them yourself.
Here's a tutorial about Socket programming in VB.NET, but you'll probably find more information if you search for "C# Socket tutorial". C# syntax is a bit different than VB.NET, but it uses the same classes and the same concepts, so you'll probably be able to apply the lessons to your own code.