How to find Roku IP + Port on network using SSDP search in VB.NET - 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.

Related

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

vb.net Parameters Startup Form not hiding?

I am creating a application to be used with a touch panel device. The touch panel device comes with a standard windows OSK (On screen Keyboard). Whilst testing its been concluded that the standard OSK is to large and too complex for what we need it in. So I have built my own OSK. some of the feilds though only requier numeric inputs so I though of futher simplifying the process by creating a new form which hosts a numeric pad. so far this is all working. the idea is then to have the app which ask for diffrent inputs then to trigger the OSK application, say that the user wants to enter a phonenumber in one textbox I then want to start the OSK app using a parameter that trigers the OSK to start the NumericForm form first... this too I have working but the thing I can't get right is to hide the AlphabetForm I have tried the following method but am a little stumpt on how to get this right
In short its the Me.hide which isnt working as expected?
Private Sub AlphabetForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
#Region "Recive startup parameters (if any)"
Try
Dim OSKParameters As String = Command()
If OSKParameters = "OSKNUM" Then
NumericForm.Show()
Me.Hide()
Else
ShiftSelect = 0
End If
Catch ex As Exception
'Do nothing
End Try
#End Region
End Sub
Three possible setups, as described in comments:
► Using the Application Framework, override OnStartup and set Application.MainForm to a Form object determined by a command-line argument:
To generate ApplicationEvents.vb, where Partial Friend Class MyApplication is found, open the Project properties, Application pane, click the View Application Events Button: it will add the ApplicationEvents.vb file to the Project if it's not already there.
Imports Microsoft.VisualBasic.ApplicationServices
Partial Friend Class MyApplication
'[...]
Protected Overrides Function OnStartup(e As StartupEventArgs) As Boolean
Application.MainForm = If(e.CommandLine.Any(
Function(cmd) cmd.Equals("OSKNUM")), CType(NumericForm, Form), AlphabetForm)
Return MyBase.OnStartup(e)
End Function
'[...]
End Class
► Disabling Application Framework, to start the Application from Sub Main().
In the Project->Properties->Application pane, deselect Enable application framework and select Sub Main() from the Startup form dropdown.
If Sub Main() doesn't exist yet, it can be added to a Module file. Here, the Module is named Program.vb.
Module Program
Public Sub Main(args As String())
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(True)
Dim startForm as Form = If(args.Any(
Function(arg) arg.Equals("OSKNUM")), CType(New NumericForm(), Form), New AlphabetForm())
Application.Run(startForm)
End Sub
End Module
► If the OSK can be moved to UserControls, similar to what jmcilhinney suggested, run the default container Form and select the UserControl to show using the same logic (inspecting the command-line arguments):
Public Class AlphabetForm
Public Sub New()
InitializeComponent()
Dim args = My.Application.CommandLineArgs
Dim uc = If(args.Any(
Function(arg) arg.Equals("OSKNUM")), CType(New NumericUC(), UserControl), New AlphabetUC())
Me.Controls.Add(uc)
uc.BringToFront()
uc.Dock = DockStyle.Fill
End Sub
End Class

How to Open console in VB

I currently have a console application by using the setting illustrated in the image bellow. However Now I wish to open multiple forms with the console so I'm wondering if I can somehow open multiple forms or open the console within a Windows Forms Application
#tinstaafl can you share this extra programming or a link to a
solution. Thanks
Here's a couple of links:
Console and WinForm together for easy debugging
Console Enhancements
Here's a conversion of the first one. You'll need a form with a checkbox name "CheckBox1":
Imports System.Runtime.InteropServices
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
Win32.AllocConsole()
Console.WriteLine("Done!")
Else
Win32.FreeConsole()
End If
End Sub
End Class
Public Class Win32
<DllImport("kernel32.dll")> Public Shared Function AllocConsole() As Boolean
End Function
<DllImport("kernel32.dll")> Public Shared Function FreeConsole() As Boolean
End Function
End Class
Everytime you click the checkbox you show or hide the console. You can write to and read from the same as any console app.
Forms and Console applications are very different. So much so that generally speaking a process either needs to be a form or console application. Forms applications are implemented with a message pump and console applications are command line drive. It is possible to a degree to run a form within a console, and vice versa, but generally not recommended. If you truly need both I would highly encourage you to use 2 processes.
If you could elaborate a bit more on your use case we may be better able to help you out.
So this is very cool. In the designer just add a checkbox using the Toolbox common controls.
Then double click on the new "CheckBox1" and that will automatically insert this sub routine:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
End Sub
Then all you have to do is add this code:
If CheckBox1.Checked Then
Win32.AllocConsole()
Console.WriteLine("Done!")
Else
Win32.FreeConsole()
End If
When you run your windows form program and check the box it will automatically open the window and KEEP it open until you uncheck the box.
Add this class to the bottom of your program:
Public Class Win32
<DllImport("kernel32.dll")> Public Shared Function AllocConsole() As Boolean
End Function
<DllImport("kernel32.dll")> Public Shared Function FreeConsole() As Boolean
End Function
End Class
And be sure to add the Imports statement at the top
Imports System.Runtime.InteropServices
If you want to open a console window to interact with and when you close the console, that action won't terminate your windows program then you can add these two lines of code:
Dim myProcess As Process
myProcess = Process.Start("cmd.exe")

VB.NET DownloadDataAsync:

I am having the worst trouble getting around a bug, and am hoping that I can get some advice on this site. In short, I am trying to make an asynchronous web service call from my VB.NET application. But my "client_DownloadDataCompleted" callback is NEVER being called when the download is complete.
Here is my complete code:
Public Sub BeginAsyncDownload(ByVal Url As String)
Dim waiter As System.Threading.AutoResetEvent = New System.Threading.AutoResetEvent(False)
Dim client As WebClient = New WebClient()
'client_DownloadDataCompleted method gets called when the download completes.
AddHandler client.DownloadDataCompleted, AddressOf client_DownloadDataCompleted
Dim uri As Uri = New Uri(Url)
Downloading = True 'Class variable defined elsewhere
client.DownloadDataAsync(uri, waiter)
End Sub
Private Sub client_DownloadDataCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
MessageBox.Show("Download Completed")
Downloading = False
Debug.Print("Downloaded")
End Sub
Again, the client_DownloadDataCompleted method is never being called. I have also tried using the method:
Private Sub client_DownloadDataCompleted(ByVal sender As Object, ByVal e As DownloadDataCompletedEventArgs)
With no luck. What I really need is that "Downloading" variable to be switched off when the download is complete.
Thanks in advance!
Brett
The client (Webclient) should be declared outside the BeginAsyncDownload subroutine, so it has a form/class level visibility. Please refer to the following code:
Public Class Form1
Dim client as New WebClient()
Private Sub BeginAsyncDownload(ByVal Url As String)
AddHandler client.DownloadDataCompleted, AddressOf client_DownloadDataCompleted
Dim uri As Uri = New Uri(Url)
Downloading = True 'Class variable defined elsewhere
client.DownloadDataAsync(uri, waiter)
End Sub
Private Sub client_DownloadStringCompleted(ByVal sender As Object, ByVal e As System.Net.DownloadStringCompletedEventArgs)
MessageBox.Show("Download Completed")
Downloading = False
Debug.Print("Downloaded")
End Sub
This is a tough one. I spent a little time on this and wasn't able to figure out why it wasn't getting called, sorry.
If you aren't able to get this to work, I have some code on CodePlex that includes a WebHelper class that might help you. I tried to make it as easy to use as WebClient but with all the power of HttpWebRequest.
The project is called BizArk. I wrote it just as a repository of code for myself. Feel free to just use the bits you want, I don't have any particular interest in how the code is used (as long as it's not used for evil :).
In what context are you invoking the webclient? WebClient will pick up your SynchronizationContext.Current and post its completion callback to it.
If you are using WinForms and your UI thread is blocked it will never be able to process your callback.

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