Unable to enumerate the process modules - vb.net

I was trying to make a file unlocker which get process which using the file and get it killed to make it able to be deleted. It was okay when my targeted file is a WMP file. But I can't get it work when it comes to dll and iso. I got the problem on this line:
Which is used to get the process name. Any help is appreciated.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnShow.Click
Dim files As New List(Of String)
files.Add(OpenFileDialog1.FileName)
Dim Processes As List(Of Process) = Util.GetProcessesUsingFiles(files)
RichTextBox1.AppendText(vbCrLf & "Processes that using the file is:")
For Each p As Process In Processes
TextBox1.Text = (Path.GetFileName(p.MainModule.FileName))
TextBox1.Text = TextBox1.Text.Replace(".exe", "")
Next
Timer1.Start()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnKill.Click
If TextBox1.Text = ("Nothing") Then
MsgBox("No proccess is using that file.")
ElseIf MsgBox("Proccess(es) killed") Then
End If
For Each p As Process In System.Diagnostics.Process.GetProcessesByName(Path.GetFileName(TextBox1.Text))
Try
p.Kill()
' possibly with a timeout
p.WaitForExit()
' process was terminating or can't be terminated - deal with it
Catch winException As Win32Exception
' process has already exited - might be able to let this one go
Catch invalidException As InvalidOperationException
End Try
Next

I've already got the solution. Just add Try..Catch..

Related

Locking computer drive using VB.net

I want to create a project through which I should be able to first see my drives and then select one of them to programically lock them.
Is it possible ?
If so please answer
You can get your devices with DriveInfo.GetDrives().
How do you want to lock them? If you want to encode a folder, look at https://stackoverflow.com/a/2302028/3905529
To lock a device or folder withouth encrypting is not reliable because in this case the data are not locked at another pc.
I tested the code below extracted from http://www.mindfiresolutions.com/How-to-Lock-And-Unlock-a-Folder-through-Code-in-VBNET-2310.php. First you have to provide a way to choose the directory you want to lock, in the case shown, a folderbrowserdialog was used.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnBrowse.Click
Try
If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
TextBox1.Text = FolderBrowserDialog1.SelectedPath
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Then I created two buttons to lock and unlock the directory whose path was written in a textbox previously by the function above.
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles btnLock.Click
Dim fs As FileSystemSecurity = File.GetAccessControl(TextBox1.Text)
fs.AddAccessRule(New FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny))
File.SetAccessControl(TextBox1.Text, fs)
End Sub
Private Sub btnUnlock_Click(sender As System.Object, e As System.EventArgs) Handles btnUnlock.Click
Dim fs As FileSystemSecurity = File.GetAccessControl(TextBox1.Text)
fs.RemoveAccessRule(New FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny))
File.SetAccessControl(TextBox1.Text, fs)
End Sub
The first one locks the directory and the other unlocks it.

Handle global exceptions in VB

Hello I have this project experiencing some problems with what is supposed to be my codes for the "problem" handler.
Public Event UnhandledException As UnhandledExceptionEventHandler
Private Sub form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
AddHandler currentDomain.UnhandledException, AddressOf MyHandler
End Sub
Sub MyHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)
Dim e As Exception = DirectCast(args.ExceptionObject, Exception)
Using sw As New StreamWriter(File.Open(myFilePath, FileMode.Append))
sw.WriteLine(Date.now & e.toString)
End Using
MessageBox.Show("An unexcpected error occured. Application will be terminated.")
Application.Exit()
End Sub
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
Throw New Exception("Dummy Error")
End Sub
I'm trying to globally catch all exceptions and create logfile during runtime, which works fine in the debugger(exception handling and textfile writing) but cannot catch any unhandled exceptions after I build it in the setup project and Installed into a machine. What am I missing? Do I need to include additional components to my setup project? Help would be greatly appreciated
There is already a way to handle exceptions for the entire application. Embedding the handler in a form means they would only be caught and logged if and while that form was open.
Go to Project -> Properties -> Application and click the "View Application Events" button at/near the bottom.
This will open ApplicationEvents.vb.
Select (MyApplicationEvents) in the left menu; and UnhandledException in the right. This opens an otherwise typical event handler to which you can add code:
Private Sub MyApplication_UnhandledException(sender As Object,
e As ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim myFilePath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"badjuju.log")
Using sw As New StreamWriter(File.Open(myFilePath, FileMode.Append))
sw.WriteLine(DateTime.Now)
sw.WriteLine(e.Exception.Message)
End Using
MessageBox.Show("An unexcpected error occured. Application will be terminated.")
End
End Sub
This will not catch exceptions while the IDE is running because VS catches them first so you can see them and fix them.

Read/Compile vb.net code dynamically from text file

I am trying to read and compile code from a text file. I have done some of its portion but feeling difficulties when trying to add controls to the Form. Kindly guide me. I am attaching code.
Public Class Form1
Sub Execute()
' Creates object of the compiler
Dim objCodeCompiler As System.CodeDom.Compiler.ICodeCompiler = New VBCodeProvider().CreateCompiler
'References/Parameters.
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
objCompilerParameters.ReferencedAssemblies.Add("System.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll")
objCompilerParameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
'Compiles in memory.
objCompilerParameters.GenerateInMemory = True
'Runs the source code.
'You can use resources, textbox's or even the settings, up to you! :D
'Dim strCode As String = TextBox1.Text
'Compiler Results
'Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, strCode)
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromFile(objCompilerParameters, "H:\VB project\LE21 - CodeDom - Run code from Textbox\LE21 - CodeDom - Run code from Textbox\LE21 - CodeDom - Run code from Textbox\file.txt")
'If an Error occurs
If objCompileResults.Errors.HasErrors Then
MsgBox("Error: Line>" & objCompileResults.Errors(0).Line.ToString & ", " & objCompileResults.Errors(0).ErrorText)
Exit Sub
End If
'Creates assembly
Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly
Dim objTheClass As Object = objAssembly.CreateInstance("MainClass")
If objTheClass Is Nothing Then
MsgBox("Can't load class...")
Exit Sub
End If
'Trys to excute
Try
objTheClass.GetType.InvokeMember("ExecuteCode",
System.Reflection.BindingFlags.InvokeMethod, Nothing, objTheClass, Nothing)
Catch ex As Exception
MsgBox("Error:" & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Runs the source code from textbox1.
Execute()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim p As New Form2
p.Text = "hahahahah"
p.Show()
End Sub
End Class
"Type Form2 is not defined"
That's because you haven't defined it. You may be dynamically loading and compiling some file which contains code which does define it. But the compiler has no way of knowing that at compile time. Being a statically typed system, the compiler needs to know about all of the types you're using when it compiles the code.
If you're dynamically loading class definitions from a file, then you also need to dynamically invoke those class definitions. That's going to involve a lot of reflection and CodeDOM and whatnot. It's not going to be pretty, and it's definitely not going to have compile-time type checking. (And it's going to be very "stringly typed" in the sense that instead of creating an instance of Form2 you're going to be requesting from reflection to create an instance of "Form2" and hoping for the best.) So you're going to want to put in a lot of error handling for things like, for example, classes which don't exist.

Using Background Worker VB.NET

I have to show many transaction on any table. It takes so much long time to process.
I want to use a background process in visual basic 2010, but it always give an error message like this "Cross thread operation detected". I have try so many ways that i found in the internet, but still can't find what the problem is.
Please help me about how to fix this problem.
This is my code :
Private Sub CHK_A_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CHK_A.CheckedChanged
Disabled()
P_Panel.Visible = True
B_Worker.RunWorkerAsync()
End Sub
Private Sub BTN_Search_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTN_Search.Click
USP_Select_Registration()
End Sub
Private Sub B_Worker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles B_Worker.DoWork
Threading.Thread.Sleep(25)
USP_Select_Registration()
End Sub
Private Sub B_Worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles B_Worker.RunWorkerCompleted
P_Panel.Visible = False
End Sub
This one is my store procedure
Public Sub USP_Select_Registration()
Dim Con As New SqlConnection(SQLCon)
Try
Con.Open()
Dim Cmd As New SqlCommand("USP_Select_Registration", Con)
Cmd.CommandType = CommandType.StoredProcedure
Cmd.Parameters.Add("#Check", SqlDbType.Bit).Value = CHK_A.EditValue
Cmd.Parameters.Add("#Month", SqlDbType.Int).Value = CBO_Month.SelectedIndex + 1
Cmd.Parameters.Add("#Year", SqlDbType.Int).Value = SPE_Year.EditValue
Cmd.Parameters.Add("#Search", SqlDbType.VarChar, 150).Value = TXT_Search.Text
DS_Registration.Tables("MST_Registration").Clear()
Dim Adt As New SqlDataAdapter(Cmd)
Adt.Fill(DS_Registration.Tables("MST_Registration"))
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
Finally
Con.Close()
End Try
End Sub
I think you get error because inside of USP_Select_Registration you trying to read values from form control's. Which was created by another thread.
RunWorkComleted executes in the same thread where Backgroundworker was created, thats why code P_Panel.Visible = False will executes normally.
But DoWork executes on the another thread.
And when you tried to access some forms controls to read values
TXT_Search.Text - it raise error
You can pass you searching parameters to BackgroundWorker, but you need to add parameters to USP_Select_Registration function.
For example:
Private Sub USP_Select_Registration(searchText as String)
'Your code here
End Sub
Then where you start BackgroundWorker:
B_Worker.RunWorkerAsync(TXT_Search.Text)
And
Private Sub B_Worker_DoWork(ByVal sender As Object,
ByVal e As DoWorkEventArgs) Handles B_Worker.DoWork
Threading.Thread.Sleep(25)
USP_Select_Registration(e.Argument)
End Sub
In your case you need to pass more then one parameter.
So you can create some structure/class or whatever object where you can keep all needed values. And pass that object to RunWorkerAsync

How can I do something after Process.Start("explorer.exe", OpenFolder)

I have the following code that simply opens up a folder with txt files.
Private Sub OpenTabpageTextFolderToolStripMenuItem_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles OpenTabpageTextFolderToolStripMenuItem.Click
Dim OpenFolder = (RootDrive & "QuickEmailer2\TabTxt")
Process.Start("explorer.exe", OpenFolder)
End Sub
The user then edits a txt file, and closes.
I would like to call my refresh code and make use of the changes to the txt file, but if I put the call after process.start, it runs without waiting?
I could use code to do these edit, but there are 80 files to choose from and they only need edit them once (or twice) when setting up the program for the first time.
I am sure a bit of code that says:
Private Sub OpenTabpageTextFolderToolStripMenuItem_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles OpenTabpageTextFolderToolStripMenuItem.Click
Dim OpenFolder = (RootDrive & "QuickEmailer2\TabTxt")
Process.Start("explorer.exe", OpenFolder)
'**I will hang on here while you do your stuff, then I will continue...**
Call RefreshfromAllTxtFiles()
End Sub
alternative solution: use 2 buttons/steps to setting up the program for the first time!
button/step #1: open setup files
button/step #2: setup files modified... PROCEED!
Along the lines of Steve's comment, you can use a FileSystemWatcher to monitor changes to the directory. Something like this can get you started:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim fsw As FileSystemWatcher
fsw = New System.IO.FileSystemWatcher()
'this is the folder we want to monitor
fsw.Path = "c:\temp"
fsw.NotifyFilter = IO.NotifyFilters.Attributes
AddHandler fsw.Changed, AddressOf IveBeenChanged
fsw.EnableRaisingEvents = True
End Sub
Private Sub IveBeenChanged(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
'this displays the file that changed after it is saved
MessageBox.Show("File " & e.FullPath & " has been modified")
' you can call RefreshfromAllTxtFiles() here
End If
End Sub