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
Related
First post, so go easy on me.
I've been coding for years, first with VB6, then VB.NET and more recently ASP.NET. I'm ashamed to say, this issue has beaten me to the point where I need to ask for help. What's more annoying is that this should be a simple thing to achieve! I'm clearly missing something here.
I'm creating checkbox controls dynamically, quite a few of them in fact. Two per dynamically created table row and their IDs are appended with the ID of the particular DB record on the row, row 1, 2, 3 etc. So on each row there would be two checkboxes, ihave_check_1, ineed_check_1. The next row would be ihave_check_2 and ineed_check_2 and so on.
There is a submit button at the bottom of the page, and when clicked, it's supposed to loop through each row (and cell) in the table and pick out controls whose IDs contain "ihave_check_" and "ineed_check_" then get their Checked value. Once I have the values, I add a record into the database.
Problem is, when you click the button, the table disappears and so do the values.
From what I've read so far, this is happening because the controls are dynamically created, if they were static (coded in the HTML section) I wouldn't have this problem.
So first question, what do I need to do to get it working?
And second question, why is using dynamic controls so difficult?
Here's the code setting up the table, which works great:
Private Sub ddCardSeries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddCardSeries.SelectedIndexChanged
If IsPostBack = True And Not ddCardSeries.SelectedValue = "Select..." Then
cardsTable.Visible = True
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXXXXX;")
Dim dtSections As New DataTable
dtSections = dat.DataSelect("SELECT baseCardID,baseCardSeries,baseCardNumber,baseCardName,frontArtist,conceptArtist,backArtist,backWriter,isBaseCard,isDieCut,isMatte,isGlossy,differentBack,frontImage,backImage FROM baseCards where baseCardSeries = '" & Split(Split(ddCardSeries.Text, "(ID:")(1), ")")(0) & "' and isBaseCard = 'Yes'")
If dtSections.Rows.Count > 0 Then
For i As Integer = 0 To dtSections.Rows.Count - 1
Dim row As New TableRow
For x = 0 To dtSections.Columns.Count - 1
Dim cell1 As New TableCell
If Not IsDBNull(dtSections.Rows(i)(x)) Then
If x = 0 Then
cell1.Text = dtSections.Rows(i)(x)
ElseIf x = 1 Then
cell1.Text = get_card_series(dtSections.Rows(i)(x))
ElseIf x = 13 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
ElseIf x = 14 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
Else
cell1.Text = dtSections.Rows(i)(x)
End If
Else
cell1.Text = ""
End If
row.Cells.Add(cell1)
Next x
Dim newbutton As New Button
Dim newlabel As New Label
newlabel.Text = "<br />"
newbutton.Text = "Modify this entry"
newbutton.Width = 120
newbutton.ID = "modify_button_" & dtSections.Rows(i)(0)
Dim newcheck1 As New CheckBox
Dim newlabel2 As New Label
newlabel2.Text = "<br />"
newcheck1.Text = "I own this card"
newcheck1.Width = 120
newcheck1.ID = "ihave_check_" & dtSections.Rows(i)(0)
Dim newcheck2 As New CheckBox
newcheck2.Text = "I need this card"
newcheck2.Width = 120
newcheck2.ID = "ineed_check_" & dtSections.Rows(i)(0)
Dim cell2 As New TableCell
If is_user_admin() = True Then
newbutton.Enabled = True
Else
newbutton.Enabled = False
End If
cell2.Controls.Add(newbutton)
cell2.Controls.Add(newlabel)
cell2.Controls.Add(newcheck1)
cell2.Controls.Add(newlabel2)
cell2.Controls.Add(newcheck2)
row.Cells.Add(cell2)
cardsTable.Rows.Add(row)
Next
End If
Else
cardsTable.Visible = False
End If
End Sub
Here's the code that loops through the table and tries to save the results to the database:
Protected Sub SubmitChanges_Click(sender As Object, e As EventArgs) Handles SubmitChanges.Click
For Each pcontrol As control In Page.Controls
Dim havecard As String = Nothing
Dim needcard As String = Nothing
Dim rowcardid As String = Nothing
'For Each tabcell As TableCell In tabrow.Cells
'For Each pgcontrol As Control In tabcell.Controls
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ihave" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
havecard = "Yes"
Else
havecard = "No"
End If
End If
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ineed" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
needcard = "Yes"
Else
needcard = "No"
End If
End If
'Next
If Not havecard = Nothing And Not needcard = Nothing Then
If add_card_to_user_list(Session("username"), rowcardid, havecard, needcard) = True Then
Label1.Text = "Update complete"
Else
Label1.Text = "Update failed"
End If
End If
'Next
Next
End Sub
Public Function add_card_to_user_list(ByVal userid As String, ByVal cardid As String, ByVal own As String, ByVal need As String) As Boolean
Try
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXX;")
Dim dtCardSeries As New DataTable
dtCardSeries = dat.DataSelect("select CardID from [" & userid & "_cards] where cardid = '" & cardid & "'")
If dtCardSeries.Rows.Count > 0 Then
dat.DataDelete("delete from [" & userid & "_cards] where cardid = '" & cardid & "'")
End If
dat.DataInsert("insert into [" & userid & "_cards] (Username,CardID,Own,Need) values ('" & userid & "', '" & cardid & "', '" & own & "', '" & need & "');")
Return True
Catch ex As Exception
Return False
End Try
End Function
Any help at this point would be gratefully received.
Thanks!
Please forgive me for asking too many questions.
I have been working on this all day and can't take it anymore.
I have a stored proc called sp_signup()
The stored proc first checks to see if the user has already signed up. If yes, then inform the user that s/he has already signed up for this class.
SET #ERROR = 'You have already signed up for this training'
This works a treat.
If no, then check to see if there are still available seats.
If seats are still available, sign the user up by inserting into training table and inform the user s/her has been signed up.
SET #ERROR = 'You have been registered for this class'
This works a treat.
If no seats remain, then put the user on waiting list by inserting the user's registration info into waitingList table and inform the user s/he has been placed on waiting list.
SET #ERROR = 'Sorry, but this class is full. However, you have been placed on waiting list.'
This works a treat as well.
So, the stored proc, when tested, works great.
However, on our .net app that calls the stored proc, we are sending users emails informing them that they have either been signed up for the class or have been placed on waiting list depending on what the #Error message says.
This is where we are having problem because the email is not going out.
Here are the conditionals for sending email:
If Label1.Text = "You have been registered for this class" Then
'Email code goes here and is sent to inform users they have been registered for class
ElseIf Label1.Text = "Sorry, but this class is full. However, you have been placed on waiting list." Then
'Email code goes here and is sent inform to users they have been placed on waiting list
Else
End If
below is where the stored procedure call is made:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim username = Session("Username")
Try
Dim s As String
s = "sp_signup"
Dim connStr As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim conn As New SqlConnection(connStr)
Dim cmd = New SqlCommand(s, conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#cosID", Request.QueryString("cosId"))
cmd.Parameters.AddWithValue("#locID", Request.QueryString("locid"))
cmd.Parameters.AddWithValue("#dat", Request.QueryString("iddate"))
cmd.Parameters.AddWithValue("#UserName", username)
cmd.Parameters.Add("#ERROR", SqlDbType.[Char], 500)
cmd.Parameters("#ERROR").Direction = ParameterDirection.Output
conn.Open()
cmd.ExecuteNonQuery()
message = DirectCast(cmd.Parameters("#ERROR").Value, String)
Dim cmdGetKey As New SqlCommand("SELECT ##IDENTITY", conn)
Dim skey As Integer = cmdGetKey.ExecuteScalar()
Session("TrainingId") = skey
conn.Close()
btnSendEmail_Click()
'Display some feedback to the user to let them know it was processed
Label1.ForeColor = System.Drawing.Color.Green
Label1.Text = message
Catch
'If the message failed at some point, let the user know
Label1.ForeColor = System.Drawing.Color.Red
Label1.Text = message
End Try
End Sub
The email code has been tested and works without the stored proc and is below:
Protected Sub btnSendEmail_Click()
Dim skey As Integer = Session("TrainingId")
'Response.Write(skey)
'Response.End()
Dim Conn As SqlConnection
'Dim param As SqlParameter
'Dim cmdcommand As SqlCommand
Conn = New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString)
Conn.Open()
If Label1.Text = "You have been registered for this class" Then
Dim emailcmd As New SqlCommand("select distinct lg.Email, lg.fullname, c.CourseName, l.location, d.trainingDates, d.trainingTime, i.instructorName from tblTrainings t Inner Join tblCourses c on t.courseId = c.courseId " & _
" Inner Join tblLocations l on t.locationId = l.LocationId " & _
" Inner Join tblTrainingDates d on t.dateid=d.dateid " & _
" Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
" Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
" Inner Join tblLogin lg on t.username = lg.username where lg.username = '" & Session("username") & "' AND t.CourseID = " & Request.QueryString("cosId") & " AND t.LocationID = " & Request.QueryString("locid") & " AND t.dateId = " & Request.QueryString("iddate") & " AND TrainingId = " & skey & ";", Conn)
Dim dr = emailcmd.ExecuteReader()
If dr.Read() Then
email = dr.GetString(0)
fullname = dr.GetString(1)
courses = dr.GetString(2)
Loc = dr.GetString(3)
tdates = dr.GetDateTime(4)
ttime = dr.GetString(5)
End If
'code for other email requests
Dim objSmtpClient As SmtpClient = New SmtpClient("relay.smtp", 25)
Dim objSender As MailAddress = New MailAddress("name.emailadd.com", "name.emailadd.com")
Dim objMail As MailMessage = New MailMessage("name.emailadd.com", "name.emailadd.com")
objMail.Bcc.Add("name.emailadd.com")
objMail.To.Add(email)
'objMail.CC.Add("name.emailadd.com")
objMail.Subject = "About Your Training: " & courses & ""
objMail.Body = " Dear " & fullname & " <br>You have just signed up for <b>" & courses & "</b> training. <br><br>This training will be held at <b>" & Loc & "</b> on <b>" & tdates & "</b> starting from <b>" & ttime & "</b>.<br><br> For more details about this training, please visit <a href='Training/'> Training/</a>. "
objMail.IsBodyHtml = True
objSmtpClient.Send(objMail)
dr.Close()
ElseIf Label1.Text = "Sorry, but this class is full. However, you have been placed on waiting list." Then
Dim waitcmd As New SqlCommand("select distinct lg.Email, lg.fullname, c.CourseName, wl.location, d.trainingDates, d.trainingTime, i.instructorName from tblWaitingList wl Inner Join tblCourses c on wl.courseId = c.courseId " & _
" Inner Join tblLocations l on wl.locationId = l.LocationId " & _
" Inner Join tblTrainingDates d on wl.dateid=d.dateid " & _
" Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
" Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
" Inner Join tblLogin lg on wl.username = lg.username where lg.username = '" & Session("username") & "' AND wl.CourseID = " & Request.QueryString("cosId") & " AND wl.LocationID = " & Request.QueryString("locid") & " AND wl.dateId = " & Request.QueryString("iddate") & " AND TrainingId = " & skey & ";", Conn)
Dim dr = waitcmd.ExecuteReader()
If dr.Read() Then
email = dr.GetString(0)
fullname = dr.GetString(1)
courses = dr.GetString(2)
Loc = dr.GetString(3)
tdates = dr.GetDateTime(4)
ttime = dr.GetString(5)
End If
'code for other email requests
Dim objSmtpClient As SmtpClient = New SmtpClient("relay.smtp", 25)
Dim objSender As MailAddress = New MailAddress("name.emailadd.com", "name.emailadd.com")
Dim objMail As MailMessage = New MailMessage("name.emailadd.com", "name.emailadd.com")
objMail.Bcc.Add("name.emailadd.com")
objMail.To.Add(email)
'objMail.CC.Add("name.emailadd.com")
objMail.Subject = "About Your Training: " & courses & ""
objMail.Body = " Dear " & fullname & " <br>You have been placed on the waiting list for <b>" & courses & "</b> training. <br><br>This training will be held at <b>" & Loc & "</b> on <b>" & tdates & "</b> starting from <b>" & ttime & "</b>.<br><br> Should a seat become available, notification will be based on first-come, first-served bases.<br>For more details about this training, please visit <a href='http://#/'> http://Training/</a>. "
objMail.IsBodyHtml = True
objSmtpClient.Send(objMail)
dr.Close()
Else
End If
End Sub
I guess you have the order of the following statements wrong:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
...
btnSendEmail_Click()
...
Label1.Text = message
I think you should set Label1.Text before calling btnSendEmail_Click(). It should be the other way round:
Label1.Text = message
...
btnSendEmail_Click()
I am having problems uploading CSV files to my SQL Database. I am trying to achieve this through the File Upload technique on an intranet site. The intranet site is for me and another user to have the ability to file upload these CSVs (in case one of us is out).
I've used the following;
Dim errorList As String = String.Empty
Dim returnValue As Integer = 0
Dim SQLCon As New SqlClient.SqlConnection
Dim SQLCmd As New SqlClient.SqlCommand
Dim ErrString As String
Dim countRecs As Integer = 0
Dim batchid As Integer = GetNextBatchNumber("PartsImport")
Using tf As New TextFieldParser(fileandpath)
tf.TextFieldType = FileIO.FieldType.Delimited
tf.SetDelimiters(",")
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (ID,PartName,PartID,Price,ShipAddress) " _
+ " values ('" + row(0) + "','" + row(1) + "','" _
+ row(2) + "','" + row(3) + "','" + row(4) + "')"
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close()
SQLCon.Dispose()
SQLCmd.Dispose()
When I click the form button to upload, it gives me a success message but when I look in the actual table, it is still blank.
Any ideas? Appreciate it
Thanks
Dave
private void UploaddataFromCsv()
{
SqlConnection con = new SqlConnection(#"Data Source=local\SQLEXPRESS;Initial Catalog=databaseName;Persist Security Info=True;User ID=sa");
string filepath = "C:\\params.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while ( !sr.EndOfStream )
{
value = sr.ReadLine().Split(',');
if(value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "[Base].[PartsImport]";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
Try catching a SqlException and seeing if there is a formatting issue with your request. If you have an identity column on the ID, you shouldn't set it explicitly from your CSV as that may cause a potential duplicate to be submitted to your database. Also, I suspect that you have some type mismatches in your types since you are putting quotes around what appear to be number columns. I would recommend you consider replacing the string concatenation in your query to using parameters to avoid issues with improper quote escaping (ie. what would happen if you have a PartName of "O'Reily's auto parts"?) Something like this may work. Note, I've been in the LINQ world for so long, I may have some syntax errors here.
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text 'Setup Command Type
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (PartName,PartID,Price,ShipAddress) " _
+ " values (#PartName, #PartID, #Price, #ShipAddress)'"
Dim partNameParam = New SqlParameter("#PartName", SqlDbType.VarChar)
Dim partIdParam = New SqlParameter("#PartID", SqlDbType.Int)
Dim partPriceParam = New SqlParameter("#Price", SqlDbType.Money)
Dim partAddressParam = New SqlParameter("#ShipAddress", SqlDbType.VarChar)
SQLCmd.Parameters.AddRange( {partNameParam, partIdPAram, partPriceParam, partAddressParam})
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString()
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
partNameParam.Value = row[1]
partIdParam.Value = row[2]
partPriceParam.Value = row[3]
partAddressParam.Value = row[4]
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close() 'TODO: Change this to a Using clause
SQLCon.Dispose()
SQLCmd.Dispose() 'TODO: Change this to a Using clause
With all that being said, if you have any significant number of items to insert, the bulk copy example is a better answer.
I have a text file having three fields category name, image name and link or URL. The three fields are stored in the text file separated by comma. I want to read the textfile values and display them one by one that is in a column format. So all the category names will be displayed in one column, image name in one column and link in one column.
I have read the text file and i get all the contents in text file in a variable. The content that i get in variable is as follows:
glass,glassbowlcategory.jpg,www.google.com glass,glassbowlcategory.jpg,www.google.com glass bowl,images1.jpg,http://www.fitnessfirstusa.com/catalog.asp?Brand=LG%20Sciences
In the above string first one is category name, second is image name and third is link.
I have used the folllowing code to read text file.
Sub BuildFileList(strFolder)
Dim strFileName1
Dim strSearchText
Dim objFSO, objTextFile
Dim strReadLineText
Dim intLineNumber,strNewContents
Dim strLineNumbers
Dim objFile
' Name of text file to search:
'
'strFileName = "readme.txt"
strFileName1 = "saveimagename.txt"
Const ForReading = 1
Const ForWriting = 2
'' Create an instance of the the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(Server.MapPath(strFileName1))
intLineNumber = 0
'
strLineNumbers = ""
Do While Not objTextFile.AtEndOfStream
intLineNumber = intLineNumber + 1
strReadLineText = objTextFile.ReadLine
' response.Write(strReadLineText)
strNewContents = strNewContents & strReadLineText & vbCrLf
response.Write(strNewContents)
'
Loop
end sub
Please advise how can i split the contents that i get in the variable and display them
For tabular data
Const ForReading = 1
Const ForWriting = 2
Dim objTextFile
Dim intLineNumber, strNewContents, strReadLineText
dim data, columns
strFileName1 = "saveimagename.txt"
Set objTextFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(Server.MapPath(strFileName1))
intLineNumber = 0
strLineNumbers = ""
data = split(objTextFile.readall(), vbcrlf)
for intLineNumber = 0 to ubound(data)
columns = split(data(intLineNumber), ",", 3)
if (ubound(columns) = 2) then
strNewContents = strNewContents & "<tr><td>" & columns(0) & "</td><td>" & columns(1) & "</td><td>" & columns(2) & "</td></tr>" & vbcrlf
end if
next
response.write "<table>" & strNewContents & "</table>"
perhaps you could use Microsoft ActiveX Database Objects (ADO) for that?
here are some links:
Much ADO about Text Files
Microsoft ODBC Desktop Database Drivers
and some sample code:
'http://msdn.microsoft.com/en-us/library/ms974559.aspx
dim conn : set conn = server.createObject("ADODB.Connection")
dim rs : set rs = server.createObject("adodb.recordset")
dim sql
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
importPath & ";" &_
"Extended Properties=""text;HDR=" & HDR & ";FMT=Delimited"""
sql = "SELECT * FROM " & myImportFile
rs.open sql, conn, adOpenStatic, adLockOptimistic, adCmdText
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