How to create a notification in a text file when user starts a new application - vb.net

I am new at programming. I have been asked to create a code which will locally monitor and logs the name of the application to a text file whenever user starts or executes an application on their system. I don't have much idea about processes, can u help me please?
User stars any application, Log is saved in a text file with time and name of application.

You have to use WMI. Then you can monitor Win32_ProcessStartTrace to be notified when a process starts. Additionally you even can use Win32_ProcessStopTrace to be notified when a process stops.
Your code would look like that:
Public Shared Sub Main()
Dim startWatcher As ManagementEventWatcher = New ManagementEventWatcher(New WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"))
startWatcher.EventArrived += New EventArrivedEventHandler(startWatcher_EventArrived)
startWatcher.Start()
End Sub
Private Shared Sub startWatcher_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
Dim logString As String ="{0}: Process started: {1}".Format( Now.ToString(), e.NewEvent.Properties("ProcessName").Value)
Using sw As StreamWriter = File.AppendText(YourLogFile)
sw.WriteLine(logString)
End Using
End Sub

Related

VB.net Asynchronous call to Url with no response needed

I have a VB.Net page that needs to submit data to a url after a user clicks a button. I don't need any data back from the url, I just need to pass parameters to it and allow the user to continue to the next step without waiting for the url to do it's thing.
I've seen some similar posts for c# using UploadStringTaskAsync, but haven't been able to find a corresponding method for VB.net.
https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadstringtaskasync?view=net-6.0
I believe I can call the Async method from my existing nonasync methods as I don't need the response back. However, if there is a more elegant approach to do this please let me know.
Update with current code attempting to use thread:
Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
Dim thread As New Thread(AddressOf testSub)
thread.Start()
End If
End Sub
Sub testSub
Using WC As New WebClient WC.UploadString("https://someurl.com?parameter1=testing&parameter2=anothertest", "SOMEDATA")
End Using
End Sub
This runs but unfortunately does not appear to handle any of the parameters. When I post the url directly in the browser it runs as expected. I don't need to send any data other than the querystring as well so I'm not sure if that's breaking the uploadstring. However, when I run it via debugger I don't see any errors so long as I populate that string for the data with a value.
I might be misunderstanding though when the await call is needed. While I don't need any data back, the external url can take up to 5 minutes to process. I'm wondering if it's taking too long and timing out after that thread is started.
You could run it in its own thread.
Imports System.Net
Imports System.Threading
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
' Create a thread to run this in the background
Dim t As New Thread(
Sub()
Using WC As New WebClient
WC.UploadString("https://YOURURL", "YOURDATA")
End Using
End Sub
)
' Start the thread
t.Start()
End Sub
End Class

Reading Applications and services log

I want to read a custom event log which is stored under Applications and services log section in Windows Eventlog.
Unfortunately when calling the Log according to its naming properties I receive an error message that the log cannot be found.
Ulitmately I try read event details from events with a specific ID but first I need to able to access the log.
This is the code that I have so far:
Imports System
Imports System.Diagnostics.Eventing.Reader
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query As New EventLog("Logname as per Properties", System.Environment.MachineName)
Dim elEventEntry As System.Diagnostics.EventLogEntry
Dim nmbr As Integer = query.Entries.Count
MsgBox(nmbr)
End Sub
End Class
This is the structure in the eventlog (I want to read the blue highlighted part)
Anybody any idea how to determine the correct log name?
Thx & BR
Daniel
For many of the event logs, you need to use an EventLogQuery.
As an example, if you wanted to query the "Setup" event log to count the number of entries with an EventID of 1, you could do this:
Imports System.Diagnostics.Eventing.Reader
Module Module1
Sub Main()
Dim query As New EventLogQuery("Setup", PathType.LogName, "*[System/EventID=1]")
Dim nEvents = 0
Using logReader = New EventLogReader(query)
Dim eventInstance As EventRecord = logReader.ReadEvent()
While Not eventInstance Is Nothing
nEvents += 1
eventInstance = logReader.ReadEvent()
End While
End Using
Console.WriteLine(nEvents)
Console.ReadLine()
End Sub
End Module
You can see the names of the items to query by looking at the XML for an event in Windows Event Viewer.
The Using construct makes sure that the EventLogReader is properly disposed of after it's been used.
Further information: How to: Access and Read Event Information (from Microsoft).

How to open a specific file without user selection?

I currently have the following code which allows a user to select a file:
Private Sub FileToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles FileToolStripMenuItem1.Click
Dim result As DialogResult
Using filechooser As New OpenFileDialog()
result = filechooser.ShowDialog()
playFile = filechooser.FileName
End Using
End Sub
What I am trying to do is have the program open a file on its own without user selection. Basically, i have a generic file that needs to be used for the application regardless of who is using it, and I want it to be uploaded automatically upon the application being started.
You could just simply point your PlayFile directly by specifying the file
playFile = "C:\yourfile.txt" 'point to your file here

"make single instance application" what does this do?

in vb 2008 express this option is available under application properties. does anyone know what is its function? does it make it so that it's impossible to open two instances at the same time?
does it make it so that it's impossible to open two instances at the same time?
Yes.
Why not just use a Mutex? This is what MS suggests and I have used it for many-a-years with no issues.
Public Class Form1
Private objMutex As System.Threading.Mutex
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Check to prevent running twice
objMutex = New System.Threading.Mutex(False, "MyApplicationName")
If objMutex.WaitOne(0, False) = False Then
objMutex.Close()
objMutex = Nothing
MessageBox.Show("Another instance is already running!")
End
End If
'If you get to this point it's frist instance
End Sub
End Class
When the form, in this case, closes, the mutex is released and you can open another. This works even if you app crashes.
Yes, it makes it impossible to open two instances at the same time.
However it's very important to be aware of the bugs. With some firewalls, it's impossible to open even one instance - your application crashes at startup! See this excellent article by Bill McCarthy for more details, and a technique for restricting your application to one instance. His technique for communicating the command-line argument from a second instance back to the first instance uses pipes in .NET 3.5.
Dim _process() As Process
_process = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
If _process.Length > 1 Then
MsgBox("El programa ya está ejecutandose.", vbInformation)
End
End If
I found a great article for this topic: Single Instance Application in VB.NET.
Example usage:
Module ModMain
Private m_Handler As New SingleInstanceHandler()
' You should download codes for SingleInstaceHandler() class from:
' http://www.codeproject.com/Articles/3865/Single-Instance-Application-in-VB-NET
Private m_MainForm As Form
Public Sub Main(ByVal args() As String)
AddHandler m_Handler.StartUpEvent, AddressOf StartUp ' Add the StartUp callback
m_Handler.Run(args)
End Sub
Public Sub StartUp(ByVal sender As Object, ByVal event_args As StartUpEventArgs)
If event_args.NewInstance Then ' This is the first instance, create the main form and addd the child forms
m_MainForm = New Form()
Application.Run(m_MainForm)
Else ' This is coming from another instance
' Your codes and actions for next instances...
End If
End Sub
End Module
Yes you're correct in that it will only allow one instance of your application to be open at a time.
There is even a easier method:
Use the following code...
Imports System.IO
On the main form load event do the following:
If File.Exist(Application.StartupPath & "\abc.txt") Then
'You can change the extension of the file to what ever you desire ex: dll, xyz etc.
MsgBox("Only one Instance of the application is allowed!!!")
Environment.Exit(0)
Else
File.Create(Application.StartupPath & "\abc.txt", 10, Fileoptions.DeleteonClose)
Endif
This will take care of single instances as well as thin clients, and the file cannot be deleted while the application is running. and on closing the application or if the application crashes the file will delete itself.

Monitor process standard output that does not necessarily use CR/LF

My application periodically starts console programs with process.start. I need to monitor the output of the programs in "realtime".
For example, the program writes the following text to the console:
Processing.................
Every second or so a new dot appears to let the user know the program is still processing. However,... until the programm outputs a CR/LF, I am not able to retrieve the standard output of the program (while it is still running).
What can I do to get the output in realtime for - let's say - piping it into a database for instance in VB.NET?
what about sending output into a text file and reading that file every second?
I'm gutted since I did have a prototype application at home that did something like this. I'll see if I can fetch it. In the meantime have a look at this link:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
It shows how to redirect the output of applications to a custom stream e.g.
Public Class Form1
Private _p As Process
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim psi As New ProcessStartInfo()
psi.FileName = "C:\mydir.bat"
psi.RedirectStandardOutput = True
psi.UseShellExecute = False
_p = New Process()
_p.Start(psi)
tmrReadConsole.Enabled = True
End Sub
Private Sub tmrReadConsole_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrReadConsole.Tick
If _p IsNot Nothing Then
txtConsoleOutput.Text = _p.StandardOutput.ReadToEnd()
End If
End Sub
End Class
The above is a webform that has a timer which is used to poll the output stream of a console and get it's content into a textbox. It doesn't quite work (hence why I want to find my other app), but you get the idea.
Hope this helps.