I am working on a VB.Net project and trying to get it to pull data from a database. I have the data base located in my bin folder with in the project but I do not know the exact path how to do it. The code that I am using is noted below
Private Sub btnTotalTravelCost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTotalTravelCost.Click
'strsql is a sql statement that selects all the fields from the
'ApprovedTravelRequest table
Dim strSql As String = "SELECT * FROM ApprovedTravelRequests "
'strPath provides the database type and path of the Travel database.
Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" & "Data Source=c:\Travel.accdb"
Dim odaTravel As New OleDb.OleDbDataAdapter(strSql, strPath)
Dim DatCost As New DataTable
Dim intCount As Integer
Dim decTotalCost As Decimal = 0D
'The DataTable name datCost is filled with the data
odaTravel.Fill(DatCost)
'The connection to the databsise is disconnected
odaTravel.Dispose()
For intCount = 0 To DatCost.Rows.Count - 1
decTotalCost += Convert.ToDecimal(DatCost.Rows(intCount)("Travel Cost"))
Next
Me.lblTotalTravelCost.Visible = True
Me.lblTotalTravelCost.Text = "The Total Approved Travel Cost is " & decTotalCost.ToString("C")
End Sub
End Class
Will someone be able to explain how to do this? I am wanting to pull the data from the Bin File. I know the current location shown is incorrect.
If the database is in the bin folder (with the executable), then you can do:
' Get the current directory (where the exe resides)
Dim folder As String = System.AppDomain.CurrentDomain.BaseDirectory
' Construct the full path to the DB (assuming it's with the exe)
folder = System.IO.Path.Combine(folder, "Travel.accdb")
' Build your connection string
Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" & "Data Source=" & folder
Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" & "Data Source=c:\Travel.accdb"
Dim strSql As String = "SELECT * FROM ApprovedTravelRequests"
Dim decTotalCost As Decimal = 0.0
Using connect As New OleDb.OleDbConnection(strPath)
Using command As New OleDb.OleDbCommand(strSql, connect)
connect.Open()
Using reader As OleDb.OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
While reader.Read()
decTotalCost += Convert.ToDecimal(reader(0))
End While
End If
Me.lblTotalTravelCost.Visible = True
Me.lblTotalTravelCost.Text = "The Total Approved Travel Cost is " & decTotalCost.ToString("C")
End Using
End Using
End Using
Related
I'm creating a code for the computers at work. I had to make an "Install" program. I didn't know how to do it properly but I found a way to do it.
When I "Install" the program on a other computer I have my USB-stick and copy it to the local disk at the computer.
Now I start the program for the first time at their computer and this code run's
and then I got an error here because Program is not yet divined:
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim Pathproj As String = AppDomain.CurrentDomain.BaseDirectory
Dim Pathfile As String = Pathproj.Replace("bin\Debug\", "Bestanden\Locatie.txt")
Dim Program As String = System.IO.File.ReadAllText(Pathfile)
'Deze bestanden worden aangemaakt en er wordt automatisch een route ingezet.
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim lBibliotheek As String = System.IO.File.ReadAllText(Program & "Bibliotheek.txt")
Dim lExcel_autonummering As String = System.IO.File.ReadAllText(Program & "Excelbestand autonummering.txt")
Dim lLocatie_telbestanden As String = System.IO.File.ReadAllText(Program & "Locatie telbestanden.txt")
Dim lMapnamen As String = System.IO.File.ReadAllText(Program & "Mapnamen.txt")
Dim lOrderschijf As String = System.IO.File.ReadAllText(Program & "Zoek schijf.txt")
Because when the form2_load I do this and then I wan't to divine that string.
Public Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Locatie_05Kuipers As String
If System.IO.File.ReadAllText(Pathfile) = "" Then
'If System.IO.File.ReadAllText("C:\testing1\testing2\testing7\testing1\testing1\text.txt") = "" Then
Locatie_05Kuipers = InputBox("Vul hier de Locatie waar je start bestanden moeten staan. Bijvoorbeeld: K:\Inventor\Instalprogram\ ")
If System.IO.File.Exists(Pathfile) Then
System.IO.File.Delete(Pathfile)
End If
Dim objStreamWriter As StreamWriter
objStreamWriter = New StreamWriter(Pathfile)
objStreamWriter.WriteLine(Locatie_05Kuipers & "\03 - Locaties")
objStreamWriter.Close()
ButtonInstal.Visible = True
Exit Sub
Else
End If
So how or where do I need to put my strings?
You can save a path in your settings, and every time you need it, you can create the file and put your data in it.
For example:
Dim pathString As String = My.Settings.filePath
Dim fullPath = Path.Combine(pathString, "Locatie.txt")
If Not Directory.Exists(pathString) Then
Directory.CreateDirectory(pathString)
File.Create(fullPath)
Else
If Not File.Exists(pathString) Then
File.Create(fullPath)
Else
Console.WriteLine($"File {fullPath}already exists.")
End If
End If
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
Please somebody help me. I use Lotus Notes to send email with using vb.net but I got this error when I try to run. I already add references about interop.lotus.dll and interop.Domino.dll but it's still the same error. Please advice..
Line 115: If dsEmail.Tables(0).Rows.Count > 0 Then
Line 116: **s.Initialize("abcde!")** 'ERROR in THIS LINE
Protected Sub btnSend_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.ServerClick
Dim s As New Domino.NotesSession
Dim db As Domino.NotesDatabase
Dim doc As Domino.NotesDocument
Dim mimeEntity As Domino.NotesMIMEEntity
Dim mimeChild As Domino.NotesMIMEEntity
Dim header As Domino.NotesMIMEHeader
Dim stream As Domino.NotesStream
Dim sendTo As String
Dim connectionString As String = "Data Source=[hide];User ID=[hide];initial Catalog=[hide];Password=[hide]"
Dim objConn As New SqlConnection(connectionString)
objConn.Open()
Dim dsEmail = New DataSet
Dim CommTaskA As SqlCommand
Dim AdapTaskA As SqlDataAdapter
CommTaskA = New SqlCommand("select EMAILBLASTCCID, rtrim(ltrim(EMAILADDR)) EMAILADDR, SUBJECTEMAIL, EMAILTEMPLATE from [hide] where [MESSAGE_TIME] is NULL", objConn)
CommTaskA.CommandTimeout = 180
AdapTaskA = New SqlDataAdapter
AdapTaskA.SelectCommand = CommTaskA
AdapTaskA.Fill(dsEmail)
AdapTaskA.Dispose()
CommTaskA.Dispose()
objConn.Close()
If dsEmail.Tables(0).Rows.Count > 0 Then
s.Initialize("abcde!")
db = s.GetDatabase("[hide]", "[hide].nsf", False)
subjectEmail = dsEmail.Tables(0).Rows(0)(2).ToString
For x As Integer = 0 To dsEmail.Tables(0).Rows.Count - 1
doc = db.CreateDocument()
sendTo = dsEmail.Tables(0).Rows(x)(1).ToString
doc.ReplaceItemValue("SendTo", dsEmail.Tables(0).Rows(x)(1))
doc.ReplaceItemValue("Subject", dsEmail.Tables(0).Rows(x)(2))
mimeEntity = doc.CreateMIMEEntity
mimeChild = mimeEntity.CreateChildEntity
header = mimeEntity.GetNthHeader("Content-Type")
header.SetHeaderVal("multipart/related")
stream = s.CreateStream
stream.WriteText("<img src='" & dsEmail.Tables(0).Rows(x)(3) & "'>")
mimeChild.SetContentFromText(stream, "text/html", Domino.MIME_ENCODING.ENC_NONE)
stream.Close()
doc.Send(False)
objConn.Open()
CommTaskA = New SqlCommand("update [ZITA].[DEV].[EMAILBLASTCC_test] set [MESSAGE_TIME] ='" & DateTime.Now.ToString & "' where rtrim(ltrim(EMAILADDR)) = '" & sendTo & "'", objConn)
CommTaskA.CommandTimeout = 180
CommTaskA.ExecuteNonQuery()
CommTaskA.Dispose()
objConn.Close()
Next
End If
End Sub
Thank you for all your respond.. I found the answer
the problem because the user account Lotus Notes and my IIS Manager are different.
You must make your Lotus Notes IBM and Application Pool Identity in IIS Manager run with the same account.
It works for me. Thank You
Make sure the Windows environment variable PATH points to C:\Users\adventina.nababan\AppData\Local\IBM\Notes\Data\ too.
For further instructions on how to do this, please take a look at the question "Adding directory to PATH Environment Variable in Windows".
I have been trying to upload and read an Excel file (.xls, or .xlsx)
I am upploading sucessfully using this code:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim filepath As String = ""
If FileUpload1.HasFile Then
Try
Dim filename As String = FileUpload1.PostedFile.FileName
Dim extension = (filename.Substring(filename.LastIndexOf("."), (filename.Length() - filename.LastIndexOf("."))))
If extension = ".xlsx" Or extension = ".xls" Then
filepath = "\" & Common.toUnix(Now) & "_" & filename
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
' ==== NOW READ THE FILE
Else
StatusLabel.InnerText = "Only Excel file types are accepted (.xls/.xlsx)<br> File Uploaded had extension: " & extension
End If
Catch ex As Exception
StatusLabel.InnerText = "Upload status: The file could not be uploaded. The following error occured: " + ex.ToString()
End Try
End If
End Sub
It uploads OK, but when trying to read the file I get this error:
System.Data.OleDb.OleDbException (0x80004005): The Microsoft Jet database engine cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data.
I am using code to read similar to this:
vb.net traversing an xls / xlsx file?
Therefore the connection is as follows:
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0" & _
";Data Source=" & ExcelFile & _
";Extended Properties=Excel 8.0;"
Dim conn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Dim excelDataSet As New DataSet()
Try
conn = New OleDbConnection(connString)
conn.Open() '<<< ERROR IS RAISED ON THIS LINE
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets(dt.Rows.Count) As String
Dim i As Integer = 0
For Each row As DataRow In dt.Rows
excelSheets(i) = row("payments").ToString
System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
If i = SheetNumber Then
Exit For
End If
Next
..................
I'm uploading to a shared server so don't have control as to permissions as such, but I do have read/write permissions and uploading Images works OK, but it's reading this file that I can't get to work.
NOTE
This error occurs with .xls files, when using .xlsx I get this error:
System.Data.OleDb.OleDbException (0x80004005): Cannot update. Database or object is read-only. at System.Data.OleDb.OleDbConnectionInternal
This error occurs on this line:
For Each row As DataRow In dt.Rows
So it appears it is uplpoading and opening the file OK, but not reading the rows....
I am not sure why that's happening either!
Any help would be much appreciated!
ACE is brutal, have troubles with it all the time and it cannot exist on a System in both 32 and 64 bit version at the same time. As a result I just dont use it at all.
To read an Excel XLSX file I use "EPPlus" which has proven to be very easy to deal with and extreamly efficient.
It ONLY works with XLSX (not XLS)
Example... (simple just pulls out first sheet as a datatable)
Public Function XlsxToDataTable(byteStream As IO.MemoryStream) As DataTable
Using pac As New OfficeOpenXml.ExcelPackage(byteStream)
Dim wb As OfficeOpenXml.ExcelWorkbook = pac.Workbook
Dim ws As OfficeOpenXml.ExcelWorksheet = wb.Worksheets(1) '1 based
Dim out As New DataTable
For iC As Integer = 1 To ws.Dimension.End.Column
out.Columns.Add(ws.Cells(1, iC).Value.ToString)
Next
For iR As Integer = 2 To ws.Dimension.End.Row
Dim nr As DataRow = out.NewRow
For iC As Integer = 1 To ws.Dimension.End.Column
nr(iC - 1) = ws.Cells(iR, iC).Value
Next
out.Rows.Add(nr)
Next
Return out
End Using
End Function
I'm writing a script to look in a directory, read the file name and use a part of the file name to run a SQL query to amend a DB, then copy the files to a new location and delete the original.
Once this is done it sends an email confirmation to a predefined email address.
I have the majority in place but am not able to Poll a Dir and process all files that may be there. Im new to this VB.net stuff and to get the other stuff working iv just named it at the beginning.
Any help would be greatly appreciated.
Dim fileName As String = "C:\temp\Input\VBTEST1.success"
Dim pathname As String = "C:\temp\Input\"
Dim result As String
Dim sourceDir As String = "C:\temp\Input\"
Dim processedDir As String = "C:\temp\Input\Processed\"
Dim fList As String() = Directory.GetFiles(sourceDir, "*.success")
Dim sqlCommand As SqlCommand
Public Sub Main()
result = Path.GetFileName(fileName)
Console.WriteLine("GetFileName('{0}') returns '{1}'", fileName, result)
Dim betacell As String = result
betacell = (result.Remove(7, 8))
Dim connection As New SqlConnection(My.Settings.connectionString)
connection.Open()
Dim updateTransaction As SqlTransaction = connection.BeginTransaction()
Dim sqlQ As String = "UPDATE " & My.Settings.JobTb & " SET Status = '10' WHERE JobNumber ='" & betacell & "'"
sqlCommand = New SqlCommand(sqlQ, connection, updateTransaction)
sqlCommand.ExecuteNonQuery()
updateTransaction.Commit()
connection.Close()
SendEmail(My.Settings.emailUsers, "EMAIL TEXT")
Call MoveFiles()
End Sub
I'm all chuffed now as iv also managed to make it look for all files with a .success extension. Now it processes all files and not the one named in the code.
Module Module1
Dim sourceDir As String = My.Settings.watchPath
Dim processedDir As String = My.Settings.processedPath
Private loggerName As String = "EmailReleases"
Public Sub log(ex As Exception)
Console.WriteLine("Error: " & ex.ToString)
End Sub
Public Sub log(ByVal s As String)
Console.WriteLine(DateTime.Now.ToString & " [" & loggerName & "] " & s)
End Sub
Public Sub Main()
Dim inputFiles As String() = Directory.GetFiles(sourceDir, "*.success")
log("Starting processing of .success files in '" & sourceDir & "' ... ")
If (inputFiles.Length > 0) Then
Dim connection As New SqlConnection(My.Settings.connectionString)
connection.Open()
For Each fileName As String In inputFiles
Dim sqlCommand As SqlCommand
Dim fFile As New FileInfo(fileName)
log(" Processing " & fFile.Name)
Dim betacell As String = fFile.Name.Substring(0, fFile.Name.Length - 8)
'Update Status on Database with the use of the Betacell
Dim updateTransaction As SqlTransaction = connection.BeginTransaction()
Dim sqlQ As String = "UPDATE " & My.Settings.JobTb & " SET Status = '10' WHERE JobNumber ='" & betacell & "'"
sqlCommand = New SqlCommand(sqlQ, connection, updateTransaction)
Dim result = sqlCommand.ExecuteNonQuery()
'Email COnfirmation
SendEmail(My.Settings.emailUsers, "EMAIL TEXT")
If (result > 0) Then
'Move the file
fFile.MoveTo(processedDir & fFile.Name)
updateTransaction.Commit() ' make sure to commit only in case moving the file is OK
Else
log("ERROR - Betacell '" & betacell & "' not found in database!")
updateTransaction.Rollback()
End If
Rather than polling a folder (i.e. checking every n seconds whether it has new files) it's much more efficient to have the operating system notify you of changes in that folder. You can do this by creating a FileSystemWatcher. There is an example on MSDN.
However, if you did want to poll a folder, it's actually nice and easy - just wrap the following code in a Timer. Please note I normally code in C#, so apologies if the syntax is not 100%...
Imports System.IO
....
For Each file as String in Directory.GetFiles("C:\SomeFolder")
DoSomethingWithFile (file)
Next