will everything automatically close in this code if there is an exception - vb.net

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.

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.

VB .Net - TransactionScope aborts when Using is outside Try/Catch

The following method is called from within a loop:
Public Sub ExampleAbort()
Using trans As New TransactionScope(TransactionScopeOption.Required, New TransactionOptions With {.IsolationLevel = IsolationLevel.ReadUncommitted, .Timeout = New TimeSpan(0, 10, 0)})
Try
DoSomeTransationalStuffHere()
trans.Complete()
Catch ex As Exception
ShowError(ex.Message)
Throw
End Try
End Using
End Sub
This will lead to the DTS aborting the transaction after the first item. If I place the 'Using' statement within the Try/Catch block, everything works. Can someone please explain this behavior? I was under the assumption that Using-blocks ALWAYS Dispose'd no matter how you return from a method.
Best regards,
Goran

My url checker function is hanging application in vb.net

Here is vb.net 2008 code is:
Public Function CheckURL(ByVal URL As String) As Boolean
Try
Dim Response As Net.WebResponse = Nothing
Dim WebReq As Net.HttpWebRequest = Net.HttpWebRequest.Create(URL)
Response = WebReq.GetResponse
Response.Close()
Return True
Catch ex As Exception
End Try
End Function
when a url is processing in checking it hangs my application for a while. Is this possible it checks smoothly all url list without hanging my application..
Is there any other fastest way to check urls?
Note: I have about 800 urls in file to check all links a valid by website responce or not.
If an exception occurs, the WebResponse object isn't properly disposed of. This can lead to your app running out of connections. Something like this will work better:
Try
Dim WebReq As Net.HttpWebRequest = Net.HttpWebRequest.Create(URL)
Using Response = WebReq.GetResponse()
Return True
End Using
Catch ex as WebException
Return False
End Try
This using the Using keyword ensures that the response is closed and finalized whenever that block exits.
If it's the server itself that's taking awhile to respond, look into the BeginGetResponse method on the HttpWebRequest. Check MSDN for a sample on how to use it. But be warned, that way also lies madness if you are not careful.
The answer is two fold:
Most of the waiting time is due to downloading content you don't need. If you request to only return the header, you will receive substantially less data, which will make your process faster.
As Matt identified, you aren't disposing of your connections, which may slow your process.
Expanding on Matt's answer, do the following:
Try
Dim WebReq As Net.HttpWebRequest = Net.HttpWebRequest.Create(URL)
WebReq.Method = "HEAD" 'This is the important line.
Using Response = WebReq.GetResponse()
Return True
End Using
Catch ex as WebException
Return False
End Try
GetResponse delivers you the whole content to your request. If this is what you want, there's not many room to speed up the request on the client side, since it mostly depends on the URLs server how fast to reply and how much data will be send over. If you just want to check if the URL is valid (or responding at all), it might be better to just ping it.
Keep in mind GetResponse isn't disposed when it runs into an error, so use the code posted by Matt to avoid this.
For your other problem, hanging application, you might avoid this be running this code as a thread.
This works basically like this (from here):
rem at the top of the code
Imports System.Threading
...
rem your event handler, p.e. button click or whatever
trd = New Thread(AddressOf ThreadTask)
trd.IsBackground = True
trd.Start()
rem your code
Private Sub ThreadTask()
dim i as long
Do
i += 1
Thread.Sleep(100)
Loop
End Sub

VB.NET: question about "using" block

Consider the code:
On Error Goto ErrorHandler
Using sr As StreamReader = New StreamReader(OpenFile)
str = sr.ReadToEnd
sr.Close()
End Using
Exit Sub
ErrorHandler:
If there is an error inside the Using block how do you clean up the sr object?
The sr object is not in scope in ErrHandler so sr.Close() cannot be called. Does the Using block cleanup any resources automatically even if there is an error?
As codeka says, you don't need to call Close on sr. It'll called automatically, and that includes if there is an error. Using the using statement gives you the same functionality as try ... finally ... end try.
And as you see in the answers to your other question, you shouldn't be using On Error etc just do:
Try
Using sr as StreamReader ...
...
End Using
Catch ex as SomeException
...
End Try
Yes, the using block will automatically call IDisposable.Dispose (which, for a StreamReader is the same as calling Close) so there's nothing you need to do (that's the whole point of using blocks!)
This code:
Using sr As StreamReader = New StreamReader(OpenFile)
str = sr.ReadToEnd
sr.Close()
End Using
Is really equivalent to this:
Dim sr As StreamReader = Nothing
Try
sr = New StreamReader(OpenFile)
sr.Close() ' notice: unnecessary '
Finally
sr.Close()
End Try
Keep in mind that code within a Finally block will always execute before the method returns (if it throws an exception of its own, well, then you're in for a world of hurt). So the sr.Close line you have within your Using block is superfluous (notice it is unnecessary in the equivalent code using Try/Finally since sr.Close will be called in the Finally no matter what -- exception thrown or not).

how do I clean up after a StreamWriter during an exception?

I'm trying to clean-up after an exception, and I'm not sure how to handle a StreamWriter.
Dim sw As StreamWriter
Try
''// stuff happens
somethingBad1() ''//Sometimes throws an exception
sw = New StreamWriter(File.Open("c:\tmp.txt", FileMode.Create))
''// stuff happens
somethingBad2() ''//Also sometimes throws an exception
sw.Write("Hello World")
sw.Flush() ''//Flush buffer
sw.Close() ''//Close Stream
Catch ex As Exception
sw = Nothing
Finally
sw = Nothing
end try
If somethingBad1 throws an exception, I don't need to do anything to sw; however, if somathignBad2 happens, sw has already been created and I need to close it. But How do I know if sw has been created or not?
''//stuff happens but you don't care because you didn't instantiate
''// StreamWriter yet
somethingBad1() ''//Sometimes throws an exception
Using sw As New StreamWriter("test.dat")
''// stuff happens
somethingBad2() ''//Also sometimes throws an exception
''//as you are in a using statement the sw.Dispose method would be called
''//which would free the file handle properly
sw.Write("Hello World")
End Using
Only do the try after assigning the sw variable (in your sample). Or use a using statement.
But as a general rule, you should close the StreamWriter (if not using it with using), and not just assign Nothing to it. Also, catching all exceptions should be avoided, only handle exception which you know how to handle gracefully.
Darin has it right, but just one stylistici point to expand on Pavel Minaev's comment: unlike VB6, in VB.Net setting your sw reference to Nothing has no real effect. You really don't need to do it. What you could do is have code like this in your finally block:
Finally
''# test
If sw IsNot Nothing Then sw.Dispose()
End
And that would take care of all the required cleanup (including what you've show of the catch block). You wouldn't even need to close the stream in your main code. But Using blocks are normally the better way to handle this.