Poll a directory looking for files with a certain extension - vb.net

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

Related

Vb.net problems download

How can I do a check that first download something and only after that it starts up the program.exe?
I already tried to do something like this but it excutes the file when the download is not finished and it throws some errors.
my Code:
Dim client As WebClient = New WebClient
Dim SourcePath As String = "C:\ProgramData\KDetector\UserAssistView.exe"
Dim SaveDirectory As String = "C:\ProgramData\KDetector"
Dim FileName As String = System.IO.Path.GetFileName(SourcePath)
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, FileName)
If System.IO.File.Exists(SavePath) Then
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
Else
client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"), "C:\ProgramData\KDetector\")
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
End If
You are calling the asynchronous DownloadFile method. Asynchronous method will not block the calling thread.
In order to avoid the problem, your code must be like this:
Dim downloadLink As String = "http://www.nirsoft.net/utils/userassistview.zip"
Dim saveFilePath As String = "C:\ProgramData\KDetector\userassistvkew.zip"
Dim fileName As String = Path.GetFileNameWithoutExtension(saveFilePath)
Dim client As WebClient = New WebClient
Try
CheckExsist(saveFilePath, fileName)
'Before was client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"))
client.DownloadFile(downloadLink, saveFilePath)
MsgBox("Download file completed. File saved in: " & saveFilePath)
'Zip extraction stuff
Catch ex As Exception
MsgBox(ex.Message)
End Try
This is the CheckExsist sub:
Private Sub CheckExsist(ByRef sourcePath As String, ByVal fileName As String, Optional ByVal counter As Integer = 1)
If System.IO.File.Exists(sourcePath) Then
sourcePath = sourcePath.Replace(Path.GetFileName(sourcePath), "") & fileName & "(" & counter & ")" & Path.GetExtension(sourcePath)
counter += 1
CheckExsist(sourcePath, fileName, counter)
End If
End Sub
I manage to download the software (from the official website) and save it as a .zip. Code the last few rows to programmatically extract the .zip, if you ecounter any problem or bug feel free to ask with another question. Anyways there are alot of post on SO regarding zip extraction on vb.net

Create a vb class using a text file. The values for class name and attributes should come from database

I want to create an executable that will use a text file as a template and create a class in vb.net
The class name and its attributes are stored in the database. The user should be able to input the class name. The ClassName and AttributeName tags in the template are to be replaced by the corresponding values from the database.
Any lead would be appreciated. Thank You.
Code files are just text files. Generating code files is a bit confusing because you have source code appearing as string literals, but in a technical sense it isn't very difficult:
Sub GenerateCode()
Dim dtb As New DataTable
dtb.Columns.Add("ClassName")
dtb.Columns.Add("PropertyName")
dtb.Columns.Add("PropertyType")
'NOTE: datatable must be sorted by ClassName
dtb.Rows.Add("ClassOne", "PropertyOne", "String")
dtb.Rows.Add("ClassOne", "PropertyTwo", "Integer")
dtb.Rows.Add("ClassOne", "PropertyThree", "String")
dtb.Rows.Add("ClassTwo", "AnotherPropertyOne", "String")
dtb.Rows.Add("ClassTwo", "AnotherPropertyTwo", "Integer")
dtb.Rows.Add("ClassTwo", "AnotherPropertyThree", "String")
Dim strFilename As String = ""
Dim strParentFolder As String = "C:\Junk"
If Not System.IO.Directory.Exists(strParentFolder) Then
System.IO.Directory.CreateDirectory(strParentFolder)
End If
Dim strPreviousClassName As String = ""
Dim sb As New System.Text.StringBuilder
For Each drwProperty As DataRow In dtb.Rows
Dim strThisClassName As String = drwProperty("ClassName").ToString
If strThisClassName <> strPreviousClassName Then
'class name has changed
If strPreviousClassName > "" Then
'write previous class
sb.AppendLine("End Class")
strFilename = strParentFolder & "\" & strPreviousClassName & ".vb"
My.Computer.FileSystem.WriteAllText(strFilename, sb.ToString, False)
End If
'start new class
sb = New System.Text.StringBuilder
sb.AppendLine("Class " & strThisClassName)
strPreviousClassName = strThisClassName
End If
'append property
sb.AppendLine(" Property " & drwProperty("PropertyName").ToString & " As " & drwProperty("PropertyType").ToString)
Next drwProperty
'Write last class
sb.AppendLine("End Class")
strFilename = strParentFolder & "\" & strPreviousClassName & ".vb"
My.Computer.FileSystem.WriteAllText(strFilename, sb.ToString, False)
End Sub

VB.NET not copying a folder to new destination

So I want to copy the folder at the end, But, for some reason, it doesn't copy it. I do not get an error message, so the code doesn't have errors, it's just incorrect.
Dim Log As String = System.IO.Path.Combine(DateTime.Now.ToString("yyyy_MM_dd_HHmmss"))
Process.Start("CMD", "/c robocopy.exe " & Source & " " & Destination & " /log:C:\Backup\log_" & Log & ".txt ")
Dim Copy2 As String = ("Backup_" & DateTime.Now.ToString("yyyy_MM_dd_HHmmss"))
Dim Destination2 As String
Destination2 = Destination
Dim copy4 As String = Destination2.Substring(0, Destination2.LastIndexOf("\"))
Dim Copy3 As String = System.IO.Path.Combine(copy4, Copy2)
FileIO.FileSystem.CreateDirectory(Copy3)
My.Computer.FileSystem.MoveDirectory(Destination, Copy3, True)
MsgBox("Backup ist vollendet!")
did you try to end the Process, befor accessing the just copied data ?
Try :
process.kill

Connect to MongoDB server with Driver 2.0 best practice

I have VB.net code that connects to a MongoDB. When the database is up and running my code works fine, but when the database is not running I don't get any errors back.
How do I check that the Server is up and running so I can connect to it and do my work? Basically IF the Server is up do work ELSE return a message to user that server is not available.
I look at the documentation about the MongoClient Class but I can't seem to find anything I can use.
MongoClient Class (http://api.mongodb.org/csharp/2.0/html/T_MongoDB_Driver_MongoClient.htm)
Below is my code that works to connect to the MongoDB:
Public Function DbConnection(ByRef ConnString As String, vDbName As String, vColName As String) As MongoClient
'default port
'ConnString = "mongodb://localhost:27017"
'example DB and Collection
'vDbName = "blog"
'vColName = "users"
'Root Object
Dim vClient As MongoClient
vClient = New MongoClient(ConnString)
Dim vDb As MongoDatabaseBase
vDb = vClient.GetDatabase(vDbName)
Dim vCol As IMongoCollection(Of BsonDocument)
vCol = vDb.GetCollection(Of BsonDocument)(vColName)
Return vClient
End Function
Below is additional code where I use InsertOneAsync without creating an error:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If txtName.Text = "" Then
MsgBox("Enter a Name for the Database.")
Else
Dim ConnString As String
ConnString = txtConnStr.Text
Dim vDbName As String
vDbName = txtDb.Text
Dim vColName As String
vColName = txtColl.Text
'Root Object
Dim vClient As MongoClient
vClient = DbConnection(ConnString, vDbName, vColName)
Dim vDb As MongoDatabaseBase
vDb = vClient.GetDatabase(vDbName)
Dim vCol As IMongoCollection(Of BsonDocument)
vCol = vDb.GetCollection(Of BsonDocument)(vColName)
Dim vAddUser As BsonDocument
vAddUser = New BsonDocument
vAddUser.Add("_Id", txtID.Text)
vAddUser.Add("Name ", txtName.Text)
vAddUser.Add("Email", txtEmail.Text)
vAddUser.Add("City", txtCity.Text)
rtfDataDisplay.Text = "BsonDocument = " & vAddUser.ToString & ", #" & vAddUser.Count
Await vCol.InsertOneAsync(vAddUser)
End If
End Sub
Below is the solution I came up with. I am only posting the Try...Catch since I have already posted entire procedures above.
Try
Dim watch As Stopwatch = New Stopwatch
watch.Start()
Dim insertResult As Task = vCol.InsertOneAsync(vAddUser)
Await insertResult
watch.Stop()
MsgBox("Faulted =" & insertResult.IsFaulted.ToString & ", Status = " & insertResult.Status.ToString & ", Watch = " & watch.Elapsed.ToString)
Catch ex As Exception
If ex.HResult.ToString = "-2146233083" Then
MsgBox("unable to insert data due to a timeout exception")
Else
MsgBox("Unable to insert data = " & ", HResult = " & ex.HResult.ToString & "!" & ex.ToString)
End If
End Try
Since the asynch only returns Task, it doesn't wait until the operation is complete. If you wait after the task and then you will capture the exception and process it accordingly, Here is the sample
Change this
Await vCol.InsertOneAsync(vAddUser)
Var insertTask = vCol.InsertOneAsync(vAddUser); insertTask.Wait();
and then remove the async keyword from the button_click method signature.

VB.Net Question

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