How can I replicate this console action in VB.net with Webview2? - vb.net

So in edge I F12, goto console and type in SM.Player.token and receive a value back, not sure what you call this - a javascript variable or function?
I've got a program that does various interactions with this page and whilst I can manually go into the console, retrieve this value and enter it into a text box in the app it would be nice to be able to automate this part of the process.
I tried :
Dim token As String = ""
Dim script As String = "document.getElementById('SM.Player.token')"
token = "" & WebView2.ExecuteScriptAsync(script).ToString
But that just returns :
"System.Threading.Tasks.Task`1[System.String]"
Anyone able to point me in the right direction?

Related

How do I open a user's default browser open to the users homepage?

I am trying to figure out how to cause a Menu Strip item to open the active Windows accounts default browser to their homepage. I have tried Process.Start("about:blank") and for some reason this always opens Internet Explorer's about:blank page. (I have Google Chrome as my default browser with http://www.duckduckgo.com as its homepage on Windows 7 Pro.)
I know I can specify any URL to open the default browser, but how to get their selected homepage to open? I have found some articles based in C# that required looking into registry entries as to finding their chosen homepage per each browser. Would the process be the same/similar in VB.Net 2017 and how would I go about doing so? This is using VB.Net 2017 Community Edition and the project is a Windows.Forms desktop application.
The only way I found is to manually query the registry about the default command to handle the http protocol.
The first line of this code will return something like "C:\Program Files\Your Browser\browser.exe" -osint -url "%1", so you want to replace %1 by your landing page.
Then, if you want to use Process.Start with command line arguments, the first parameter will be the command and the second one the arguments.
Thus, we need to split the registry string between the command and the argument list. The regex will do this job.
I omited null checks and regex success for clarity.
Dim cmd = CStr(Registry.ClassesRoot.OpenSubKey("http\shell\open\command").GetValue(String.Empty))
cmd = cmd.Replace("%1","about:blank")
Dim r = new Regex("^""([^""]+)"" (.*)")
Dim m = r.Match(cmd)
Process.Start(m.Groups(1).Value, m.Groups(2).Value)
Found some clues here.
Dim readValue As String = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\
Associations\UrlAssociations\http\UserChoice", "Progid", Nothing).ToString
Will give an identifier for the current user's browser.
Dim path As String = My.Computer.Registry.GetValue("HKEY_CLASSES_ROOT\"
& readValue & "\shell\open\command", "", Nothing).ToString
Will return the run command with path.
Add some code to extract the EXE and run it without arguments, for example;
Dim DivArr As Char() = {Chr(34), "\"c}
'split into segments using quotes and back-slash seperators
Dim parts() As String = path.Split(DivArr)
'find first segment with period/full-stop
Dim Executable As String = Array.Find(parts, Function(x) (x.Contains(".")))
Process.start(Executable)
You may try this:
Process.Start("your_url_here eg. www.homepage.com etc.")
and, this will open with google chrome if its your default browser.

VB.NET Screenshot Application Window and Send

I have built an application that obtains details from a web service and displays them in a GUI for the agent to see.
I've had instances of problems occuring, sometimes an exception due to a change in how the data is received due to the provider and unfortunately no user lets me know this occurs, they just click through and pay no attention to the error.
I've built a custom form to capture the error and then email it to me with some details like username etc. etc.
I would ideally LIKE to capture the screen of the application as well, much like an ALT+PRINTSCRN so I can see what the application looks like at the time of error as well.
How possible is this?
Assuming WinForm, I've done this before:
Public Sub SaveAsImage(frm As Form)
'Dim fileName As String = "sth.png"
'define fileName
Dim format As ImageFormat = ImageFormat.Png
Dim image = New Bitmap(frm.Width, frm.Height)
Using g As Graphics = Graphics.FromImage(image)
g.CopyFromScreen(frm.Location, New Point(0, 0), frm.Size)
End Using
image.Save(fileName, format)
End Sub
When being called, it will capture the current screen in the area defined by frm and save to a file.

VBA: Follow Link in existing Session - Excel

We have a Excel-List of URLs with a lot of parameters.
The problem is: The first time you follow a link, you get redirected to a ADFS-Login, which cuts some of the Parameters, since they have a maximum URL-length.
My question: Is there a possibility to tell excel (be it via VBA or default) to use an existing Session?
I tried some shennenigans, for example via Chrome: Find the Window handle for a Chrome Browser or to take an existing IE-Window: http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window.html While I get an existing Window, it seems like it always gets redirected and the URL cut. Is there anyhow a possibility to make this?
Please try this and post feedback
Open Sheet1
In Column A, from row 2 create your list of URLS
Insert ActiveXControl Microsoft Web Browser WebBrowser1
Size the control to your needs
Insert Control Button outside the bounds of the browser
Change name of the button to NextButton
Open Code Editor (Alt+F11)
In Sheet1 place the below code
Dim currentURLRow As Integer ''Sheet level variable
Sub NextButton_Click()
On Error Resume Next
Dim url As String
''VBA evaluates second expression even when the first of OR is true. So on error resume next helps here
If currentURLRow = 0 Or Trim(Cells(currentURLRow, 1)) = "" Then
''First time or loop back
currentURLRow = 2
Else
currentURLRow = currentURLRow + 1
End If
On Error GoTo 0 ''reset error so you know of any (good) errors
url = Cells(currentURLRow, 1)
''Sheet1.WebBrowser1.Silent = True ''Uncomment this if you are seeing lot of script errors that you dont want to see
WebBrowser1.Navigate url
Debug.Print WebBrowser1.Document.body.InnerHTML ''' Here you can do magic if the urls you are navigating are serialisable to objects :)
End Sub
Now the first time you navigate to the site, you should be prompted for user name and password, on click of next, your session to saved.

TelnetExpect Reading Output from Stream in VB.NET

Good Morning,
I have been tasked with writing a program that locates the local port a MAC Address is registered to, and to do that I need to SSH and Telnet into Cisco devices and receive the output of the commands so I can parse it and decide what to do with the information.
So far I have the SSH connection and parsing done no problem thanks to Renci.SshNET. But I am having trouble with the Telnet, I set it up to use Telnetlib.dll and I know it works because I can do "show users" on the switch I'm connecting to and see that one of the vty lines are being occupied by my application. But in the application I'm writing all I get is the application freezing up, none of the buttons work, and I can't see the mouse when I hover over the window, so I'm guessing that the application isn't liking something at run-time.
The code I'm using, in VB.NET is:
Using client As TcpClient = New TcpClient(host, 23)
Dim tel As TelnetStream = New TelnetStream(client.GetStream)
Dim buff(client.ReceiveBufferSize) As Byte
Dim result As String
tel.SetRemoteMode(TelnetOption.Echo, False)
Dim exp As Expector = New Expector(tel)
exp.Expect("username: ")
exp.SendLine(username)
exp.Expect("password: ")
exp.SendLine(password)
exp.Expect(">")
tel.Read(buff, 0, buff.Length)
result = System.Text.Encoding.ASCII.GetString(buff)
MessageBox.Show(result)
End Using
Telnetlib.dll include the definitions for the Expector, SendLine, Expect, and TelnetStream.
I did some debugging and found that it freezes when it goes to execute the result = System.Text.Encoding.ASCII.GetString(buff)
command.
Thanks for any help.

Opening a file using impersonation

I have been searching the web looking for a way to open a WORD file from a secure network folder by impersonating a user who has access. The closest I've come to finding the answer was this from 2 years ago:
Impersonating in .net (C#) & opening a file via Process.start
Here is the code that I am using. When I set the arguments = LocalFile_Test, everything works perfectly because the user is accessing the local c:\ that is has access to. But when I set arguments = RemoteFile_Test, Word opens up a blank document which is the same effect as if I put garbage in the arguments. So it appears that it cannot find the file even though when I login with the user/domain/password that I specify in the properties below, I can find that exact file name and it is not empty. Does anything jump out at you right away? I appreciate your time.
Dim LocalFile_Test As String = "C:\New.docx"
Dim RemoteFile_Test As String = "\\Server1\Apps\File\New.docx"
Dim MyStartInfo As New System.Diagnostics.ProcessStartInfo
MyStartInfo.FileName = "C:\Program Files\Microsoft Office\Office12\WINWORD.exe "
MyStartInfo.Arguments = LocalFile_Test
MyStartInfo.LoadUserProfile = True
MyStartInfo.UseShellExecute = False
MyStartInfo.UserName = "specialuser"
MyStartInfo.Domain = "mydomainname"
MyStartInfo.Password = New System.Security.SecureString()
MyStartInfo.Password.AppendChar("p"c)
MyStartInfo.Password.AppendChar("a"c)
MyStartInfo.Password.AppendChar("s"c)
MyStartInfo.Password.AppendChar("s"c)
Process.Start(MyStartInfo)
My understanding is that you are trying to get a password protected file from a server, and when you do process start, it just opens up a blank word doc. I think the error is how you are trying to get the file, I think you have to map the actual physical path of the file on the server, like
System.Web.HttpContext.Current.Server.MapPath("\\Server1\Apps\File\New.docx")
From there, I am fairly certain, you need to create network credentials for the user like
System.Net.NetworkCredential=New NetworkCredential(userName:=, password:=)
Finally, once that is done, you can either write the file, or transmit the file like so...
System.Web.HttpContext.Current.Response.TransmitFile(file name)
System.Web.HttpContext.Current.Response.WriteFile(file name)
Then,once you get the file, you can try to open it with process start.
Hope that helps, let me know if what I said doesn't work.