I'm very new to .NET. I am trying to use a code example from the first person that posted a response, here: Connect to remote MySQL database using VB.NET 2010
I would like to instantiate the MySqlVB model object but when I add the following code into the controller, I get a not found error. I don't know how to resolve this.
The error is: Warning 1 Namespace or type specified in the Imports 'MySql.Data.MySqlClient' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
What I need is to run a MySQL query and to return the dataset to the controller. Can someone show me how to do this, please?
I'm using VB 2010 Express to do this.
This is the controller
Public Class Form1
Private Sub PrintBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintBtn.Click
Dim data As New MySqlVB
With data
If .Connection Then
MessageBox.Show("Database Conneted.")
Else
MessageBox.Show(.ErrorMessage)
End If
End With
End Sub
End Class
And this is my model object
Imports MySql.Data.MySqlClient
Public Class MySqlVB
Private _connection As New MySqlConnection
Private _errormessge As String
Private _servername As String = "xxx.xxx.xxx.xxx"
Private _databasename As String = "testdb"
Private _userid As String = "theuser"
Private _password As String = "thepass"
Public WriteOnly Property ServerName() As String
Set(ByVal value As String)
_servername = value
End Set
End Property
Public WriteOnly Property DatabaseName() As String
Set(ByVal value As String)
_databasename = value
End Set
End Property
Public WriteOnly Property UserID() As String
Set(ByVal value As String)
_userid = value
End Set
End Property
Public WriteOnly Property Password() As String
Set(ByVal value As String)
_password = value
End Set
End Property
Public ReadOnly Property ErrorMessage() As String
Get
Return _errormessge
End Get
End Property
Public Function Connection() As Boolean
Try
_connection.ConnectionString = "Server=" & _servername & ";Port=3306;Database=" & _databasename & ";User ID=" & _userid & ";Password=" & _password & ""
_connection.Open()
If _connection.State = ConnectionState.Open Then
_connection.Close()
Return True
End If
Catch ex As Exception
_errormessge = ex.Message
Return False
End Try
End Function
End Class
Assuming you have fixed your reference to MySql.Data.MySqlClient I think your class could use some work.
Public Class DataAccess
Private ConnectionString As String
Public Sub New(UserName As String, Password As String)
Dim builder As New MySqlConnectionStringBuilder With {
.Server = "xxx.xxx.xxx.xxx",
.Database = "testdb",
.UserID = UserName,
.Password = Password
}
ConnectionString = builder.ConnectionString
Debug.Print(ConnectionString) 'just to see what the builder created
End Sub
Public Function TestConnecion() As Boolean
Using cn As New MySqlConnection(ConnectionString)
Try
cn.Open()
Catch ex As Exception
Debug.Print(ex.Message) 'just to see what is wrong with connection
Return False
End Try
End Using
Return True
End Function
Public Function GetData() As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnectionString)
Using cmd As New MySqlCommand("Select * From SomeTable")
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
End Class
Assuming you have a DataGridView to display data and 2 text boxes for user id and password, you can use your class in your form like this.
Private Sub FillGrid()
Dim daClass As New DataAccess(txtUser.Text, txtPassword.Text)
Dim dt = daClass.GetData
DataGridView1.DataSource = dt
End Sub
Of course you will need to add error handling. Also you need to salt and hash passwords. Plain text passwords should never be stored.
I try for one week to provide a PHP application (client) and a VB.Net application (server) via text messages (JSON).
I must therefore open a socket server in VB.Net, read the client message and close the connection. Of course by managing connections from clients in separate threads since PHP may well send multiple queries simultaneously.
This is a trivial task in Java, as I usually do, but and a VB.Net I tried many solutions found on StackOverflow and CodeProject, but none is exactly what I want to achieve .
Finally I think I found something interesting !
Based on the post Writing a Simple HTTP Server in VB.Net from Patrick Santry, I have a functional class :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class Server
#Region "Declarations"
Private Shared singleServer As Server
Private Shared blnFlag As Boolean
Private LocalTCPListener As TcpListener
Private LocalPort As Integer
Private LocalAddress As IPAddress = GetIPAddress()
Private ServerThread As Thread
#End Region
#Region "Properties"
Public Property ListenPort() As Integer
Get
Return LocalPort
End Get
Set(ByVal Value As Integer)
LocalPort = Value
End Set
End Property
Public ReadOnly Property ListenIPAddress() As IPAddress
Get
Return LocalAddress
End Get
End Property
#End Region
#Region "Methods"
Private Function GetIPAddress() As IPAddress
With System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName())
If .AddressList.Length > 0 Then
Return New IPAddress(.AddressList.GetLowerBound(0))
End If
End With
Return Nothing
End Function
Friend Shared Function getServer(ByVal LocalPort As Integer, ByVal Optional LocalAddress As String = Nothing) As Server
If Not blnFlag Then
singleServer = New Server
If Not LocalAddress Is Nothing Then
Server.singleServer.LocalAddress = IPAddress.Parse(LocalAddress)
End If
If Not LocalPort = 0 Then
Server.singleServer.LocalPort = LocalPort
End If
blnFlag = True
Return Server.singleServer
Else
Return Server.singleServer
End If
End Function
Public Sub StartServer()
Try
LocalTCPListener = New TcpListener(LocalAddress, LocalPort)
LocalTCPListener.Start()
ServerThread = New Thread(AddressOf StartListen)
serverThread.Start()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Public Overloads Sub SendResponse(ByVal sData As String, ByRef thisSocket As Socket)
SendResponse(Encoding.UTF8.GetBytes(sData), thisSocket)
End Sub
Public Overloads Sub SendResponse(ByVal bSendData As [Byte](), ByRef thisSocket As Socket)
Dim iNumBytes As Integer = 0
If thisSocket.Connected Then
If (iNumBytes = thisSocket.Send(bSendData, bSendData.Length, 0)) = -1 Then
' socket error can't send packet
Else
' number of bytes sent.
End If
Else
' connection dropped.
End If
End Sub
Private Sub New()
' create a singleton
End Sub
Private Sub StartListen()
Do While True
' accept new socket connection
Dim mySocket As Socket = LocalTCPListener.AcceptSocket
If mySocket.Connected Then
Dim ClientThread As Thread = New Thread(Sub() Me.ProcessRequest(mySocket))
ClientThread.Start()
End If
Loop
End Sub
Private Sub ProcessRequest(ByRef mySocket As Socket)
Dim bReceive() As Byte = New [Byte](1024) {}
Dim i As Integer = mySocket.Receive(bReceive, bReceive.Length, 0)
Dim sRequest = Encoding.UTF8.GetString(bReceive)
Dim sResponse As String
sResponse = "Your message was : " & sRequest
SendResponse(sResponse, mySocket)
mySocket.Close()
End Sub
Public Sub StopServer()
Try
LocalTCPListener.Stop()
ServerThread.Abort()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
#End Region
End Class
It remains for me to process the request and generate the response in the processRequest method.
I am trying to run some vb.net code that indicates if i'm connected to the internet
If My.Computer.Network.IsAvailable Then
MsgBox("Computer is connected.")
Else
MsgBox("Computer is not connected.")
End If
This works fine if I'm connecting to a WiFi signal that doesn't require a login. If I connect to a public WiFi signal that I'm required to login/pay and I execute the code before completing this step it still tells me I'm connected (in theory yes but without paying/logging in I'm not)
Any ideas how set this up?
Thanks
You could check for an internet connection by trying to read Google.com:
Public Shared Function CheckForInternetConnection() As Boolean
Try
Using client = New WebClient()
Using stream = client.OpenRead("http://www.google.com")
Return True
End Using
End Using
Catch
Return False
End Try
End Function
Taken from: Here
I use this
Public Function HaveInternetConnection() As Boolean
Try
Return My.Computer.Network.Ping("www.google.com")
Catch
Return False
End Try
End Function
I create this class to track internet connection changes. This class can check the stable internet connections also (stable means, that the connection not change during N second). The class raise events, if the connection changes.
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Runtime.InteropServices.ComTypes
Imports System.Text
Imports System.Collections.Generic
Imports System.Linq
Imports System.Net.NetworkInformation
Imports System.Net
Public Enum InternetConnectionState
Connected
Disconnected
End Enum
Public Class NetworkConnections
Implements IDisposable
Public Shared Property CheckHostName As String = "www.google.com"
Public Property ConnectionStableAfterSec As Integer = 10
Private MonitoringStarted As Boolean = False
Private StableCheckTimer As System.Threading.Timer
Private IsFirstCheck As Boolean = True
Private wConnectionIsStable As Boolean
Private PrevInternetConnectionState As InternetConnectionState = InternetConnectionState.Disconnected
Public Event InternetConnectionStateChanged(ByVal ConnectionState As InternetConnectionState)
Public Event InternetConnectionStableChanged(ByVal IsStable As Boolean, ByVal ConnectionState As InternetConnectionState)
Public Sub StartMonitoring()
If MonitoringStarted = False Then
AddHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
MonitoringStarted = True
NetworkAddressChanged(Me, Nothing)
End If
End Sub
Public Sub StopMonitoring()
If MonitoringStarted = True Then
Try
RemoveHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
Catch ex As Exception
End Try
MonitoringStarted = False
End If
End Sub
Public ReadOnly Property ConnectionIsStableNow As Boolean
Get
Return wConnectionIsStable
End Get
End Property
<DllImport("wininet.dll")> _
Private Shared Function InternetGetConnectedState(ByRef Description As Integer, ByVal ReservedValue As Integer) As Boolean
End Function
Private Shared Function IsInternetAvailable() As Boolean
Try
Dim ConnDesc As Integer
Dim conn As Boolean = InternetGetConnectedState(ConnDesc, 0)
Return conn
Catch
Return False
End Try
End Function
Private Shared Function IsInternetAvailableByDns() As Boolean
Try
Dim iheObj As IPHostEntry = Dns.GetHostEntry(CheckHostName)
Return True
Catch
Return False
End Try
End Function
Public Shared Function CheckInternetConnectionIsAvailable() As Boolean
Return IsInternetAvailable() And IsInternetAvailableByDns()
End Function
Private Sub NetworkAddressChanged(sender As Object, e As EventArgs)
wConnectionIsStable = False
StableCheckTimer = New System.Threading.Timer(AddressOf ElapsedAndStable, Nothing, New TimeSpan(0, 0, ConnectionStableAfterSec), New TimeSpan(1, 0, 0))
If IsFirstCheck Then
If CheckInternetConnectionIsAvailable() Then
PrevInternetConnectionState = InternetConnectionState.Connected
RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Connected)
Else
PrevInternetConnectionState = InternetConnectionState.Disconnected
RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Disconnected)
End If
IsFirstCheck = False
Else
If CheckInternetConnectionIsAvailable() Then
If PrevInternetConnectionState <> InternetConnectionState.Connected Then
PrevInternetConnectionState = InternetConnectionState.Connected
RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Connected)
End If
Else
If PrevInternetConnectionState <> InternetConnectionState.Disconnected Then
PrevInternetConnectionState = InternetConnectionState.Disconnected
RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Disconnected)
End If
End If
End If
End Sub
Private Sub ElapsedAndStable()
If wConnectionIsStable = False Then
wConnectionIsStable = True
Dim hasnet As Boolean = CheckInternetConnectionIsAvailable()
RaiseEvent InternetConnectionStableChanged(True, IIf(hasnet, InternetConnectionState.Connected, InternetConnectionState.Disconnected))
End If
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
Try
RemoveHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
Catch ex As Exception
End Try
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Track changes on a form with 2 listbox. Important! The events are thread unsafe, that need to be handle with invoke method.
Imports System.Net.NetworkInformation
Imports System.Net
Public Class frmNetworkConnections
Private WithEvents conn As NetworkConnections
Delegate Sub AddToList1Callback(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
Delegate Sub AddToList2Callback(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn = New NetworkConnections
End Sub
Sub AddToList1(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
If Me.InvokeRequired = True Then
Dim d As New AddToList1Callback(AddressOf AddToList1)
Me.Invoke(d, ConnectionState, IsStable)
Else
ListBox1.Items.Add(Now & " - State: " & ConnectionState.ToString() & ", Stable: " & IsStable)
End If
End Sub
Sub AddToList2(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
If Me.InvokeRequired = True Then
Dim d As New AddToList2Callback(AddressOf AddToList2)
Me.Invoke(d, ConnectionState, IsStable)
Else
ListBox1.Items.Add(Now & " - State: " & ConnectionState.ToString() & ", Stable: " & IsStable)
ListBox2.Items.Add(Now & " - State: " & ConnectionState.ToString() & ", Stable: " & IsStable)
End If
End Sub
Private Sub conn_InternetConnectionStableChanged(IsStable As Boolean, ConnectionState As InternetConnectionState) Handles conn.InternetConnectionStableChanged
AddToList2(ConnectionState, IsStable)
End Sub
Private Sub conn_InternetConnectionStateChanged(ConnectionState As InternetConnectionState) Handles conn.InternetConnectionStateChanged
AddToList1(ConnectionState, False)
End Sub
Private Sub btnStartMonitoring_Click(sender As Object, e As EventArgs) Handles btnStartMonitoring.Click
btnStopMonitoring.Enabled = True
btnStartMonitoring.Enabled = False
conn.StartMonitoring()
End Sub
Private Sub btnStopMonitoring_Click(sender As Object, e As EventArgs) Handles btnStopMonitoring.Click
btnStopMonitoring.Enabled = False
btnStartMonitoring.Enabled = True
conn.StopMonitoring()
End Sub
End Class
The result is:
I use the stable connection changes.
If you dont want to track changes, only check the connection, you can use the CheckInternetConnectionIsAvailable() shared function.
You could use the Ping class to try to reach a host in the Internet. In order not to wait too long, you should set a timeout when using Send.
A good way to check if the user is connected to the internet is
If My.Computer.Network.Ping("www.google.com") Then
MsgBox("Computer is connected to the internet.")
End If
You can also use this code, however it's slower
Public Shared Function CheckForInternetConnection() As Boolean
Try
Using client = New WebClient()
Using stream = client.OpenRead("http://www.google.com")
Return True
End Using
End Using
Catch
Return False
End Try
End Function
***** Best *****
The best Code For it, it not make any bug or Any slow.
Button Or Timer .. Etc
Try
If My.Computer.Network.Ping("www.google.com") Then
Label1.Text = "Internet Founded"
End If
Catch ex As Exception
'' Else ''
Label1.Text = "No internet Acess"
End Try
At least hope you gave me that
"Question Answer", it the best solution .Thanks.
(you can try it out)
Try
Dim client = New Net.WebClient
client.OpenRead("http://www.google.com")
Label21.Text = "Internet : Connected"
Catch
Label21.Text = "Internet : Disconnected"
End Try
Use this code in vb.net 100% solved, you can use this code form loading.
I am using this code and is working very well:
Public Function IsConnectedToInternet() As Boolean
If My.Computer.Network.IsAvailable Then
Try
Dim IPHost As IPHostEntry = Dns.GetHostEntry("www.google.com")
Return True
Catch
Return False
End Try
Else
Return False
End If
End Function
My.Computer.Network.Ping gave me problems so I used this function
Public Function fVerificaConnessioneInternet() As Boolean
Dim objPing As New System.Net.NetworkInformation.Ping
Try
Return If(objPing.Send("www.google.it").Status = IPStatus.Success, True, False)
Catch
Return False
End Try
End Function
or you could use this, a little better function to use. this should help you out if you need a c# version
http://www.guideushow.com/code-snippet/function-to-check-if-you-can-connect-to-the-internet-vb-net-c/
Public Function IsConnectionAvailable() As Boolean
' Returns True if connection is available
' Replace www.yoursite.com with a site that
' is guaranteed to be online - perhaps your
' corporate site, or microsoft.com
Dim objUrl As New System.Uri("http://www.google.com/")
' Setup WebRequest
Dim objWebReq As System.Net.WebRequest
objWebReq = System.Net.WebRequest.Create(objUrl)
objWebReq.Proxy = Nothing
Dim objResp As System.Net.WebResponse
Try
' Attempt to get response and return True
objResp = objWebReq.GetResponse
objResp.Close()
objWebReq = Nothing
Return True
Catch ex As Exception
' Error, exit and return False
objResp.Close()
objWebReq = Nothing
Return False
End Try
End Function
I am trying to create a Crystal Report with my custom object as the datasource.
It all works great unless some of the object's properties have null values. In that case, I get the error:
Error number: 5
Exception has been thrown by the target of an invocation.
(Not much help!)
Here's a copy of my code showing one CrystalReportViewer getting correctly populated by an object with no null values and another CrystalReportViewer giving the error with an object with a null value.
Thanks for any help/advice!
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim cryRpt As New ReportDocument
'Verify the path to the Crystal Report's .RPT file:
Dim strReportPath As String = CurDir() & "\..\..\" & "rpt_report.rpt"
If Not IO.File.Exists(strReportPath) Then
Throw (New Exception("Unable to locate report file:" & vbCrLf & strReportPath))
End If
cryRpt.Load(strReportPath)
Dim reportArray1(0) As cls_object
reportArray1(0) = New cls_object()
reportArray1(0).iNumber = 99
reportArray1(0).strString = "Hello"
cryRpt.SetDataSource(reportArray1)
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
Dim reportArray2(0) As cls_object
reportArray2(0) = New cls_object()
'reportArray1(0).iNumber = 99 'this is commented out. this line is the only difference
reportArray1(0).strString = "Hello"
cryRpt.SetDataSource(reportArray2)
CrystalReportViewer2.ReportSource = cryRpt
CrystalReportViewer2.Refresh()
Catch ex As Exception
MsgBox("Error number: " & Err.Number & vbCrLf & Err.Description, MsgBoxStyle.Exclamation, Err.Source)
End Try
End Sub
End Class
Public Class cls_object
Protected _iNumber As Integer?
Protected _strString As String
Public Property iNumber() As Integer
Get
Return _iNumber
End Get
Set(ByVal value As Integer)
_iNumber = value
End Set
End Property
Public Property strString() As String
Get
Return _strString
End Get
Set(ByVal value As String)
_strString = value
End Set
End Property
Public Sub New()
End Sub
End Class
Your not using a DBNull, You are using the Of Nullable, which Crystal does not understand. Not sure when they will support this. See this link crystal-does-not-support-systemnullable
I have a Form (ClientGUI) that has a RichTextBox. What I want to do is to append text to this RichTextBox from a Sub located in another class (MyQuickFixApp). I know that the Sub works, because the debugger go through, but it doesn't append the text to my RichTextBox.
How do I do that ?
Thanks for you help !
ClientGUI.vb :
Imports QuickFix
Imports QuickFix.Transport
Imports QuickFix.Fields
Public Class ClientGUI
Dim initiator As SocketInitiator
Public Sub ClientGUI_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim filename As String = "Resources/initiator.cfg"
Dim settings As New SessionSettings(filename)
Dim myApp As New MyQuickFixApp()
Dim storeFactory As New FileStoreFactory(settings)
Dim logFactory As New FileLogFactory(settings)
initiator = New SocketInitiator(myApp, storeFactory, settings, logFactory)
End Sub
Public Sub ConnectToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ConnectToolStripMenuItem.Click
ToolStripDropDownButton1.Text = "Establishing connection..."
ToolStripDropDownButton1.Image = My.Resources.Connecting
initiator.Start()
End Sub
Public Sub DisconnectToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DisconnectToolStripMenuItem.Click
ToolStripDropDownButton1.Text = "Disconnecting..."
ToolStripDropDownButton1.Image = My.Resources.Disconnecting
initiator.Stop()
End Sub
End Class
MyQuickFixApp.vb :
Imports QuickFix
Imports QuickFix.Transport
Imports QuickFix.Fields
Public Class MyQuickFixApp
Inherits MessageCracker : Implements IApplication
Dim _session As Session = Nothing
Public Sub FromAdmin(message As Message, sessionID As SessionID) Implements IApplication.FromAdmin
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("IN (ADMIN): " + message.ToString())
Try
Crack(message, sessionID)
Catch ex As Exception
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("==Cracker exception==")
ClientGUI.RichTextBox1.AppendText(ex.ToString())
ClientGUI.RichTextBox1.AppendText(ex.StackTrace)
End Try
End Sub
Public Sub FromApp(message As Message, sessionID As SessionID) Implements IApplication.FromApp
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("IN (APP): " + message.ToString())
Try
Crack(message, sessionID)
Catch ex As Exception
ClientGUI.RichTextBox1.AppendText("")
ClientGUI.RichTextBox1.AppendText("==Cracker exception==")
ClientGUI.RichTextBox1.AppendText(ex.ToString())
ClientGUI.RichTextBox1.AppendText(ex.StackTrace)
End Try
End Sub
Public Sub ToApp(message As Message, sessionId As SessionID) Implements IApplication.ToApp
Try
Dim possDupFlag As Boolean = False
If (message.Header.IsSetField(Tags.PossDupFlag)) Then
possDupFlag = Converters.BoolConverter.Convert(message.Header.GetField(Tags.PossDupFlag))
End If
If (possDupFlag) Then
Throw New DoNotSend()
End If
Catch ex As FieldNotFoundException
ClientGUI.RichTextBox1.AppendText("OUT (APP): " + message.ToString())
End Try
End Sub
Public Sub OnCreate(sessionID As SessionID) Implements IApplication.OnCreate
'_session = Session.LookupSession(sessionID)
ClientGUI.RichTextBox1.AppendText("Session created - " + sessionID.ToString())
End Sub
Public Sub OnLogon(sessionID As SessionID) Implements IApplication.OnLogon
ClientGUI.RichTextBox1.AppendText("Logon - " + sessionID.ToString())
ClientGUI.ToolStripDropDownButton1.Text = "Connected"
ClientGUI.ToolStripDropDownButton1.Image = My.Resources.Connected
'MsgBox("onlogon")
End Sub
Public Sub OnLogout(sessionID As SessionID) Implements IApplication.OnLogout
ClientGUI.RichTextBox1.AppendText("Logout - " + sessionID.ToString())
ClientGUI.ToolStripDropDownButton1.Text = "Disconnected"
ClientGUI.ToolStripDropDownButton1.Image = My.Resources.Disconnected
End Sub
Public Sub ToAdmin(message As Message, sessionID As SessionID) Implements IApplication.ToAdmin
ClientGUI.RichTextBox1.AppendText("OUT (ADMIN): " + message.ToString())
End Sub
Public Sub OnMessage(message As FIX42.Heartbeat, sessionID As SessionID)
ClientGUI.RichTextBox1.AppendText("HEARTBEAT")
End Sub
End Class
I guess that the code in MyQuickFixApp class access to the default instance of your ClientGUI, not the instance which is actually running, each time you write ClientGUI.(...).
See this thread Why is there a default instance of every form in VB.Net but not in C#? for more information about default instance, which is something you should avoid to use.
So you could add a parameter in the MyQuickFixApp class constructor :
Public Class MyQuickFixApp
Inherits MessageCracker : Implements IApplication
Dim _clientGUI As ClientGUI = Nothing
Public Sub New(cltGui As ClientGUI)
_clientGUI = cltGui
End sub
(...)
End class
Then, replace in the MyQuickFixApp class all the ClientGUI.(...), with _clientGUI.(...) to be sure to access to the correct instance.
And finally, initialize your MyQuickFixApp class in ClientGUI like this:
Dim myApp As New MyQuickFixApp(me)
Note that this code, you can only access to the method of the class in the Form_Load event. This variable should be declared in the class and initialized in the form_load if you want to access it later from the ClientGUI form.
Public Class ClientGUI
Dim initiator As SocketInitiator
Dim myApp As MyQuickFixApp()
Public Sub ClientGUI_Load(sender As Object, e As EventArgs) Handles MyBase.Load
(...)
myApp =New MyQuickFixApp(Me)
(...)
End Sub
(...)
End Class
In Form
private void button3_Click(object sender, EventArgs e)
{
TestClass tc = new TestClass();
tc.addComment(richTextBox1);
}
In Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
public class TestClass
{
public void addComment(RichTextBox rt)
{
rt.Text = rt.Text + Environment.NewLine + "My Dynamic Text";
}
}
you can do it same in VB.net also