Save audio and video file in SQL Server database - asp.net

How can I save and retrieve audio and video files in and from a SQL Server database?

The naive approach is to use a BLOB column and read the entire content into a byte[], then write the byte[] back to the client. The problem is that it consumes huge amounts of memory in your ASP.Net process.
A much better approach is to use streaming semantics, see these two articles:
Download and Upload images from SQL Server via ASP.Net MVC
FILESTREAM MVC: Download and Upload images from SQL Server
The articles refer to images, but you can use the code as-is to store any other form of media, including audio and video. Although the code is for ASP.Net MVC, the concepts use to stream large files into and from SQL Server can be used just as well from ASP.Net forms.
I'm not making a case that you should or should not use SQL Server as the storage for media. That is an entirely different discussion.

Refer to How to Store audio in Sql and retrieve for play, you come to know how to store the audio files in the database. Follow the same way for videos also.

Public Sub InsertAudioDataInTable(TableName, TableMapingName, TextName,_
LoopStart, LoopEnd, Panel, PathOnDisk)
Dim SndSourceStream As Stream = New FileStream(PathOnDisk, FileMode.Open,
FileAccess.Read)
Dim BinarySndReader As New BinaryReader(SndSourceStream)
Dim bytes As Byte() = BinarySndReader.ReadBytes(SndSourceStream.Length)
strImage = "#Aud" ' Aud mean a feild Audio in database
'''''''''''''''''''''''''''''''''''''''''''''''' For SQL String
Dim b = 0
Dim dataContaner(LoopEnd + 2 - LoopStart) As String
For a = LoopStart To LoopEnd
dataContaner(b) = Panel.Controls(TextName & a).Text
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 = bytes
myCmd.ExecuteNonQuery()
''''''''
End Sub
Private Sub btSclass_Click(sender As Object, e As EventArgs) Handles btSclass.Click
If btSclass.Text = "Start Class" Then
If A7.Text <> "" Then
GlobalVariableDefault.startTime = DateTime.Now
A2.Text = GlobalVariableDefault.startTime.ToString("hh\:mm\:ss")
GlobalVariableDefault.StID = A7.Text
Me.Hide()
FTodayLesson.Show()
A2.Text = L.Text
btSclass.Text = "End Class"
btSclass.BackColor = Color.Red
If recording = False Then
mciSendString("open new Type waveaudio Alias recsound", "", 0, 0)
mciSendString("record recsound", "", 0, 0)
recording = True
End If
Else
MyMessage("Select a student name from list")
End If
ElseIf btSclass.Text = "End Class" Then
mciSendString("save recsound " & Filez, "", 0, 0)
mciSendString("close recsound ", "", 0, 0)
recording = False
FunConnection(DatabaseName_Audio)
InsertAudioDataInTable("RecAudio", "InsertAdio", "A", 1, 8, PShortInfo, "D:\aa\Test.wav")
btSclass.BackColor = Color.WhiteSmoke
btSclass.Text = "Start Class"
MyMessage("Data Save")
FunConnection(DatabaseName_QurqnServer)
End If
End Sub

'''''data base used in above code

Related

asynchronous process structuring in .net

I'm working on a process that takes an excel file, does some review of the data and adds it to a datatable to later save it in the DB. In the review that must be done, in some cases the intervention of the user is necessary, for that I need to interrupt the process, open a modal window, that the user intervenes and then continue the process, in that step is where I am stuck, no I make progress on this point. I put some of the code in case it serves as a guide, thanks in advance.
Dim oSqlBulk As SqlBulkCopy
Dim myExcelConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ConfigurationManager.AppSettings("DirArch").ToString() & "\" & HttpContext.Current.Session("nombrearchivo").ToString & ";Extended Properties=Excel 12.0;")
myExcelConn.Open()
Dim objOleDB As New OleDbDataAdapter("SELECT * FROM [" & nombreHoja & "$]", myExcelConn)
'data is extracted from excel
objOleDB.TableMappings.Add("Table", "DTDatos")
objOleDB.Fill(dt_datos)
Dim tmpEncaArchivo As New Encabezado_Archivo
tmpEncaArchivo.IdSubida = obtieneIdsubida()
tmpEncaArchivo.IdArchivo = "1"
tmpEncaArchivo.Usuario = " "
tmpEncaArchivo.Fecha = Fecha
tmpEncaArchivo.UbicacionArchivo = " "
tmpEncaArchivo.IdBanco = valorddlbancos '
tmpEncaArchivo.CodCuenta = valorddlcuentas '
tmpEncaArchivo.lstDetalleArchivo = New List(Of Detalle_Archivo)
' the new datatable is filled with the processed data
For i = 0 To dt_datos.Rows.Count - 1
Dim tmpDetalleArchivo As New Detalle_Archivo
tmpDetalleArchivo.IdSubida = tmpEncaArchivo.IdSubida
tmpDetalleArchivo.IdArchivo = tmpEncaArchivo.IdArchivo
tmpDetalleArchivo.Linea = i + 1
tmpDetalleArchivo.Documento = IIf(IsDBNull(dt_datos.Rows(i)("Código de Autorización")), " ", dt_datos.Rows(i)("Código de Autorización"))
tmpDetalleArchivo.Monto = CDec(Replace(dt_datos.Rows(i)("Monto"), ".", ","))
tmpDetalleArchivo.Estado = "N"
tmpDetalleArchivo.Moneda = IIf(InStr(IIf(IsDBNull(dt_datos.Rows(i)("Moneda")), " ", dt_datos.Rows(i)("Moneda")), "Colón"), "CL", "DL")
If IsDBNull(dt_datos.Rows(i)("Estado")) Then
tmpDetalleArchivo.Datos = " "
Else
tmpDetalleArchivo.Datos = "S"
End If
tmpDetalleArchivo.Fecha = Fecha
tmpDetalleArchivo.Sobrante = 0
'Depending on the result of this function, the process must be stopped
If consultaRegDuplicado(tmpDetalleArchivo.IdSubida, tmpDetalleArchivo.IdArchivo, tmpDetalleArchivo.Fecha, tmpDetalleArchivo.Moneda,
tmpDetalleArchivo.Monto, tmpDetalleArchivo.Documento, valorddlcuentas, valorddlbancos) Then
'Here the code should be executed to open the modal for user intervention
tmpEncaArchivo.lstDetalleArchivo.Add(tmpDetalleArchivo)
End If
Next

How Read .text file line by line and the stored in database in sql server

I have a module which upload report and then stored in database in sql server. Now I have come up with this code to read .txt file line by line.
Protected Sub ibtnTxtUpload_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim jsbldr As New StringBuilder
Try
If FileUpload1.HasFile Then
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
If Extension = ".txt" Then
Dim Request_Val As String = ""
Dim sFileName As String = FileUpload1.FileName
'Read Line by Line
Using sRead As New StreamReader(FileUpload1.PostedFile.FileName)
sFileName = sRead.ReadToEnd
End Using
Dim sFileLines() As String = sFileName.Split(vbCrLf)
'Trim the line
Dim dt As New DataTable("XmlData")
dt.Columns.Add("Item", GetType(String))
dt.Columns.Add("Description", GetType(String))
dt.Columns.Add("Rev", GetType(String))
dt.Columns.Add("Locator", GetType(String))
dt.Columns.Add("UOM", GetType(String))
dt.Columns.Add("Quantity", GetType(Double))
Dim writer As New StringWriter
Dim sline As String
Dim i As Integer = 0
Dim lStart As Boolean = False
For Each sline In sFileLines
If sline.TrimStart.TrimEnd <> "" Then
If lStart = True Then
If sline.Substring(0, 10).TrimStart.TrimEnd <> "-------" Then
Dim newRow As DataRow = dt.NewRow
newRow("Item") = sline.Substring(0, 32).TrimStart.TrimEnd
newRow("Description") = sline.Substring(33, 53).TrimStart.TrimEnd
newRow("Rev") = sline.Substring(86, 3).TrimStart.TrimEnd
newRow("Locator") = sline.Substring(89, 26).TrimStart.TrimEnd
newRow("UOM") = sline.Substring(115, 3).TrimStart.TrimEnd
newRow("Quantity") = sline.Substring(124, 7).TrimStart.TrimEnd
dt.Rows.Add(newRow)
End If
End If
If sline.Substring(0, 32).TrimStart.TrimEnd = "Item" Then
lStart = True
End If
If sline.TrimStart.TrimEnd = "" Then
lStart = False
End If
End If
Next
'Execute SQL Stored Procedure
Using cn As New SqlConnection(cls.strConnString)
Using cmd As New SqlCommand()
With cmd
.CommandType = CommandType.StoredProcedure
.CommandText = "USP_XML_SOH_ACCOUNT_MAINT"
.Parameters.Add("#XMLdata", SqlDbType.Xml) : .Parameters("#XMLdata").Value = writer.ToString
.Parameters.Add("#USR_ID", SqlDbType.VarChar, 30) : .Parameters("#USR_ID").Value = cls.GetUserName
.Parameters.Add("#FILE_NAME", SqlDbType.VarChar, 255) : .Parameters("#FILE_NAME").Value = sFileName
.Parameters.Add("#RET_VAL", SqlDbType.VarChar, 255)
.Parameters("#RET_VAL").Direction = ParameterDirection.Output
.Connection = cn
cn.Open()
.ExecuteNonQuery()
Request_Val = .Parameters("#RET_VAL").Value.ToString
End With
End Using
End Using
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Javascript", "<script>$(document).ready(function(){$('#grid-div').height(250);$.blockUI({message: 'Updating data...',css: {border: 'none',padding: '15px', width: '15%', left: '40%',backgroundColor: '#000','-webkit-border-radius': '10px','-moz-border-radius': '10px',opacity: .5,color: '#fff'}});setTimeout($.unblockUI, 2000); " & _
" $('#dialog-message').html('<table style=""border-style:hidden;""><tr><td style=""padding:5px;""> <img src=""images/gridview/check_circle_64x64.png""/></td><td>" & Request_Val.ToString & "</td></tr></table>');" & _
"$('div#dialog-message').dialog ({ my: 'center', at: 'center', of: window}).prev ().find ('.ui-dialog-titlebar-close').hide(); " & _
"var varCounter = 0; var varName = function(){ if(varCounter < 1){ varCounter++; $('#dialog-message').dialog('open'); } else {clearInterval(varName);}};setInterval(varName, 2000);}); </script>")
Else
jsbldr.Append("<script>")
jsbldr.Append("$(document).ready(function(){")
jsbldr.Append("$('div#dialog-message').dialog ({ my: 'center', at: 'center', of: window}).prev ().find ('.ui-dialog-titlebar-close').hide();")
jsbldr.Append("$('#dialog-message').html('<table style=""border-style:hidden;""><tr><td style=""padding:5px;""> <img src=""images/gridview/exclamation_circle_64x64.png""/></td><td>Invalid file format, please use .xlsx excel file extention.</td></tr></table>');")
jsbldr.Append("$('#dialog-message').dialog('open');")
jsbldr.Append("});")
jsbldr.Append("</script>")
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Javascript", jsbldr.ToString)
End If
End If
Catch ex As Exception
jsbldr.Append("<script>")
jsbldr.Append("$(document).ready(function(){")
jsbldr.Append("$('div#dialog-message').dialog ({ my: 'center', at: 'center', of: window}).prev ().find ('.ui-dialog-titlebar-close').hide();")
jsbldr.Append("$('#dialog-message').html('<table style=""border-style:hidden;""><tr><td style=""padding:5px;""> <img src=""images/gridview/exclamation_circle_64x64.png""/></td><td>Uploading SOH Account file template encounter error, please check the file.</td></tr></table>');")
jsbldr.Append("$('#dialog-message').dialog('open');")
jsbldr.Append("});")
jsbldr.Append("</script>")
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Javascript", jsbldr.ToString)
End Try
End Sub
Here's the actual text file, in every end of the record there is an end symbol, I'm trying to put here but it can't capture.
Item Description Rev Locator UOM Quantity
------------------------------------------------------------------------------- --- ------------------------- --- ------------
604K23660 KIT-FDR HCF MSI ANG.2.0.0 PC 1.00
604K23670 KIT FEEDER TM ANG.2.0.0 PC 3.00
604K26021 LEN ASSY ANG.2.0.0 PC 1.00
CT200541 AP/DCC4400/4300/3300/2200 Cartridge Toner ANG.2.0.0 Unt 3.00
(Magenta)
CT200542 AP/DCC4400/4300/3300/2200 Cartridge Toner (Yellow) ANG.2.0.0 Unt 6.00
Subinventory: NEI-OLO Description: Non-Equipment Inventory of Olongapo
Item Description Rev Locator UOM Quantity
------------------------------------------------------------------------------- --- ------------------------- --- ------------
CT350769 DC-III 3007/2007 Drum Cartridge Standard PC 7.00
CT350851 AP/DC-IV C5570/4470/3370/3371/2270 Long Life Drum PC 2.00
Cartridge (1 piece)
I put some condition in my For Each for the file. Now the condition read each line where to start reading and where to end and then add each row in my datatable, it loop until lStart = FALSE but I have an error on my condition if the record reached the ending symbol lSTart = False and then will loop again to find the "Item".
For Each sline In sFileLines
If sline.TrimStart.TrimEnd <> "" Then
If lStart = True Then
If sline.Substring(0, 10).TrimStart.TrimEnd <> "-------" Then
Dim newRow As DataRow = dt.NewRow
newRow("Item") = sline.Substring(0, 32).TrimStart.TrimEnd
newRow("Description") = sline.Substring(33, 53).TrimStart.TrimEnd
newRow("Rev") = sline.Substring(86, 3).TrimStart.TrimEnd
newRow("Locator") = sline.Substring(89, 26).TrimStart.TrimEnd
newRow("UOM") = sline.Substring(115, 3).TrimStart.TrimEnd
newRow("Quantity") = sline.Substring(124, 7).TrimStart.TrimEnd
dt.Rows.Add(newRow)
End If
End If
If sline.Substring(0, 32).TrimStart.TrimEnd = "Item" Then
lStart = True
End If
If sline.TrimStart.TrimEnd = "" Then
lStart = False
End If
Here's my condition on the ending symbol, apparently the symbol can't capture here,but on visual studio it can.
If sline.TrimStart.TrimEnd = "" Then
lStart = False
End If
After reading all the data, I need an XMLData to write this on the database in sql server. So I have a stored procedure for this. It is not working yet because the error on my For Each Condition.
I appreciate the suggestion and help, feel free to right my codes. Thanks
I picked to put them in a list but you could use an array. I don't need to show you how to insert values inside excel as you seem to know already. Skip the 2 first line or insert them as headers inside your excel file. concept is the same.
Dim xstr As String = "007K88431 GEAR ASSY-20/46 ANG.2.0.0 PC 1.00"
Dim xline As New List(Of String)
xline.Add(Strings.Mid(xstr, 1, 30).Trim)
xline.Add(Strings.Mid(xstr, 31, 56).Trim)
xline.Add(Strings.Mid(xstr, 87, 26).Trim)
xline.Add(Strings.Mid(xstr, 113, 4).Trim)
xline.Add(Strings.Mid(xstr, 117).Trim)
That seems like a lot of surpfluous code for uploading a file! To load a Text file or a CSV, which is the same thing, run the following script.
BULK INSERT TmpStList FROM 'c:\TxtFile1.txt' WITH (FIELDTERMINATOR = '","')

In Classic ASP reading cXML Files, is it required to point your dtd link to local files?

Unfortunately, we've inherited an old Classic ASP site and are writing new code for a round trip punch-out site. Reading in the cXML file, we're continually erroring out on the 2nd line !DOCTYPE cXML SYSTEM "http://xml.../cXML.dtd.
If we capture the location of the dtd file and change it to a local file, i.e., file:///c:/....dtd it works. Is there no way to get this to work using the http location? I'd rather not store all the dtd file versions locally.
Our Code is:
Dim olddtdvalue
Dim newdtdvalue
Dim xmlfilename
olddtdvalue = "http://xml.cxml.org/schemas/cXML/"
newdtdvalue = "file:///d:/Websites/FSIResponsive/cXML/"
xmlfilename ="PORS_" & formatdatetime(now,vblongdate) & " " & replace(formatdatetime(now,vblongtime),":","_") & ".xml"
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("d:\WebSites\FSIResponsive\cXML\InFiles\" & xmlfilename,true)
f.write("remote host: " & request.ServerVariables("REMOTE_HOST") & vbcrlf & vbcrlf)
totalBytes = Request.TotalBytes
If totalBytes > 0 Then
xml = Request.BinaryRead( totalBytes )
for i = 1 to totalBytes
xmlstr = xmlstr + String(1,AscB(MidB(xml, i, 1)))
Next
f.write(xmlstr)
xml2 = xmlstr
xml2 = Replace(xml2,olddtdvalue,newdtdvalue)
End if
Set xdoc = Server.CreateObject("Microsoft.XMLDOM")
' Set xdoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
xdoc.ValidateOnParse = True
xdoc.async = False
xdoc.resolveExternals = True
' response.write xml2
loadStatus = xdoc.loadXML(xml2)
As you can see, we've tried using MSXML2.DOMDocument.6.0, but that doesn't work either.
Thanks,
Alan
Update:
Here's the code I finally got working:
Dim xmlfilename
Dim URL
totalBytes = Request.TotalBytes
If totalBytes > 0 Then
xml = Request.BinaryRead( totalBytes )
for i = 1 to totalBytes
xmlstr = xmlstr + String(1,AscB(MidB(xml, i, 1)))
Next
xml2 = xmlstr
End if
Set xdoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
xdoc.setProperty "ServerHTTPRequest", True
xdoc.setProperty "ProhibitDTD",False
xdoc.resolveExternals = True
xdoc.ValidateOnParse = True
xdoc.async = False
loadStatus = xdoc.LoadXML(xml2)
Alan

Index was out of range. Must be non-negative and less than the size of the collection - chart databind

I'm trying to build a datatable and then bind it to a gridview and chart object. The gridview appears fine but when I build the x,y array and bind them to the chart object I get the error above.
I've read many forums to understand that the index is looking at a field that is out of range but I've queried in the immediate window all the fields and the are clearly values there. There error occurs as soon as I bind it to the chart object and I don't know why the chart object doesn't just display properly.
This is my aspx codebehind:
Dim dt As DataTable = New DataTable()
dt.Columns.Add("CompanyName")
dt.Columns.Add("Amount")
dt.Columns.Add("Proportion")
Using DBContext As New fundmatrixEntities
Dim queryUnits = (From c In DBContext.Units Where c.SavingApplicationId = savAppId Select New With {.LoanAppId = c.LoanApplicationId}).Distinct().ToList()
Dim companyName As String = ""
Dim savingsAmount As String = ""
Dim totalProportion As String = ""
Dim totalSavingsAmount As String = ""
For Each loan In queryUnits
If Not loan.LoanAppId Is Nothing Then
companyName = classSQLDirect.ExecQuery("SELECT companyname FROM companyprofile where loanapplicationid='" & loan.LoanAppId.ToString & "'")
savingsAmount = classSQLDirect.ExecQuery("SELECT SUM(Amount) from unit where SavingApplicationId='" & savAppId.ToString & "' and LoanApplicationId='" & loan.LoanAppId.ToString & "'")
totalSavingsAmount = classSQLDirect.ExecQuery("SELECT amount FROM SavingApplication WHERE SavingApplicationId='" & savAppId.ToString & "'")
totalProportion = ((savingsAmount / totalSavingsAmount) * 100) & "%"
dt.Rows.Add(companyName, savingsAmount, totalProportion)
End If
Next
gvwBusinesses.DataSource = dt
gvwBusinesses.DataBind()
End Using
Dim x As String() = New String(dt.Rows.Count - 1) {}
Dim y As String() = New String(dt.Rows.Count - 1) {}
For i As Integer = 0 To dt.Rows.Count - 1
x(i) = dt.Rows(i)(0).ToString()
y(i) = dt.Rows(i)(2).ToString()
Next
chart1.Series(0).Points.DataBindXY(x, y)
chart1.Series(0).ChartType = SeriesChartType.Pie
The code errors on the line
chart1.Series(0).Points.DataBindXY(x, y)

Array list error second array replace the first array

I have a problem.
Dim Maxis As String
'Dim MaxisExtra As String
Dim b As New ArrayList
Dim WS As New WebService1.Service1
Dim cnt As String
Dim MRWS As New MobileReload_WS.MobileReload_WS
cnt = WS.StockCountTelco(1, Session("Maxis"))
If CInt(cnt) >= CInt(DropDownList1.SelectedItem.Text) Then
Dim sLock As String
sLock = MRWS.LockAStock(1, 1, "Online", Session("Maxis"), DropDownList1.SelectedItem.Text)
Session("sLock") = sLock
If sLock = "" Then
PopupMsgBox("Unable to allocate Stock")
Else
Maxis = "Maxis" & ";" & Session("Maxis") & ";" & DropDownList1.SelectedItem.Text & ";" & Session("Cost")
'If MaxisExtra = "" Then
' b.Add(Maxis)
' Elseif
' MaxisExtra = MaxisExtra + Maxis
' b.Add(MaxisExtra)
'End If
End If
Else
PopupMsgBox("Not enough stock")
End If
b.Add(Maxis)
Session("Transaction") = b
End Sub
The first time i enter the string into the arraylist it is okay. But when the user press the button add again the second time, it replace the first string. Can anyone help me how to save the string into the second slot based on my coding?
If you're talking about the b ArrayList, then you're creating a new one each time and storing the new ArrayList in Session("Transaction")
Maybe you mean something like this instead...
Dim b as ArrayList = Session("Transaction")
If b Is Nothing Then
b = new ArrayList
End If
...
Session("Transaction") = b
Although it's difficult to say exactly, because your code is very messy and not clear
You put the array list in a session variable, but you never read it back. You create a new array list each time, so it will always be empty and replace the previous one.
Get the array list from the session variable if there is one:
Dim b As ArrayList = Session("Transaction")
If b Is Nothing Then b = New ArrayList

Resources