Reading Applications and services log - vb.net

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).

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

How to create a notification in a text file when user starts a new application

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

How to find Roku IP + Port on network using SSDP search in VB.NET

I am trying to find my Roku TV on my network and apparently it needs some SSDP discovery based on Roku API help, however, I am unable to search for my device with any of the Nuget libraries.
I came across ssdpradar and was able to install the Nuget package for Visual Studio (VB.NET) through Visual Studio 2017 community release. However, I am not able to find any documentation on how to use it.
Any advice would be helpful.
Solution:
I found a solution but not with ssdpradar and rather RSSDP. After you add the nugget in your project you can use the following line of code to get all devices and then find the Roku location (ip+port) from that list.
Imports Rssdp
For Each founddevice As DiscoveredSsdpDevice In founddevices.Result
If founddevice.Usn.Contains("roku:ecp") Then
Rokulocation = founddevice.DescriptionLocation.ToString()
Exit For
End If
Next
I was able to successfully use a library called RokuDotNet recently. It's written in C# but you could load it as a project in your solution and reference it from VB.NET.
This is roughly the way I used it:
Imports RokuDotNet.Client
Public Class Form1
Private _discoveryClient As RokuDeviceDiscoveryClient
Public Sub New()
_discoveryClient = New RokuDeviceDiscoveryClient
AddHandler _discoveryClient.DeviceDiscovered, AddressOf DiscoveryHandler
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
_discoveryClient.DiscoverDevicesAsync()
End Sub
Private Async Sub DiscoveryHandler(sender As Object, e As DeviceDiscoveredEventArgs)
If InvokeRequired Then
BeginInvoke(New Action(Sub() DiscoveryHandler(sender, e)))
Return
End If
' Get the display name for the device (if the user entered one when setting it up)
Dim deviceInfo = Await e.Device.Query.GetDeviceInfoAsync
Dim name = deviceInfo.UserDeviceName
If String.IsNullOrEmpty(name) Then
name = deviceInfo.ModelName
End If
AddDevice(e.Device, name)
End Sub
Private Sub AddDevice(device As RokuDevice, name As String)
' Your code here
End Sub
End Class
You might want to add a try/catch around the await in that async function so it can show an error if there's a network problem.

How do I show a YouTuber's subscriber count in Visual Basic 2012?

I want to have a form that shows a youtuber's subscriber count. I already installed the API and I got this code:
Imports Google.GData.YouTube
Imports Google.GData.Client
Imports Google.GData.Extensions
Public Class Form1
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim subshelper As New Service
Dim feedUrl As String = "http://gdata.youtube.com/feeds/api/users/SkyDoesMinecraft"
Dim profile As ProfileEntry = subshelper.Get(feedUrl)
Dim subscount As Integer = profile.Statistics.SubscriberCount
Label1.Text = subscount
End Sub
End Class
I got this error though:
An unhandled exception of type 'Google.GData.Client.GDataRequestException' occurred in Google.GData.Client.dll
Additional information: Execution of request failed:
https://gdata.youtube.com/feeds/api/users/SkyDoesMinecraft
Can anyone help me here? Thank you!
If the only thing you care about is using the YouTube Data API to get the subscriber count for that one channel, then your best bet is probably just to make a generic HTTP request (without using any of the GData libraries) for
https://gdata.youtube.com/feeds/api/users/SkyDoesMinecraft?v=2&alt=json
and then using a JSON-parsing library to read the value of yt$statistics -> subscriberCount

"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.