Trouble with OnLoad Sub (Visual Basic) - vb.net

I have some trouble with declaring a default path file on startup.
Everytime I run the program, it's saying that pathFile is null.
Does someone know what I need to change in my code?
Imports System
Imports System.IO
Imports System.Text
Public Class GlobalVariables
Public Shared pathFile As String
End Class
Public Class Form1
Protected Overridable Sub OnLoad(e As EventArgs)
GlobalVariables.pathFile = My.Computer.FileSystem.SpecialDirectories.Desktop
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
' create or overwrite the file
Dim fs As FileStream = File.Create(GlobalVariables.pathFile)
' add text to file
Dim info As Byte() = New UTF8Encoding(True).GetBytes(rtbText.Text)
fs.Write(info, 0, info.Length)
fs.Close()
End Sub
End Class
Thanks in advance!
- Xaaf Code

Instead of trying to override OnLoad (which would be Overrides instead of Overridable), I would handle the load event:
Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles Me.Load
GlobalVariables.pathFile = My.Computer.FileSystem.SpecialDirectories.Desktop
End Sub
You could probably just set the value where pathFile is declared instead:
Public Class GlobalVariables
Public Shared pathFile As String = My.Computer.FileSystem.SpecialDirectories.Desktop
End Class

Related

Using threading in VB.net

I'm having trouble using threading in a VB.net application I'm writing. I have a really simple version here to illustrate the problem I'm having.
It works perfectly if I load my form and have the VNC control connect to my VNC server as a single thread application using this code:
Imports VncSharp
Imports System.Windows.Forms
Imports System.ComponentModel
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not RemoteDesktop1.IsConnected Then
Dim Host As String = "10.0.0.1"
RemoteDesktop1.Connect(Host)
End If
End Sub
End Class
In order to make the connection occur in the background, this is the code I've tried using the backgroundworker control. I followed the information in this article to handle referencing the controls on the form using an instance, but I still get an error when it tries to use the VNCSharp control (RemoteDesktop1) to connect to a VNC server at the line:
Instance.RemoteDesktop1.Connect(Host)
The error is:
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'RemoteDesktop1' accessed from a thread other than the thread it was created on.'
Here's the code:
Imports VncSharp
Imports System.Windows.Forms
Imports System.ComponentModel
Public Class Form1
'Taken from https://stackoverflow.com/questions/29422339/update-control-on-main-form-via-background-worker-with-method-in-another-class-v
Private Shared _instance As Form1
Public ReadOnly Property Instance As Form1
Get
Return _instance
End Get
End Property
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
_instance = Me
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
System.Threading.Thread.Sleep(1000)
If Not Instance.RemoteDesktop1.IsConnected Then
Dim Host As String = "10.0.0.1"
Instance.RemoteDesktop1.Connect(Host)
'Connect()
End If
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("BG1 complete")
End Sub
End Class
I figured it out - one part of the code in the post I linked to on threading held the answer: I needed to use Invoke() to reference the form RemoteDesktop control:
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
System.Threading.Thread.Sleep(1000)
If Not Instance.RemoteDesktop1.IsConnected Then
Me.Instance.Invoke(Sub()
Dim Host As String = "10.61.41.7"
Me.RemoteDesktop1.Connect(Host)
End Sub)
End If
End Sub
instead of just putting Instance.RemoteDesktop1.Connect(Host)

vb .net passing objects/variables through classes

I'm struggling with the solution of passing the variables through different classes in VB.
The goal is to run a Form to present the progress and other info (I made a BackgroundWorker inside Form1), while a different vb thread is doing the job.
I finished with the MainClass and myWrapper, which does not do the job in the Form1 window. I set the class WorkerArgs between them, to pass the arguments, but I can only create 2 different objects of WorkerArgs.
I need to pass the same WorkerArgs.startProgress value to Form1 Class... How to do it?
Public Class MainClass
Shared Sub Main()
Dim form1 As Form = New Form1
Dim myWrapper As WorkerArgs = New WorkerArgs
form1.Show()
myWrapper.startProgress = "start"
End Sub
End Class
Public Class WorkerArgs
Public startProgress As String
Public passPercentage As String
End Class
Public Class Form1
Public Sub OnLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim args As WorkerArgs
BackgroundWorker1.RunWorkerAsync(args)
End Sub
Public Sub bgw1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
System.Threading.Thread.Sleep(1000)
' Access variables through e
Dim args As WorkerArgs = e.Argument
' Do something with args
Dim str As String = args.startProgress
If str = "start" Then
MessageBox.Show(str)
End If
End Sub
[...]
End Class

Thread inside module and add value into me.texbox1

Have anyone idea why my code return "" inside my Textbox ? :-)
This i have in main Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim My_Thread as Threading.Thread
My_Thread = New Threading.Thread(AddressOf Module1.MyTest)
My_Thread.Start()
End Sub
And this in module1
Sub MyTest()
Dim TestingValue as string = "Test"
MainForm.Textbox1.Text = TestingValue
End sub
Invoke all time crash code and another try return "" inside texbox1 :-/
Create a Sub Class with public declarations to any object you want on MainForm, then pass the class as a parameter to the module. This would be a cleaner approach than passing the entire Form class instance. Then using the method that Jimi has suggested you can setyou textboxs without cross thread violation.
Public Class MainForm
Public Class PassToModule
Public TxBx1 As TextBox = MainForm.TextBox1
Public TxBx2 As TextBox = MainForm.TextBox2
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim PassToModule As New PassToModule
Dim My_Thread As Threading.Thread
My_Thread = New Threading.Thread(AddressOf MyTest)
My_Thread.Start(PassToModule)
End Sub
End Class
Module Module1
Dim FromMainForm As MainForm.PassToModule
Sub MyTest(PasToModule As MainForm.PassToModule)
FromMainForm = PasToModule
FromMainForm.TxBx1.BeginInvoke(New MethodInvoker(Sub()
FromMainForm.TxBx1.Text = "Test"
FromMainForm.TxBx2.Text = "Test"
End Sub))
End Sub
End Module

GetElementById with CefSharp

I'm trying to access to a website variable by it's ID in VB.net. The ID is "value", the data I'm trying to access is the stock price, and the website is linked in the code. I was using the built-in web browser with the next code:
Imports System.Xml
Imports System.Net
Public Class Bolsa
Public Sub New()
InitializeComponent()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
WebBrowser1.Navigate("https://www.ahorro.com/acnet/fichas/ficha_valor.acnet?isin=ES0113211835&marketCode=09&submarketId=09")
While Not WebBrowser1.ReadyState = WebBrowserReadyState.Complete
Application.DoEvents()
End While
Dim request As String = WebBrowser1.Document.GetElementById("value").InnerText
Dim s As String = request.Replace("<span>", Nothing)
Dim t As String = s.Replace("</span>", Nothing)
TextBox1.Text = t
End Sub
End Class
Now I'm using CefSharp plugin, because I need HTML5 support, but I cannot access the data, and I think the method is correct, I found it in the official site. The actual code:
Imports CefSharp.WinForms
Imports CefSharp
Imports System.Xml
Imports System.Net
Imports System.Treading
Imports System.Treading.Tasks
Public Class Bolsa
Private WithEvents WebClave As ChromiumWebBrowser
Dim cadena
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs)
InitializeComponent()
Dim settings As New CefSettings()
CefSharp.Cef.Initialize(settings)
WebClave = New ChromiumWebBrowser("https://www.ahorro.com/acnet/fichas/ficha_valor.acnet?isin=ES0113211835&marketCode=09&submarketId=09")
pANwEB.Controls.Add(WebClave)
End Sub
Private Sub WebClave_IsBrowserInitializedChanged(sender As Object, e As IsBrowserInitializedChangedEventArgs) Handles WebClave.IsBrowserInitializedChanged
If e.IsBrowserInitialized Then
cadena = WebClave.EvaluateScriptAsync("document.getElementById('value').innerHTML")
TextBox1.Text = cadena
End If
End Sub
End Class
Any advice?
Thanks in advance.
[EDIT]: Added full original code
Imports CefSharp
Imports CefSharp.WinForms
Public Class Form1
Public WithEvents browser As ChromiumWebBrowser
Public Sub New()
InitializeComponent()
Dim settings As New CefSettings()
CefSharp.Cef.Initialize(settings)
browser = New ChromiumWebBrowser("https://google.com") With {
.Dock = DockStyle.Fill
}
Panel1.Controls.Add(browser)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cvbar = browser.EvaluateScriptAsync("document.getElementById(""lst-ib"").value;")
Dim response = cvbar.Result
If response.Success = True And response.Result <> "" Then
MsgBox(response.Result)
End If
End Sub
End Class

How to use GetTempPath in VB.net

I am not sure what I am doing wrong.
I viewed the Developer help page for this function but it doesn't have any examples
GetTempPath Help
Rght now I just want to print the temp directory to a msgbox to make sure I am doing it right. Then I will use it to write to a file
I am new to VB.net and am more familiar with C
Here is my code:
Imports System
Imports System.IO
Imports System.Collections
Public Class Form1
Public Shared Function GetTempPath() As String
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
...
...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim tempFolder As String
tempFolder = GetTempPath()
MsgBox(tempFolder)
End Sub
The ellipses just mean there is code there that is unnecessary for the question
You need to remove your Function declaration for GetTempPath. This is causing you to use your function, not the System.IO.Path version. Since Path.GetTempPath is a Shared Function, you call it via Path.GetTempPath().
Your code should look like:
Imports System
Imports System.IO
Imports System.Collections
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
...
...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim tempFolder As String
tempFolder = Path.GetTempPath()
MsgBox(tempFolder)
End Sub