Ive written a service application that listens to a port for any communication that may come through, our lab will run a certain test which will send serial data down every couple hours or so. the service is runs picks up the data fine for a few hours and then mysteriously stops. the system eventlog says the service terminated unexpectedly. and in the application event log it has a more descriptive .NET error,
Application: BondTestService.exe Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ObjectDisposedException at
System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean
ByRef) at
System.StubHelpers.StubHelpers.SafeHandleAddRef(System.Runtime.InteropServices.SafeHandle,
Boolean ByRef) at
Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(Microsoft.Win32.SafeHandles.SafeFileHandle,
System.Threading.NativeOverlapped*, Int32 ByRef, Boolean) at
System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent() at
System.Threading.ThreadHelper.ThreadStart_Context(System.Object) at
System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object) at
System.Threading.ThreadHelper.ThreadStart()
i was reading how services behave and how serial ports behave, so correct me if im wrong if the there is a 2 hour gap or so inbetween tests, the service will assume that its not running and stop itself?
I also read after reading the buffer from the serial port i append to a string builder object like below and do what i need to the string, then what happens to the serial port does it just stay open waiting for next value or do i have to close it and reopen it in order to refresh it?
Not sure how to handle this as it needs to be open waiting for the lab tester to send his data at any given time.
Imports System
Imports System.Data.SqlClient
Imports System.IO.Ports
Imports System.Net.Mime
Imports Microsoft.Win32
Imports System.IO
Imports System.Text.RegularExpressions
Imports BondTestService.PI
Imports PCA.Core.Configuration
Public Class Bond
Dim WithEvents serialPort As New IO.Ports.SerialPort
Public Delegate Sub myDelegate()
Public RawString As New System.Text.StringBuilder
Public value As String
Public BondTest As Integer = 10
#Region "Commport Traffic and Configuration Validations"
Public Sub StartListening()
If serialPort.IsOpen Then
serialPort.Close()
ErrorLog2(Now.ToString & "Port Closed because StartListening method started over")
End If
Try
With serialPort
.PortName = Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("commport")
.BaudRate = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("baudrate"))
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("parity") = 0 Then
.Parity = Parity.None
End If
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("stopbits") = 1 Then
.StopBits = StopBits.One
End If
.DataBits = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("bytesize"))
.Handshake = Handshake.None
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("RtsControl") = 1 Then
.RtsEnable = True
Else
.RtsEnable = False
End If
End With
serialPort.Open()
'debug
'ErrorLog2("Listening to COM 19, SerialPort has been Opened")
Catch ex As Exception
ErrorLog2(Now.ToString & ex.tostring)
End Try
End Sub
Public Function Filelocator() As String
' Dim filePath As String = IO.Path.Combine(Application.StartupPath, "bondtest.bat")
Dim filePath As String = IO.Path.Combine("C:\Program Files (x86)\PIPC\Interfaces\Lab", "BondTest.bat")
'Dim reader As New System.IO.StreamReader(filePath)
Dim LineNumber = 4
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To LineNumber - 1
If file.ReadLine() Is Nothing Then
ErrorLog2("LineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
ErrorLog2("LineNumber")
End If
Return line
End Using
End Function
Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Try
If GetBondInterfaceStatus = 1 Then
UPdateVariable()
Else
exit Sub
End If
Catch ex As Exception
Errorlog2(Ex.Tostring)
End Try
End Sub
#End Region
#Region "String Handling"
Public Sub UPdateVariable()
With RawString
.Append(serialPort.ReadLine())
End With
try
ErrorLog2(now.ToString & RawString.ToString)
InsertTestDataDEBUG(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()), RawString.tostring)
InsertTestData(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()))
RawString.Clear()
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Public Function StringParser(RawString As String)As Double ()
Dim Moisture = RawString
Dim pattern As String = "[0-9],"
Dim regex As New Regex(pattern)
Dim Counter As Integer = 0
Dim dblValues(1) As Double
Dim values As String() = Moisture.Split(New Char() {" "c})
for i = 0 to values.Count - 1
if regex.IsMatch(values(i)) Then
dblValues(Counter) = CDbl(values(i).Substring(0,1))
Counter = Counter + 1
Elseif values(i) = "" Then
continue for
else
if Double.TryParse(values(i), dblValues(Counter)) Then
Counter = Counter + 1
End If
End If
Next
Return dblValues
End Function
#End Region
#Region "SQL Statements"
Private Sub InsertTestData(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
' Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.PaperTestValues(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime)"
Try
conn.ExecuteNonQuery(InsertQuery)
IncrementTestPosition
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub InsertTestDataDEBUG(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double, rawString As String)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#RawString") = rawString
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.InterfaceTesting(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp, RawValue) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime, #RawString)"
Try
conn.ExecuteNonQuery(InsertQuery)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub IncrementTestPosition()
Dim tempPosition As Integer = GetBondPosition()
Dim FrontOriginalMax = 5
Dim CenterOriginalMax = 15
Dim BackOriginalMax = 25
Dim FrontRetestOrWinderMax = 10
Dim CenterRetestOrWinderMax = 20
Dim BackRetestOrWinderMax = 30
If tempPosition = FrontOriginalMax Then
tempPosition = 11
else if tempPosition = CenterOriginalMax Then
tempPosition = 21
else if tempPosition = BackOriginalMax Then
tempPosition = 1
Else If tempPosition = FrontRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = CenterRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = BackRetestOrWinderMax then
tempPosition = 1
else
tempPosition = tempPosition + 1
End If
SetBondPosition(tempPosition.tostring)
End Sub
#End Region
#Region "Get PiValues"
Private Function GetRecordID() As Int64
Dim RecordID As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
RecordID = piserver.GetCurrentValue("PAPERLAB:PaperLabReelSelected")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return RecordID
End Function
Private Function GetBondPosition() As Int64
Dim BondPos As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
BondPos = CInt(piserver.GetCurrentValue("PAPERLAB:SBOND.POS"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return BondPos
End Function
Private Sub SetBondPosition(pos As String)
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
piserver.WriteValue("PAPERLAB:SBOND.POS", pos)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Function BondTestType() As String
Dim TestType As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
TestType = piserver.GetCurrentValue("M1:BOND.TYPE")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return TestType
End Function
Private Function BondReelLoc() As String
Dim ReelLoc As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
ReelLoc = piserver.GetCurrentValue("M1:BOND.ReelLoc")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return ReelLoc
End Function
Private Function GetBondInterfaceStatus() As Integer
Dim Status As Integer = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
Status = CInt(piserver.GetCurrentValue("PAPERLAB:BOND_INTERFACE.S"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return Status
End Function
#End Region
#Region "Debug"
Private Sub ErrorLog(RecordID As Int32, BondTest As Integer, ReelLoc As String, TestType As String, StartingTestPos As Integer, dataArray() As Double)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
' For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
' Next
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
'For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
'Next
End Using
End If
End Sub
Private Sub ErrorLog2(dataArray as string)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
' Dim TestPos = StartingTestPos
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
End If
End Sub
#End Region
This is a screenshot of the errors:
Thanks in advance
Normally, after opening the serial port in .NET it stays opened for arbitrary time. I've written several .NET applications were serial ports are used for months or years without app or computer restart and they work well.
According to the exception info you posted it looks like that serial port has been disposed. There are several possible reasons.
Using bad driver or HW, that disconnects your serial port. I've been using many USB-to-RS232 converters and some of them had bad drivers so sometimes ports were randomly disconnected and ObjectDisposedException was thrown. In earlier Windows editions (XP) the OS even 'blue-screened'. Here is more info about such situation where ObjectDisposedException is thrown.
This is a known problem with SerialPort. Device removal causes an uncatchable exception in a background thread it uses (WaitForCommEvent). The only solutions are to not use SerialPort or create a .config file that puts unhandled exception trapping mode back to .NET 1.1 behavior.
The USB cable of your RS232 converter is manually disconnected. If you do this, most drivers normally disconnect all handles to your serial port and .NET throws ObjectDisposedException.
Also check your power management settings on your USB port if USB-to-RS232 converter is used. Try to uncheck this option on USB device to which converter is connected.
SW bug in your code.
It's always advisable (especially if converter used) to try more types of converters just to be sure there is no problem in HW device/driver.
Update: So as Timmy was saying the connection was getting disposed by garbage collection. so i declared the object as a shared variable in the class
Shared Dim WithEvents serialPort as IO.Ports.SerialPort
and in the OnStart method i initiated it as a new Serial port and rocked on. has not throw any errors since garbage collection wont disposed of it. Hope this helps somebody having a similar issue.
How can I do a check that first download something and only after that it starts up the program.exe?
I already tried to do something like this but it excutes the file when the download is not finished and it throws some errors.
my Code:
Dim client As WebClient = New WebClient
Dim SourcePath As String = "C:\ProgramData\KDetector\UserAssistView.exe"
Dim SaveDirectory As String = "C:\ProgramData\KDetector"
Dim FileName As String = System.IO.Path.GetFileName(SourcePath)
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, FileName)
If System.IO.File.Exists(SavePath) Then
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
Else
client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"), "C:\ProgramData\KDetector\")
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
End If
You are calling the asynchronous DownloadFile method. Asynchronous method will not block the calling thread.
In order to avoid the problem, your code must be like this:
Dim downloadLink As String = "http://www.nirsoft.net/utils/userassistview.zip"
Dim saveFilePath As String = "C:\ProgramData\KDetector\userassistvkew.zip"
Dim fileName As String = Path.GetFileNameWithoutExtension(saveFilePath)
Dim client As WebClient = New WebClient
Try
CheckExsist(saveFilePath, fileName)
'Before was client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"))
client.DownloadFile(downloadLink, saveFilePath)
MsgBox("Download file completed. File saved in: " & saveFilePath)
'Zip extraction stuff
Catch ex As Exception
MsgBox(ex.Message)
End Try
This is the CheckExsist sub:
Private Sub CheckExsist(ByRef sourcePath As String, ByVal fileName As String, Optional ByVal counter As Integer = 1)
If System.IO.File.Exists(sourcePath) Then
sourcePath = sourcePath.Replace(Path.GetFileName(sourcePath), "") & fileName & "(" & counter & ")" & Path.GetExtension(sourcePath)
counter += 1
CheckExsist(sourcePath, fileName, counter)
End If
End Sub
I manage to download the software (from the official website) and save it as a .zip. Code the last few rows to programmatically extract the .zip, if you ecounter any problem or bug feel free to ask with another question. Anyways there are alot of post on SO regarding zip extraction on vb.net
Recently installed new version of Neo4j on Windows 7 Prof PC. Able to create nodes using API batch inserts. Cypher queries from web interface work but now fail from VB.NET code at the line after the comment 'retrieve results of query, which will be in JSon. This ran okay on the previous Neo4j version (2.2.x)
Public Shared Function DBQuery(URI As String, PostString As String) As DataView
'runs query and returns JSon results as a dataview
'Uses POST method to access Neo4j Server API
Dim S As String = ""
Dim HttpWReq As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URI)
HttpWReq.Method = "POST"
HttpWReq.ContentType = "application/json"
HttpWReq.Accept = "application/json"
Dim B1() As Byte = System.Text.Encoding.Unicode.GetBytes(PostString, 0, Len(PostString))
'POST query
'http://blog.micic.ch/net/using-neo4j-graph-db-with-c-net
HttpWReq.Connection = "Open"
HttpWReq.ContentLength = B1.Length
Dim newStream As IO.Stream = HttpWReq.GetRequestStream()
'this method closes stream before calling getResponse
Using newStream
newStream.Write(B1, 0, B1.Length)
End Using
'retrieve results of query, which will be in JSon
Dim HttpWResp As System.Net.HttpWebResponse = CType(HttpWReq.GetResponse(), System.Net.HttpWebResponse)
HttpWReq.KeepAlive = False
HttpWReq.Timeout = 15000000
Dim E As System.Text.Encoding = System.Text.Encoding.GetEncoding(HttpWResp.CharacterSet)
Dim SR As IO.StreamReader = New IO.StreamReader(HttpWResp.GetResponseStream, encoding:=E)
S = SR.ReadToEnd 'JSon result
Return JSonToDV(S)
End Function
Documentation for v2.3.0 indicates the need for a different conf file setting, but this is not working. The documentation is at http://neo4j.com/docs/2.3.0-M01/server-configuration.html . The neo4j-server.properties file originally had no entry for org.neo4j.server.database.location=data/graph.db. Adding the suggested line (org.neo4j.server.database.location="C:/Data/Neo4j/UMLS/graph.db") and then the database failed to start. Would appreciate suggested solutions.
The problem was not with Neo4j 2.3.0 but with the VB.NET code. The corrected code, which works is:
Public Shared Function DBQuery(URI As String, PostString As String, method As EnumLib.WebServiceMethod) As DataView
'Used for individual API calls; see BulkUpload for other method
'Uses POST method to access Neo4j Server API
Dim ID As Long = 0
Dim HttpWReq As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URI)
Select Case method
Case EnumLib.WebServiceMethod.POST
HttpWReq.Method = "POST"
Case EnumLib.WebServiceMethod.GET
HttpWReq.Method = "GET"
End Select
HttpWReq.ContentType = "application/json"
HttpWReq.Accept = "application/json"
Dim B1() As Byte = System.Text.Encoding.UTF8.GetBytes(PostString, 0, Len(PostString))
'http://blog.micic.ch/net/using-neo4j-graph-db-with-c-net
HttpWReq.Connection = "Open"
Dim S As String = ""
Try
HttpWReq.ContentLength = B1.Length
Dim newStream As IO.Stream = HttpWReq.GetRequestStream()
'this method closes stream before calling getResponse
Using newStream
newStream.Write(B1, 0, B1.Length)
End Using
Dim HttpWResp As System.Net.HttpWebResponse = CType(HttpWReq.GetResponse(), System.Net.HttpWebResponse)
Dim E As System.Text.Encoding = System.Text.Encoding.GetEncoding(HttpWResp.CharacterSet)
Dim SR As IO.StreamReader = New IO.StreamReader(HttpWResp.GetResponseStream, encoding:=E)
S = SR.ReadToEnd
Catch ex As System.Net.WebException
MsgBox("Message: " & vbLf & ex.Message)
Dim RS As IO.StreamReader = New IO.StreamReader(ex.Response.GetResponseStream)
Dim SS As String = RS.ReadToEnd
PostReturnString = "WebException Error: " & ex.Message & vbLf & vbLf & ex.Status & vbLf & vbLf & SS
' MsgBox("Status: " & vbLf & ex.Status & vbLf & vbLf & SS)
End Try
Return JSonToDV(S)
End Function
What I'm trying to accomplish I have a textbox control and a button control on a form. When clicked whatever is entered into the textbox control, I want to send that data to a console application, which in turn create a text file. I have it mostly working but I can't get the data sent from the web application. How do I accomplish this? Here is what I have so far.
Here is my sub to send to the console application:
Public Sub send_to_console()
Dim file As String = "C:\inetpub\wwwroot\TestConsoleApp\TestConsoleApp\bin\Debug\TestConsoleApp.exe"
Dim info As ProcessStartInfo = New ProcessStartInfo(file, TextBox1.Text)
Dim p As Process = Process.Start(info)
End Sub
Console App Code:
ublic Sub Main(ByVal args As String)
Dim w As StreamWriter
Dim filepath As String = "C:\xml_files\testFile.txt"
Dim new_string As String
new_string = "This has been completed on " & Date.Now
If args = "" Then
new_string = "No data entered on: " & Date.Now
Else
new_string = args & " " & Date.Now
End If
If System.IO.File.Exists(filepath) Then
File.Delete(filepath)
End If
w = File.CreateText(filepath)
w.WriteLine(new_string)
w.Flush()
w.Close()
End Sub
Currently i'm getting an error: no accessible Main
'#######################EDITS###########
Dim file As String = "C:\inetpub\wwwroot\TestConsoleApp\TestConsoleApp\bin\Debug\TestConsoleApp.exe"
Dim info As ProcessStartInfo = New ProcessStartInfo(file, TextBox1.Text)
info.UseShellExecute = False
Dim p As Process = Process.Start(info)
main takes an array of string not a string.
so
Public Sub Main(ByVal args As String())
.....
If args.length < 1 Then
new_string = "No data entered on: " & Date.Now
Else
new_string = args(0) & " " & Date.Now
End If
.....
End Sub
In order to prevent windows from splitting your arguments concatenate a quote character before and after
Dim info As ProcessStartInfo = New ProcessStartInfo(file, """" & TextBox1.Text & """")
Four double quote characters represent a string literal containing a single double quote.
I am trying to make a voice recognition thing with google's voice api.
I modified UPLOADFILEEX function that can be found on codeproject...
The file I wish to delete is C:\record.flac
Here is the function below
Public Shared Function UploadFile(ByVal uploadfilename As String, ByVal url As String, ByVal fileFormName As String, ByVal contenttype As String, ByVal querystring As System.Collections.Specialized.NameValueCollection, ByVal cookies As CookieContainer) As String
If (fileFormName Is Nothing) OrElse (fileFormName.Length = 0) Then
fileFormName = "file"
End If
If (contenttype Is Nothing) OrElse (contenttype.Length = 0) Then
contenttype = "application/octet-stream"
End If
Dim postdata As String
postdata = "?"
If Not (querystring Is Nothing) Then
For Each key As String In querystring.Keys
postdata += key + "=" + querystring.Get(key) + "&"
Next
End If
Dim uri As Uri = New Uri(url + postdata)
Dim boundary As String = "----------" + DateTime.Now.Ticks.ToString("x")
Dim webrequest As HttpWebRequest = CType(Net.WebRequest.Create(uri), HttpWebRequest)
webrequest.CookieContainer = cookies
webrequest.ContentType = "audio/x-flac; rate=16000"
webrequest.Method = "POST"
Dim sb As StringBuilder = New StringBuilder
sb.Append("--")
sb.Append(boundary)
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("Content-Disposition: form-data; name=""")
sb.Append(fileFormName)
sb.Append("""; filename=""")
sb.Append(IO.Path.GetFileName(uploadfilename))
sb.Append("""")
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("Content-Type: ")
sb.Append(contenttype)
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
Dim postHeader As String = sb.ToString
Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(postHeader)
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "--" + boundary + "" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
Dim fileStreama As FileStream = New FileStream(uploadfilename, FileMode.Open, FileAccess.Read)
Dim length As Long = postHeaderBytes.Length + fileStreama.Length + boundaryBytes.Length
webrequest.ContentLength = length
Dim requestStream As Stream = webrequest.GetRequestStream
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
Dim sendBuffer(Math.Min(4096, fileStreama.Length)) As Byte
Dim bytesRead As Integer = 0
Do
bytesRead = fileStreama.Read(sendBuffer, 0, sendBuffer.Length)
If bytesRead = 0 Then Exit Do
requestStream.Write(sendBuffer, 0, bytesRead)
Loop
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim responce As WebResponse = webrequest.GetResponse
Dim s As Stream = responce.GetResponseStream
Dim sr As StreamReader = New StreamReader(s)
Return sr.ReadToEnd
sr.Dispose()
s.Dispose()
fileStreama.Dispose()
requestStream.Dispose()
webrequest.Abort()
responce.Close()
End Function
The function WORKS (Thankgod) but whenever I want to clear up (i.e. delete the audio file that is located in the c:) it just hangs and nothing happens...
Below is my code that executes on the formclosing event....
Private Sub Form1_Close(sender As System.Object, e As System.EventArgs) Handles MyBase.FormClosing
Dim di As New IO.DirectoryInfo("c:\")
Dim diar1 As IO.FileInfo() = di.GetFiles()
Dim dra As IO.FileInfo
For Each dra In diar1
If dra.Name.Contains("record.") Then
dra.Delete()
End If
Next
End Sub
As you probably may be able to see from the function I HAVE TRIED TO REMOVE ALL THE STREAMS AND CLOSE THEM SO THE FILE IS NOT BEING ACCESSED
BUT it still hangs and when I try manually delete it... it tells me it is being used by another process (which is my program) - (I use ffmpeg to convert the .wav to .flac file but that does not cause any problems)....
What am I doing wrong...
Have I missed the closing of some stream or something.
By the way the uploadfilename string is c:\record.flac (just for your information - I dont think it will help)
Your function is calling Return BEFORE disposing of the file stream. This means that your Dispose call is never fired.. and the stream holds onto a file reference.
I Agree with Boo that the return before the dispose probably is the cause. So the solution would be to store the result of sr.ReadToEnd in a variable, close the streams and then return the var.
But a better solution would be to use the Using statement (http://msdn.microsoft.com/en-us/library/htd05whh.aspx) on every class that you have to call .Dispose() on (aka classes that implement IDisposable).
This gives clearer code because you can easily see what resources are in use where in your code. Also less buggy code as .NET ensures that everything is disposed once you leave the scope of the using block.