closing msaccess.exe in vb.net - vb.net

I am working on creating a vb.net program i have a button that when clicked on will browse for MDB files (code 1) and when selected will execute some lines of code that will populate all of the macros within the access database into a combo box (code 2). The problem i'm having is MSACCESS.EXE process is not closing after code 2 runs. I've tried a couple different things like objAccess.CloseCurrentDatabase() none of which are working.. Any ideas on what i'm doing wrong?
code 1
Private Sub CommandDBPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CommandDBPath.Click
Dim dialog As New OpenFileDialog()
dialog.Filter = "Access database (*.mdb)|*.mdb"
If DialogResult.OK = dialog.ShowDialog Then
TextDBPath.Text = dialog.FileName
End If
SelectDatabaseMacro()
End Sub
code 2
Private Sub SelectDatabaseMacro()
Dim objAccess As Object '' Access.Application
Dim i As Long
Dim path As String
path = TextDBPath.Text
objAccess = CreateObject("Access.Application")
objAccess.OpenCurrentDatabase(path)
For i = 0 To objAccess.CurrentProject.AllMacros.Count - 1
TextReportMacro.Items.Add(objAccess.CurrentProject.AllMacros(i).Name)
Next
objAccess.CloseCurrentDatabase()
objAccess = Nothing
End Sub

Try adding an objAccess.Quit statement after you objAccess.CloseCurrentDatabase().

To abruptly kill the process,
For Each p As Process In Process.GetProcesses()
If p.ProcessName = "MSAccess" Then
p.Kill()
End If
Next
Or for a more "graceful" approach, try this,
The process must have a windows interface (window) in order to work.
For Each p As Process In Process.GetProcesses()
If p.ProcessName = "MSAccess" Then
p.CloseMainWindow()
End If
Next

Related

Notify Icon appears to be disposed after running batch file

I have a WinForms application in VB.net with a NotifyIcon with ContextMenu attached. For some reason when I click the menu item to set the main form as Me.TopMost = false, then copy the batch file to the PC and run it, the NotifyIcon seems to get disposed (no longer appears in system tray). This only appears to happen intermittently.... I have no idea what could be causing this.
The reason that I am thinking that the NotifyIcon is disposed is because if I add a readerNotify.Visible = True after the operation the icon still does not re-appear. See below for the code
Private Sub ResetWindowsUpdateComponentsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ResetWindowsUpdateComponentsToolStripMenuItem.Click
'Adds Windows Update Components reset batch file to ProgramData and runs the file
Dim fileContent As String = My.Resources.WindowsUpdate_Components_Reset
Dim filename As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\WUCR.bat"
Me.TopMost = False
clearWUCache()
My.Computer.FileSystem.WriteAllText(filename, fileContent, False, System.Text.Encoding.ASCII)
'**WHERE NOTIFYICON SEEMS TO DIE**
Dim objProcess As Process = New Process
objProcess.StartInfo.FileName = filename
objProcess.Start()
objProcess.WaitForExit()
prgBarTemps.Value = 100
lblStatus.Text = "Windows Update components reset successfully!"
Me.TopMost = True
End Sub
Private Sub clearWUCache()
Dim wuCacheFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Windows) & "\SoftwareDistribution\Download"
Try
WebFixProcesses.deleteFolders(wuCacheFolder)
WebFixProcesses.deleteFiles(wuCacheFolder)
Catch ex As Exception
MsgBox(ex.Message)
Dim wuCacheDirect As String = "C:\Windows\SoftwareDistribution\Download"
WebFixProcesses.deleteFolders(wuCacheDirect)
WebFixProcesses.deleteFiles(wuCacheDirect)
lblStatus.Text = "Press a button to fix problems"
End Try
End Sub
I must be doing something wrong here in the way I am setting up the batch file in conjunction with setting Me.TopMost = False or something like that. Any help on this is greatly appreciated!
EDIT:
Here is some additional info from my Form.Designer InitializeComponent() method on the NotifyIcon.
Private Sub InitializeComponent()
'Have omitted other controls
Me.readerNotify = New System.Windows.Forms.NotifyIcon(Me.components)
'readerNotify
'
Me.readerNotify.ContextMenuStrip = Me.ContextMenu
Me.readerNotify.Icon = CType(resources.GetObject("readerNotify.Icon"), System.Drawing.Icon)
Me.readerNotify.Text = "WebFix"
Me.readerNotify.Visible = True
End Sub
Public WithEvents readerNotify As System.Windows.Forms.NotifyIcon

Causing a batch file to finish its operations, before continuing?

The following code will extract files modified today from the SourceDirectory and place them into the FilesExtracted folder, then the batch file will delete the rest of the files in the sourceDirectory. But after that is all done a brand new set of files will be copied from the OriginalTestFiles folder and put into the sourceDirectory, but its does not do it. Does anyone think that it could be because the batch files hasn't stopped its operations and is still deleting the files in the sourceDirectory, or is there another problem. Thank You all!
Imports System.IO
Public Class frmExtractionator
' Dim txtFiles1 As Control
Dim sourceDirectory As String = "F:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "F:\FilesExtracted"
Dim originalDirectory As String = "F:\OriginalTestFiles"
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
If (IO.File.GetLastWriteTime(currentFileLoc).ToString("MM/dd/yyyy") = DateTime.Now.ToString("MM/dd/yyyy")) Then
MessageBox.Show(currentFileLoc & " moved", "Moved Succesfully")
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
End If
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
System.Diagnostics.Process.Start("F:\poop.bat")
Try
Dim txtFiles2 = Directory.EnumerateFiles(originalDirectory)
For Each currentFileLoc2 As String In txtFiles2
Dim fileName = currentFileLoc2.Substring(originalDirectory.Length + 1)
File.Move(currentFileLoc2, Path.Combine(sourceDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class
You can get the process as a variable once you start it and wait for it to exit:
Dim theProcess As Process = Process.Start("F:\poop.bat")
theProcess.WaitForExit()
Try monitoring the Process for completion...
'Start the process.
Dim Proc = Process.Start("F:\poop.bat")
'Wait for the window to finish loading.
Proc.WaitForInputIdle()
'Wait for the process to end.
Proc.WaitForExit()
...

Move file in Windows-Service

This is my first time making a windows service app. I'm trying to move files from one folder to another using a windows service app. It'll do so every 10 seconds.
This is the code I'm using. It works when I use it on a windows form app but doesn't work when I use it on a windows-service app.
The code in the Timer1_Tick works if I use it in OnStart. But doesn't work in the timer.
Protected Overrides Sub OnStart(ByVal args() As String)
Timer1.Enabled = True
End Sub
Protected Overrides Sub OnStop()
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim FileToMove As String
Dim MoveLocation As String
Dim count1 As Integer = 0
Dim files() As String = Directory.GetFiles("C:\Documents and Settings\dmmc.operation\Desktop\Q8")
Dim pdfFiles(100) As String
For i = 0 To files.Length - 1
If Path.GetExtension(files(i)) = ".pdf" Then
pdfFiles(count1) = files(i)
count1 += 1
End If
Next
For i = 0 To pdfFiles.Length - 1
If pdfFiles(i) <> "" Then
FileToMove = pdfFiles(i)
MoveLocation = "C:\Documents and Settings\dmmc.operation\Desktop\Output\" + Path.GetFileName(pdfFiles(i))
If File.Exists(FileToMove) = True Then
File.Move(FileToMove, MoveLocation)
End If
End If
Next
End Sub
Windows.Forms.Timer won't work without a Form instantiated. You should be using System.Timers.Timer instead:
Private WithEvents m_timer As System.Timers.Timer
Protected Overrides Sub OnStart(ByVal args() As String)
m_timer = New System.Timers.Timer(1000) ' 1 second
m_timer.Enabled = True
End Sub
Private Sub m_timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles m_timer.Elapsed
m_timer.Enabled = False
'Do your stuff here
m_timer.Enabled = True
End Sub
I've also build a service that moves files that are dropped into a folder but I'm using the FileSystemWatcher. The FileSystemWatcher allows me to move the file when a new one is created, create an entry in a SQL Database and send an email notification when it's all done.
This is how I have setup the FileSystemWatcher
Set a folder to watch: watcher.Path = "C:\Folder to Watch"
Set the file type to watch: watcher.Filter = "*.pdf".
The type of event to watch and the Method that gets triggered: watcher.Created += new FileSystemEventHandler(OnChanged);
Lastly, I need to enable the event: watcher.EnableRaisingEvents = true;
Unfortunately, I have instances on a daily basis where the files do not get moved successfully. I get IO exceptions for file in use. The files get copied but the file in the destination folder is 0kb.
I'm trying to troubleshoot it and I've manage to debug remotely but I still haven't figured out what I am doing wrong.
The most common error I get is: Error: System.IO.IOException: The process cannot access the file 'fileName.pdf' because it is being used by another process.
this error does not make sense as the file did not exist prior to my service trying to move it...
Any further help would be appreciated.

Opening up process and grabbing window title. Where did I go wrong?

In my application I allow for the users to add a program from a open file dialog, and it then adds the item to a listview and saves the items location into the tag. So what I am trying to do is when the program in the listview is selected and the button is pressed, it starts a timer and this timer checks to see if the process is running, and if it isn't launches the process, and once the process is launched it gets the window title of the process and sends it to a textbox on another form.
EDIT:
The question is if anyone can see why it is not working, by this I mean starting the process, then when it's started closing the form and adding the process window title to a textbox on another form.
I have tried to get it working but I can't. I know that the process name it is getting is right I think my problem is to do with my for loop. Basically it isn't doing anything visible right now.
I feel like I am very close with my code and im hoping it just needs a couple minor tweaks. Any help would be appreciated. Sorry if my coding practices aren't that great, im pretty new to this.
**EDIT:I found solution. I added code to the button that enables my timer to execute the process. Also another problem was indeed the way it read the file, I had to use the replace function to remove the ".exe" from the filepath code.
EDIT 2 : A better solution has been posted by Mark Hall. I am now using his code as it has less chance for error.
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim s As String = ListView1.SelectedItems(0).Tag
Dim myFile As String = Path.GetFileName(s)
Dim mu As String = myFile.Replace(".exe", "").Trim()
Dim f As Process
Dim p As Process() = Process.GetProcessesByName(mu)
For Each f In p
If p.Length > 0 Then
For i As Integer = 0 To p.Length - 1
ProcessID = (p(i).Id)
AutoMain.Name.Text = f.MainWindowTitle
Timer1.Enabled = False
Me.Close()
Next
Else
ProcessID = 0
End If
If ProcessID = 0 Then
Process.Start(mu)
End If
Next
End Sub
What is happening is that you are looking for a Process that matches your parameters before you enter your For Each loop the Process array is empty so it never enters it, therefore you never start your process.
This is a very quick example that works:
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
Dim s As String = ListView1.SelectedItems(0).Tag.ToString
Dim myFile As String = Path.GetFileName(s)
Dim p As Process() = Process.GetProcessesByName(Path.ChangeExtension(myFile, Nothing))
Static started As Boolean
If p.Count > 0 Or started Then
If p.Length > 0 Then
For i As Integer = 0 To p.Length - 1
ProcessId = (p(0).Id)
AutoMain.Name.Text = p(0).MainWindowTitle
Timer1.Enabled = False
started = False
Timer1.Stop()
Me.Close()
Next
Else
ProcessId = 0
End If
Else
started = True
Process.Start(myFile)
End If
End Sub

How would I open a program within Visual Basic 2010?

How would I open a program within Visual Basic 2010? (Like running "Application.txt" from "C:\" within a Visual Basic project.
Public Class getfrom
Dim getfrom As String
Dim saveto As String
Dim download As Boolean
Function openRunt()
Dim myProcess As New Process()
Try
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.FileName = "C:\\Runt.exe"
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
Catch e As Exception
' do nothing.
End Try
Return False
End Function
Function setVariables()
' Download the file from..
getfrom = "http://sourceforge.net/projects/iforsm/files/iForsm.exe"
' Download the file to..
saveto = "C:\Runt.exe"
' Allow download..
download = True
Return False
End Function
Private Sub getfrom_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
setVariables()
If download = True Then
My.Computer.Network.DownloadFile(getfrom, saveto)
Dim fileExists As Boolean
fileExists = My.Computer.FileSystem.FileExists("C:\Runt.exe")
If fileExists = True Then
'System.Diagnostics.Process.Start("notepad.exe", "c:\Application.txt")
openRunt()
End If
Else
End
End If
'End
End Sub
End Class
If you mean opening the text file with the notepad program via your application then something like the following should do the trick.
System.Diagnostics.Process.Start("notepad.exe", "c:\Application.txt")
See: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx
You would use the ProcessStart mechanism, see the link below for a tutorial.
This is located within the System.Diagnostics namespace.
Thanks
Pete
Process Start Tutorial