terminate application using full path - vb.net

I want to terminate an application using the full file path via vb.net,so i am using this code snippet
Public Sub forceCopy()
Try
'Dim strDatabasePath As String = My.Computer.FileSystem.CombinePath(Application.UserAppDataPath, "LIC.mdf")
'Dim strdbLogPath As String = My.Computer.FileSystem.CombinePath(Application.UserAppDataPath, "LIC_log.ldf")
Dim strDatabasePath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC.mdf")
Dim strdbLogPath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC_log.ldf")
Dim path As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC.mdf")
Dim matchingProcesses = New List(Of Process)
For Each process As Process In process.GetProcesses()
For Each m As ProcessModule In process.Modules
If String.Compare(m.FileName, path, StringComparison.InvariantCultureIgnoreCase) = 0 Then
matchingProcesses.Add(process)
Exit For
End If
Next
Next
For Each p As Process In matchingProcesses
p.Kill()
Next
My.Computer.FileSystem.CopyFile(strDatabasePath, "c:\backup\LIC.mdf", True)
My.Computer.FileSystem.CopyFile(strdbLogPath, "c:\backup\LIC_log.ldf", True)
MessageBox.Show("Backup taken successfully")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I get an exception "Access Is Denied" .Any idea why?
EDIT: I get the error at this line : For Each m As ProcessModule In process.Modules

You'll need to wrap the If String.Compare(m.FileName, ...) block with Try/Catch. There are several fake and privileged processes whose FileName property you cannot access.
Killing SQL Server like this is otherwise a Really Bad Idea. Ask nicely with the ServiceController class. You will need UAC elevation to do so.

Only elevated processes can enumerate modules loaded by processes that you do not own.

Related

File.Copy not working - no error

Please take a look at this code. For some reason that I can't figure out, the File.Delete() line isn't getting fired and I'm not getting an error.
' hard-coded for testing
Dim path As String = "C:\Program Files (x86)\Test\Program\Program.exe"
Dim appDir As String = My.Application.Info.DirectoryPath
Dim iniPath As String = appDir & "\config.ini"
Dim outputPath As String = appDir & "\output.ini"
Dim textLine As String = ""
Dim reader = File.OpenText(iniPath)
Dim writer = New StreamWriter(outputPath)
' Read the lines in the ini file until the pathToExecutable line is found and write the path to that line
While (InlineAssignHelper(textLine, reader.ReadLine())) IsNot Nothing
If textLine.StartsWith("pathToExecutable=") Then
writer.WriteLine("pathToExecutable=" & path)
Else
writer.WriteLine(textLine)
End If
End While
reader.Dispose()
reader.Close()
writer.Dispose()
writer.Close()
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Return path
You stated that you are not getting an error, but if you don't implement exception handling, you're most probably getting errors and throwing them away (pun intended).
Use a try/catch around any of your System.IO.File operations, and even more, you can implement specific handles and catch specific exceptions.
Try
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Catch ioException As IOException
'The specified file is in use.
MessageBox.Show(ioException.Message)
Catch ex As Exception
'Some other error apart for file in use.
MessageBox.Show(ex.Message)
End Try
Ericosg's suggestion about using a try/catch lead me to the issue: I had the file open in a streamreader earlier in my code, but never closed it there.

FileExist not working vb.net

I really can not understand why the exception is triggered.
I created this code that performs some checks for the correctness of the license.
The function isittrial occurs if the trial software is creating a hidden file, this file is then checked with File.exist.
The problem is the following:
the file is created by isittrial but for some strange reason you enable the exception of file.exist, what can I do to fix it?
I really can not understand why it does not work.
isittrial() 'this function make the file to check
Dim percorsoCompleto As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
Try
If My.Computer.FileSystem.FileExists(directory) Then
Dim fileReader As String
Dim dire As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
fileReader = My.Computer.FileSystem.ReadAllText(directory,
System.Text.Encoding.UTF32)
Dim check = DeCryptIt(fileReader, "aspanet")
Dim datadecripted As String = DeCryptIt(Registry.GetValue("HKEY_CURRENT_USER\Software\cc", "end", ""), "aspanet")
If Date.Now < check And check <> datadecripted Then
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
Else
End If
Else
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
End If
Catch ex As Exception
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
'DeActivate()
'ForceActivation()
End Try
This line
If My.Computer.FileSystem.FileExists(directory) Then
seems to test for the existence of a file passing the name of a directory (or an empty string or whatever, we can see how this variable is initialized). In every case the result will be false.
Then your code jumps to an else block with the same error message of the exception fooling your perception of the error.
Try instead
Dim percorsoCompleto As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
percorsoCompleto = Path.Combine(percorsoCompleto, "Software", "cc.txt")
Try
If My.Computer.FileSystem.FileExists(percorsoCompleto) Then
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(percorsoCompleto,
System.Text.Encoding.UTF32)
.....
Notice that I have removed the path concatenation with a more fail safe call to Path.Combine

Shared Resource in Parallel.ForEach

How do I control access to a shared resource in a Parallel.ForEach loop? I am trying to download multiple files in parallel, and I want to capture information about downloads that fail, so that the user can re-attempt the download later. However, I am worried that if more than one download fails at the same time, the application will throw an exception because one thread will attempt to access the file while it is being written to by another.
In the code below, I would like to know how to control access to the file at RepeateRequestPath. A RequestSet is a list of strings that represent IDs of the resource I am trying to download.
Dim DownloadCnt As Integer = 0
Dim ParallelOpts As New ParallelOptions()
ParallelOpts.MaxDegreeOfParallelism = 4
Parallel.ForEach(RequestSets, ParallelOpts, Sub(RequestSet)
Try
DownloadCnt += 1
Dim XmlUrl As String = String.Format("{0}{1}{2}", "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=", String.Join(",", RequestSet), "&retmode=xml&rettype=abstract")
DownloadFile(XmlUrl, String.Format("{0}\TempXML{1}.xml", XMLCacheDir, DownloadCnt))
Catch ex As WebException
Using Response As WebResponse = ex.Response
Dim statCode As Integer = CInt(DirectCast(Response, HttpWebResponse).StatusCode)
MessageBox.Show(String.Format("Failed to retrieve XML due to HTTP error {0}. Please hit the 'Retrieve XML' button to re-run retrieval after the current set is complete.", statCode))
If Not File.Exists(RepeatRequestPath) Then
File.WriteAllLines(RepeatRequestPath, RequestSet)
Else
File.AppendAllLines(RepeatRequestPath, RequestSet)
End If
End Using
End Try
End Sub)
The usual way to protect a shared resource in VB.NET is to use SyncLock.
So, you would create a lock object before the Parallel.ForEach() loop:
Dim lock = New Object
and then you would use that inside the loop:
SyncLock lock
File.AppendAllLines(RepeatRequestPath, RequestSet)
End SyncLock
Also note that you can use AppendAllLines() even if the file doesn't exist yet, so you don't have to check for that.
You need to use a semaphore to control access to a shared resource. You want only one thread to access the error file at one time, so initialize the semaphore to only allow 1 thread in. Calling _pool.WaitOne should seize the semaphore, and then release it once it finishes creating/writing to the file.
Private Shared _pool As Semaphore
_pool = = New Semaphore(0, 1)
Dim DownloadCnt As Integer = 0
Dim ParallelOpts As New ParallelOptions()
ParallelOpts.MaxDegreeOfParallelism = 4
Parallel.ForEach(RequestSets, ParallelOpts, Sub(RequestSet)
Try
DownloadCnt += 1
Dim XmlUrl As String = String.Format("{0}{1}{2}", "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=", String.Join(",", RequestSet), "&retmode=xml&rettype=abstract")
DownloadFile(XmlUrl, String.Format("{0}\TempXML{1}.xml", XMLCacheDir, DownloadCnt))
Catch ex As WebException
Using Response As WebResponse = ex.Response
Dim statCode As Integer = CInt(DirectCast(Response, HttpWebResponse).StatusCode)
MessageBox.Show(String.Format("Failed to retrieve XML due to HTTP error {0}. Please hit the 'Retrieve XML' button to re-run retrieval after the current set is complete.", statCode))
_pool.WaitOne()
Try
If Not File.Exists(RepeatRequestPath) Then
File.WriteAllLines(RepeatRequestPath, RequestSet)
Else
File.AppendAllLines(RepeatRequestPath, RequestSet)
End If
Catch ex as Exception
'Do some error handling here.
Finally
_pool.Release()
End Try
End Using
End Try
End Sub)
svick's solution is almost right. However if you need to protect access to a shared variable you also need to declare your lock object as shared at class level.
This works correctly:
Friend Class SomeClass
Private Shared _lock As New Object
Private Shared sharedInt As Integer = 0
Sub Main()
SyncLock _lock
sharedInt += 1
End SyncLock
End Sub
End Class
If you use a non-shared lock object, synclock will protect the variable only from multiple accessing threads within the same instance, not across instances.

Why am I getting object reference not set error on script task connector?

I have an SSIS package (SQL Server 2005) that loops through a bunch of flat files in a folder. I need to wait until the source application has finished writing the file before I can open it in my flat file import task.
I have a For Each loop container and within it a script task to execute before the Data Flow Task.
When I try to create the success connector between the Script Task and the Data Flow Task I get this error:
Could not create connector. Object reference not set to an instance of
an object.
I get that something is being set to nothing, but I can't see it. I have DelayValidation set to true on both the Script Task and the Data Flow Task. What else am I missing?
I'm a C# guy so maybe I'm missing something obvious in the VB. Here's the script I poached from the interwebs:
Public Sub Main()
Dim strFileName As String = CType(Dts.Variables("FileName").Value, String)
Dim objFS As System.IO.FileStream
Dim bolFinished As Boolean = False
Do
Try
objFS = System.IO.File.Open(strFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
bolFinished = True
objFS.Close()
Catch ex As Exception
System.Threading.Thread.Sleep(1000)
End Try
Loop
If bolFinished Then
Dts.TaskResult = Dts.Results.Success
Else
Dts.TaskResult = Dts.Results.Failure
End If
End Sub
Milen k is more than right. It looks like you have an infinite loop which is opening a file several times until it breaks down.
You could change your code with the below suggested code. This will help you to get out of the infinite loop.
Your current code:
Do
Try
objFS = System.IO.File.Open(strFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
bolFinished = True
objFS.Close()
Catch ex As Exception
System.Threading.Thread.Sleep(1000)
End Try
Loop
Suggested code:
Do While(true)
Try
objFS = System.IO.File.Open(strFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
bolFinished = True
objFS.Close()
Exit Do
Catch ex As Exception
System.Threading.Thread.Sleep(1000)
End Try
Loop
Make sure that you have created a Flat File Source for your Data Flow task. If you do not have an existing one, create a temporary one which act as a place-holder for the file paths you feed it through the For Each loop.
From what I understand, you should be passing the path to each file that you will be importing to your Flat File Connection. This can easily be done by adding the variable generated in your For Each loop as an expression in the Expression property of your Flat File Connection.
UPDATE:
You need to set a condition in your Do ... Loop. For example: Loop While Not bolFinished. Look at this document for more information.

VB.NET / C# after finding installed Software names and application path how to find exe name

This code gets all software that has an Uninstall Entry and it app path. However, given I have the app path, I do not know the name of the main .exe of the software. What ways are there to find the main .exe of a found application?
'Declare the string to hold the list:
Dim Software As String = Nothing
'The registry key:
Dim SoftwareKey As String = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
Using rk As RegistryKey = Registry.LocalMachine.OpenSubKey(SoftwareKey)
'Let's go through the registry keys and get the info we need:
Dim j As Integer = 0
For Each skName As String In rk.GetSubKeyNames()
Using sk As RegistryKey = rk.OpenSubKey(skName)
Try
'If the key has value, continue, if not, skip it:
If Not (sk.GetValue("DisplayName") Is Nothing) And Not (sk.GetValue("InstallLocation") Is Nothing) And
Not (sk.GetValue("InstallLocation") = "") Then
Dim instanceremoved As Boolean = False
For Each item As ListViewItem In ListInstalled.Items
If item.SubItems.Item(1).Text = sk.GetValue("InstallLocation") Then
item.Remove()
instanceremoved = True
End If
Next
If instanceremoved = False Then
Dim itemAdd As ListViewItem = ListInstalled.Items.Add(sk.GetValue("DisplayName"))
itemAdd.SubItems.Add(sk.GetValue("InstallLocation"))
End If
End If
'No, that exception is not getting away... :P
Catch ex As Exception
MsgBox(ex)
End Try
End Using
j = j + 1
Next
End Using
The main Exe is not stored in the registry the uninstall command is stored in the UninstallString key.