I tried the below code to upload a file to sql server table using vb.net command button. But while clicking build getting error in UploaderEventArgs.
Type 'UploaderEventArgs' is not defined.
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Protected Sub UploadAttachments1_FileUploaded(ByVal sender As Object, ByVal args As UploaderEventArgs)
'set connection string
Dim connectionString As String = System.Configuration.ConfigurationSettings.AppSettings("ConnectionString")
' Read the file and convert it to Byte Array
Dim data() As Byte = New Byte((args.FileSize) - 1) {}
'get file extension
Dim extensioin As String = args.FileName.Substring((args.FileName.LastIndexOf(".") + 1))
Dim fileType As String = ""
'set the file type based on File Extension
Select Case (extensioin)
Case "doc"
fileType = "application/vnd.ms-word"
Case "docx"
fileType = "application/vnd.ms-word"
Case "xls"
fileType = "application/vnd.ms-excel"
Case "xlsx"
fileType = "application/vnd.ms-excel"
Case "jpg"
fileType = "image/jpg"
Case "png"
fileType = "image/png"
Case "gif"
fileType = "image/gif"
Case "pdf"
fileType = "application/pdf"
End Select
Dim stream As Stream = args.OpenStream
'read the file as stream
stream.Read(data, 0, data.Length)
Dim con As SqlConnection = New SqlConnection(connectionString)
Dim com As SqlCommand = New SqlCommand
com.Connection = con
'set parameters
Dim p1 As SqlParameter = New SqlParameter("#Name", SqlDbType.VarChar)
Dim p2 As SqlParameter = New SqlParameter("#FileType", SqlDbType.VarChar)
Dim p3 As SqlParameter = New SqlParameter("#Data", SqlDbType.VarBinary)
p1.Value = args.FileName
p2.Value = fileType
p3.Value = data
com.Parameters.Add(p1)
com.Parameters.Add(p2)
com.Parameters.Add(p3)
com.CommandText = "Insert into Files (Name,FileType,Data) VALUES (#Name,#FileType,#Data)"
con.Open()
'insert the file into database
com.ExecuteNonQuery()
con.Close()
End Sub
End Class
Source Link to the above code:
http://ajaxuploader.com/h/Save-Files-to-Database-using-FileUpload-Control.htm
It looks like UploaderEventArgs is part of the framework the company you linked offers, so you need to download and install it first. It's not part of the regular .NET libraries.
Related
I'm building a system that allows adding attachments. I have almost everything working, but any of the "open" formats from newer office files are coming out with the following error:
"We found a problem with some of the content in file.xlsx. Do you want us to recover as much as we can? IF you trust the source of this workbook, click yes."
clicking yes, usually will open the file, but I'd like to get past this entirely.
Files are stored in SQL Server, and uploaded and retrieved by stored procedure.
uploadFunction:
Protected Sub btnUploadAttachment_Click(sender As Object, e As EventArgs) Handles btnUploadAttachment.Click
Try
Dim fileCount As Integer = 0
For Each file As UploadedFile In filFileAttachment.UploadedFiles
fileCount += 1
Using conn As New SqlConnection With {.ConnectionString = SadSql},
cmd As New SqlCommand With {.CommandText = "RAD_ProjectTracker.dbo.spProject_Attachment_Add", .Connection = conn, .CommandType = CommandType.StoredProcedure, .CommandTimeout = SQLCommandTimeout}
Dim buffer As Byte()
Using s As Stream = file.InputStream
buffer = New Byte(s.Length) {}
s.Read(buffer, 0, buffer.Length)
End Using
cmd.Parameters.Add("#PROJECT_ID", SqlDbType.Int).Value = hfProjectID.Value
cmd.Parameters.Add("#VERSION_ID", SqlDbType.Int).Value = hfVersionID.Value
If Not hfJobID.Value.IsNullOrEmpty() Then cmd.Parameters.Add("#JOB_ID", SqlDbType.Int).Value = hfJobID.Value
cmd.Parameters.Add("#USER_ID", SqlDbType.Int).Value = Session("uid")
cmd.Parameters.Add("#ATTACHMENT", SqlDbType.VarBinary).Value = buffer
cmd.Parameters.Add("#ATTACHMENT_TYPE", SqlDbType.VarChar).Value = "ATTACH_TYPE_DOCUMENT"
cmd.Parameters.Add("#MIME_TYPE", SqlDbType.VarChar).Value = file.ContentType
cmd.Parameters.Add("#FILE_NAME", SqlDbType.VarChar).Value = file.FileName
If Not txtDescription.Text.IsNullOrEmpty() Then cmd.Parameters.Add("#DESCRIPTION", SqlDbType.VarChar).Value = txtDescription.Text
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
Next
ReturnToAttachments()
Catch ex As Exception
Dim s As String = ex.Message
End Try
End Sub
and the retrieval code:
Dim tsql As String = "Exec RAD_ProjectTracker.dbo.spProject_Attachments_Get #ATTACHMENT_ID=" & dataItem("ATTACHMENT_ID").Text
Dim dt As DataTable = GetSQLDataSet(tsql, True).TablesSafe(0)
If dt.Rows.Count > 0 Then
Dim dr As DataRow = dt.RowsSafe(0)
Dim file As Byte() = CType(dr("ATTACHMENT"), Byte())
Dim fileName As String = If(IsDBNull(dr("FILE_NAME")), "attachment", CStr(dr("FILE_NAME")))
Response.Clear()
Response.ClearHeaders()
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)
Response.ClearContent()
Response.ContentType = dr("MIME_TYPE")
Response.BinaryWrite(file)
Response.End()
End If
I've tested .xls, .dox, .ppt, .png, .jpg, .txt, and a few others and they all work fine.
It's only the .xlsx, .docx, and .pptx that seem to be having issues.
I've googled around and haven't been able to find much. Is there an extra step to these documents? or perhaps i am doing something in the wrong order?
Any help would be appreciated.
I am currently working on a project which is a music player but I am trying to make it work with SQL Server.
I have uploaded my music to SQL Server using queries , however the problem is retrieving them. The file type is varbinary(MAX). I tried to go an alternate route where i retrieve the binary in a text file and thereafter convert the file extension to .wav and play it through a media player while the local file being temporary.
Private Sub Online_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Using cn As SqlConnection = New SqlConnection("Server= DESKTOP-8KB6RLJ; Database= TESTdb; Integrated security = true ")
cn.Open()
Using cmd As SqlCommand = New SqlCommand()
cmd.Connection = cn
Dim qry As String
qry = String.Format("SELECT FileStreamCol From MUSIC")
cmd.CommandText = qry
cmd.CommandTimeout = 0
Dim oFileStream As System.IO.FileStream
oFileStream = New System.IO.FileStream("C:\3N3RGY\bytes.mp3", System.IO.FileMode.OpenOrCreate)
Using myReader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While (myReader.Read())
Dim data As Byte() = myReader(0)
oFileStream.Write(data, 0, data.Length)
End While
oFileStream.Close()
Dim myFiles As String()
myFiles = IO.Directory.GetFiles("C:\3N3RGY", "*.txt")
Dim newFilePath As String
For Each filepath As String In myFiles
newFilePath = filepath.Replace(".txt", ".mp3")
System.IO.File.Move(filepath, newFilePath)
AxWindowsMediaPlayer1.URL = ListBox1.SelectedItem
Next
End Using
End Using
End Using
Catch ex As Exception
End Try
End Sub
Currently Im facing problem in importing csv file to devexpress gridview,When i execute the code, the following error showed 'C:\New folder\QtimeAutomotiveByLot_new.csv' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides. and the filepath works perfectly fine on my side. my code is as follow, can anyone guide me on this?
asp.net
<dx:ASPxGridView ID="DetailGridx" runat="server" OnDataBinding="DetailGridx_DataBinding">
vb.net
Protected Sub DetailGridx_DataBinding(sender As Object, e As EventArgs)
Dim dt1 As New DataTable()
Dim csvFileFolder As String = "C:\New folder\QtimeAutomotiveByLot_New.csv"
'Dim csvFile As String = "QtimeAutomotiveByLot_New.csv"
Dim strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + csvFileFolder + ";Extended Properties='Text;HDR=YES;IMEX=1;';"
Dim connx As New OleDbConnection(strCon)
Dim adapter1 As New OleDbDataAdapter
connx.Open()
Dim sql As New OleDbCommand("Select * FROM [" + csvFileFolder + "]", connx)
adapter1.SelectCommand = sql
adapter1.Fill(dt1)
connx.Close()
Dim detailGrid As ASPxGridView = CType(sender, ASPxGridView)
Dim RowLotID As String = TryCast(sender, ASPxGridView).GetMasterRowFieldValues("LOTID")
Dim ddata As DataView = New DataView(dt1)
ddata.RowFilter = "LOTID = '" + RowLotID + "'"
detailGrid.DataSource = ddata
detailGrid.DataBind()
End Sub
Sounds like your current connection string to read CSV file is wrong. Unlike reading Excel files, when reading CSV files we're not specifying actual file name, but directory path where it belongs (see this issue).
The following example shows how to read CSV file using Jet 4.0 provider. Note that instead of setting IMEX=1, use FMT=Delimited property because IMEX primarily used for XLS and XLSX file format:
Protected Sub DetailGridx_DataBinding(sender As Object, e As EventArgs)
Dim dt1 As New DataTable()
Dim csvFileFolder As String = "C:\New folder\"
Dim csvFile As String = "QtimeAutomotiveByLot_New.csv"
' specify directory path containing CSV file as data source
Dim strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + csvFileFolder + ";Extended Properties='Text;HDR=YES;FMT=Delimited';"
Dim connx As New OleDbConnection(strCon)
Dim adapter1 As New OleDbDataAdapter
connx.Open()
' specify actual file name here
Dim sql As New OleDbCommand("Select * FROM [" + csvFile + "]", connx)
adapter1.SelectCommand = sql
adapter1.Fill(dt1)
connx.Close()
Dim detailGrid As ASPxGridView = CType(sender, ASPxGridView)
Dim RowLotID As String = TryCast(sender, ASPxGridView).GetMasterRowFieldValues("LOTID")
Dim ddata As DataView = New DataView(dt1)
ddata.RowFilter = "LOTID = '" + RowLotID + "'"
detailGrid.DataSource = ddata
detailGrid.DataBind()
End Sub
I can't seem to read a .xlsx file using the following connection string:
Webconfig
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
Code File
conStr = ConfigurationManager.ConnectionStrings("Excel07ConString").ConnectionString
Dim connExcel As New OleDbConnection(conStr)
connExcel.Open()
I have been getting this error:
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)". OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "'F:\Ishan\Projects\ImportExcel2DB\ImportExcel2DB\Files\Whole Extract.xlsx' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.".
and yes there is file at this specific location. Any help would be appreciated!
The HDR needs to be either Yes or No. See my project below
Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Module Module1
Sub Main()
Dim reader As New CSVReader()
Dim ds As DataSet = reader.ReadCSVFile("filename", True)
End Sub
End Module
Public Class CSVReader
Public Function ReadCSVFile(ByVal fullPath As String, ByVal headerRow As Boolean) As DataSet
Dim path As String = fullPath.Substring(0, fullPath.LastIndexOf("\") + 1)
Dim filename As String = fullPath.Substring(fullPath.LastIndexOf("\") + 1)
Dim ds As DataSet = New DataSet()
Dim header As String
If headerRow Then
header = "Yes"
Else
header = "No"
End If
Try
If File.Exists(fullPath) Then
Dim ConStr As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=""Text;HDR={1};FMT=Delimited\""", path, header)
Dim SQL As String = String.Format("SELECT * FROM {0}", filename)
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(SQL, ConStr)
adapter.Fill(ds, "TextFile")
ds.Tables(0).TableName = "Table1"
End If
For Each col As DataColumn In ds.Tables("Table1").Columns
col.ColumnName = col.ColumnName.Replace(" ", "_")
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return ds
End Function
End Class
Public connstring As String = "Provider = Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\blablabla\Document\Visual Studio 2013\Project\rentalsystem\rental_db.accdb"
i placed this line of code under a module so i wont have to call it everytime. and this is the code that the code above is connected to...
Public Sub loadLVusers()
LVusers.Items.Clear()
Dim sqlcode As String = "select id_code, user_lastname, user_firstname, user_midname, user_username, user_password, user_email, user_privilege from tblUsers"
Dim sqlcomd As New OleDb.OleDbCommand(sqlcode)
sqlcomd.Connection = New OleDb.OleDbConnection(connstring)
sqlcomd.Connection.Open()
Dim DA As New OleDb.OleDbDataAdapter(sqlcomd)
Dim DS As New DataSet
DA.Fill(DS, "Pi")
If DS.Tables("Pi").Rows.Count > 0 Then
Dim Ic(100) As String
For r = 0 To DS.Tables("Pi").Rows.Count - 1
For c = 0 To DS.Tables("Pi").Columns.Count - 1
Ic(c) = DS.Tables("Pi").Rows(r)(c).ToString
Next
Dim LVI As New ListViewItem(Ic)
LVusers.Items.Add(LVI)
Next
End If
End Sub
now when the form/window that it is attached to loads, the form/window does not open. and then it highlights
sqlcomd.Connection = New OleDb.OleDbConnection(connstring)
so im guessing that has something to do with the file path format