Using AxInterop.MSWinsockLib for socket programming's state stays at 6-Connecting - vb.net

I am using AxInterop.MSWinsockLib.dll together with Interop.MSWinsockLib.dll and MSWINSCK.OCX to create a socket connection to a printer. The following code is what I use but no matter if I put the code inside a while loop or Thread.Sleep() after the attempt to connect, The connection state still remains at 6, which is "Connecting". Please assist ASAP.
Try
Dim sock As AxMSWinsockLib.AxWinsock
sock = New AxMSWinsockLib.AxWinsock
CType(sock, System.ComponentModel.ISupportInitialize).BeginInit()
Me.Controls.Add(sock)
CType(sock, System.ComponentModel.ISupportInitialize).EndInit()
sock.RemoteHost = "10.194.1.132"
sock.RemotePort = 3001
sock.Connect()
MessageBox.Show(sock.CtlState.ToString())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Related

How to properly close a WCF Netnamedpipebinding Channel?

I have a WCF Netnamedpipebinding from my application to an Office Addin. I have noticed that when the office app is busy doing something else that my application locks up when using a WCF method. I have added an example of my code. It appears that the code stops and waits with the channel.close method.
Is the solution to change channel.close to channel.BeginClose ?
What is the the state object I need to pass in to the BeginClose method?
Public Function RequestPersonStatus(ByVal id As String, ByVal email As String)
Using factory As New ChannelFactory(Of IToOffice)(New NetNamedPipeBinding(), New EndpointAddress("net.pipe://localhost/" + XXXXXX))
Dim OfficeChannel As IToOffice = factory.CreateChannel()
Try
OfficeChannel.RequestPersonStatus(id:=id, email:=email)
Catch ex As Exception
Return False
Finally
CloseChannel(CType(OfficeChannel, ICommunicationObject))
End Try
End Using
Return True
End Function
and the closeChannel
Private Sub CloseChannel(ByVal channel As ICommunicationObject)
Try
If channel.State = CommunicationState.Opened Then
Dim caller As New AsyncCallback(AddressOf callback)
channel.BeginClose(caller, New Object)
' channel.Close()
End If
Catch ex As Exception
Log(LogTypes.AllExceptions, "CloseChannel - Error closing the channel. ", ex.ToString)
Finally
channel.Abort()
End Try
End Sub
There seems to be a lot of discussion on what and when to clean up / Dispose / close down channels. I am just posting here what I am now doing and thus my answer to my question.
Private Sub CloseChannel(ByVal channel As ICommunicationObject)
Try
If channel.State <> CommunicationState.Closed AndAlso channel.State <> CommunicationState.Faulted Then
channel.BeginClose(Sub(asr)
Try
channel.EndClose(asr)
Catch
channel.Abort()
End Try
End Sub, Nothing)
Else
channel.Abort()
End If
Catch commEx As CommunicationException
channel.Abort()
Catch ex As Exception
channel.Abort()
Finally
End Try
End Sub
As far as I know, most of the cases like the timeout error/connection/communication error are caused by that the channel/client proxy is not properly closed. Putting the client proxy/Service Channel in a using block will eliminate the problem.
using (ServiceReference1.ServiceClient client=new ServiceClient())
{
var result = client.Test();
Console.WriteLine(result);
}
The Using statement is useful for automatically closed the service proxy/service communication channel after completing the invocation. Besides, Service client proxy is similar to the communication channel created by the ChannelFactory.
Feel free to let me know if there is anything I can help with.

How to check if the connection to a SFTP server is successful using WinSCP in VB.NET

I have sent a file by SFTP to another server using WinSCP in VB.NET.
I would like to see if the connection was successful or not.
I also need to know if the file already exists in the directory beforehand.
There are a couple of things you can do. You can create a session log that tells you (in a LOT of detail) what happened during your file transfer. You can also put a try-catch block around mySession.Open(mySessionOptions) to catch an error.
Finally, use mySession.FileExists(remotepath) to check to see if the file is already on the server.
Dim mySessionOptions As New SessionOptions
With mySessionOptions
.Protocol = Protocol.Sftp
.HostName = "999.999.999.999"
.UserName = "login"
.Password = "mypassword"
.SshHostKeyFingerprint = "ssh-dss 1024 99:87:99:4d:99:a3:99:b9:99:15:99:f2:99:87:88:b2"
End With
Using mySession As Session = New Session
' Will continuously report progress of synchronization
AddHandler mySession.FileTransferred, AddressOf FileTransferred
' Connect
mySession.SessionLogPath = "C:\Users\yourName\yourFolder\Sessionlog.log"
'Use Try-Catch to check for error in connection
Try
mySession.Open(mySessionOptions)
Catch ex As Exception
MessageBox.show(ex.Message)
mySession.Close()
Exit Sub
End Try
'Check to see if file exist already on server
If mySession.FileExists(remotePath) Then
MessageBox.Show("File Exists on Server")
mySession.Close()
Exit Sub
End If
mySession.PutFiles("C:\Users\yourName\yourFolder\yourfile.dat", remotePath)
mySession.Close()
End Using
Remember to check the log you created to see exactly what happened.

will everything automatically close in this code if there is an exception

three questions please
1) If there is an exception in the try below will the request stream automatically close as it is in a using
2)do I even need the requestStream.Close() and requestStream.Dispose() as it is in a using?
3) do I need to close the System.Net.FtpWebRequest?
Try
Dim rqst As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://1.com/text.txt"), System.Net.FtpWebRequest)
rqst.Credentials = New System.Net.NetworkCredential("useb", "pass")
rqst.Method = System.Net.WebRequestMethods.Ftp.UploadFile
'Throw New ApplicationException("Exception Occured")
Dim fle() As Byte = System.IO.File.ReadAllBytes("C:\test.txt")
Using requestStream As Stream = rqst.GetRequestStream()
requestStream.Write(fle, 0, fle.Length)
requestStream.Close() 'do I need this?
requestStream.Dispose() 'do I need this ?
End Using
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
No you dont need if you are using using. As using itself is used to dispose of. Also the reason for the "using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens.
Dispose method is called immediately when control flow exits the using block.
Yes. If the exception occurs while executing code inside the using statement, the stream will be disposed before it goes to the Catch block.

Error not being caught (AsyncCallback)

Hi there i have a piece of code which connects using sockets to a server
Try
'Connect To The Server
Dim socketclient As New TcpClient
Dim success
Dim result
result = socketclient.BeginConnect(ip, port, socket.EndConnect, socketclient)
success = result.AsyncWaitHandle.WaitOne(5000, True)
If socketclient.Connected = False Then
Throw New Exception("Server is offline")
End If
catch ex as exception
End Try
As you can see. if a server is offline, my try-catch setup doesn't catch the error "host is unknown" i believe this is because the error occurs during the async call. IF this is true, how does one catch an error in an async call?
You should end the async operation.
Your wait is totally unnecessary, if you just want to block waiting for the connection just call EndConnect over the socket ;)
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.endconnect.aspx

Creating instances of forms inside a thread

i am trying to create a new instance of a form if its not allready been created the only problem is is that the instance creation is inside a thread.
Private Sub doRead(ByVal ar As System.IAsyncResult)
Dim totalRead As Integer
Try
totalRead = client.GetStream.EndRead(ar) 'Ends the reading and returns the number of bytes read.
Catch ex As Exception
'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
'to this client and remove it from the list of connected clients.
End Try
If totalRead > 0 Then
'the readBuffer array will contain everything read from the client.
Dim receivedString As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, totalRead)
messageReceived(receivedString)
End If
Try
client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing) 'Begin the reading again.
Catch ex As Exception
'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
'to this client and remove it from the list of connected clients.
MessageBox.Show(ex.ToString)
End Try
End Sub
The problem lies when the form is created on the line .showDialog() it stops here untill the application is closed. ive tryed using .show() but then the new "Convo window just hangs"
Private Sub messageReceived(ByVal message As String)
Dim data() As String = message.Split("|"c)
Select Case data(0)
Case "MESSAGE"
Dim chatDialog As New RichTextBox
Try
If conversations.ContainsKey(data(1)) Then
Dim convoWindow As ChatWindow
convoWindow = New ChatWindow
convoWindow = conversations.Item(data(1))
chatDialog = convoWindow.RichTextBox1
Else
Try
Dim convoWindow As New ChatWindow()
conversations.Add(data(1), convoWindow)
convoWindow = conversations.Item(data(1))
convoWindow.ShowDialog()
chatDialog = convoWindow.RichTextBox1
AppendTextChatWindows(data(2), chatDialog)
Thanks
Houlahan