Results 1 to 22 of 22

Thread: how to make callback

  1. #1

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    how to make callback

    Can someone explain how to make callbacks in VB.NET?
    Thank you

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: how to make callback

    In what context? Don't be afraid to elaborate. The character limit on a post is 10000 so you can give details.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    sorry. I made two separate programs, one is the client and one is the server. both forms contain two text boxes. so when client is connected to the server, both programs can communicate with each other on the network. i received the following message when i tried to run the program, "Control control name accessed from a thread other than the thread it was created on." basically i have to use the thread-save calls, i looked at the MSDN help page, but i dont really understand what they did there.

    Thanx

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: how to make callback

    There are numerous examples of accessing controls from worker threads already posted on the forum, but it's a matter of know ing what to search for. Basically you have to create an instance of a delegate and invoke that on the UI to call a method. The delegate has to match the signature of the method that you want to call, which means the same number and type of arguments and the same return type. A delegate is basically an object that contains an instance of a method. Like other objects, that delegate can be passed around wherever you like. It can then be invoked anywhere, which executes method it contains, even though the method itself may not normally be accessible from that location. If you want to call a method that has no arguments and returns no value then you can use the existing MethodInvoker delegate:
    VB Code:
    1. Private Sub SayHello()
    2.     If Me.Label1.InvokeRequired Then
    3.         'The method is being called on a worker thread so create a delegate that can cross the thread boundary.
    4.         Me.Label1.Invoke(New MethodInvoker(AddressOf SayHello))
    5.     Else
    6.         'The method is being called on the UI thread so access the control directly.
    7.         Me.Label1.Text = "Hello World"
    8.     End If
    9. End Sub
    Now you can safely call that method from anywhere as is. The method itself will detect whether it is on a worker thread or not and do what's required. If it is on a worker thread then the delegate is created and passed to the the control's Invoke method. This carries the delegate across the thread boundary to the UI thread where the method it contains is executed. This means that if the SayHello method is executed on a worker thread it simply re-executes itself on the UI thread via the delegate. If you want to call a method that has arguments or returns something then you need declare your own delegate:
    VB Code:
    1. Private Delegate Function GetTextDelegate() As String
    2.  
    3. Private Function GetText() As String
    4.     Dim result As String
    5.  
    6.     If Me.TextBox1.InvokeRequired Then
    7.         'We are on a worker thread.
    8.         result = CStr(Me.TextBox1.Invoke(New GetTextDelegate(AddressOf GetText)))
    9.     Else
    10.         'We are on the UI thread.
    11.         result = Me.TextBox1.Text
    12.     End If
    13.  
    14.     Return result
    15. End Function
    VB Code:
    1. Private Delegate Sub SetTextDelegate(ByVal text As String)
    2.  
    3. Private Sub SetText(ByVal text As String)
    4.     If Me.TextBox1.InvokeRequired Then
    5.         'We are on a worker thread.
    6.         Me.TextBox1.Invoke(New SetTextDelegate(AddressOf SetText), text)
    7.     Else
    8.         'We are on the UI thread.
    9.         Me.TextBox1.Text = text
    10.     End If
    11. End Sub
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5
    PowerPoster
    Join Date
    Aug 2005
    Location
    College Station, TX
    Posts
    4,521

    Re: how to make callback

    A good article over asynchronous programming techniques can be found below for further explanation. There is a handy template at the end that might help make it easier to implement (if JM's post hasn't already done so )

    http://www.aspfree.com/c/a/VB.NET/De...h-VB-NET-2005/

  6. #6

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    Thanx for the help guys, im reading all the resources now.

  7. #7
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: how to make callback

    For more information you may also like to follow the Articles -> Advanced .NET link in my signature and read the Asynchronous Programming and Managed Threading sections.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: how to make callback

    Put your code in VBCODE tags at least.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  9. #9

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    VB Code:
    1. 'Server
    2. Imports System.Net.Sockets
    3. Imports System.Net
    4. Imports System.Windows.Forms
    5. Imports System.Threading
    6. Imports System.IO
    7.  
    8.  
    9. Public Class FrmServer
    10.     Inherits Form
    11.  
    12.     Private connection As Socket 'Soccket object handles connection
    13.     Private readThread As Thread 'server thread
    14.  
    15.     'stream through which to transfer data
    16.     Private socketStream As NetworkStream
    17.  
    18.     'objects for writing and reading data
    19.     Private writer As BinaryWriter
    20.     Private reader As BinaryReader
    21.  
    22.  
    23.  
    24.     Public Sub New()
    25.         MyBase.New()
    26.  
    27.         ' This call is required by the Windows Form Designer.
    28.         InitializeComponent()
    29.  
    30.         'txtDisplay.CheckForIllegalCrossThreadCalls = False
    31.         ' txtInput.CheckForIllegalCrossThreadCalls = False
    32.  
    33.         ' Add any initialization after the InitializeComponent() call.
    34.         readThread = New Thread(New ThreadStart(AddressOf RunServer))
    35.         readThread.Start()
    36.     End Sub
    37.  
    38.  
    39.     Private Sub FrmServer_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
    40.         System.Environment.Exit(System.Environment.ExitCode)
    41.     End Sub
    42.  
    43.     Private Sub txtInput_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtInput.KeyDown
    44.  
    45.         Try
    46.             If (e.KeyCode = Keys.Enter AndAlso Not connection Is Nothing) Then
    47.  
    48.                 writer.Write("server>>" & txtInput.Text)
    49.                 txtDisplay.Text &= vbCrLf & "SERVER>>" & txtInput.Text
    50.  
    51.                 If txtInput.Text = "TERMINATE" Then
    52.                     connection.Close()
    53.                 End If
    54.                 txtInput.Clear()
    55.  
    56.             End If
    57.  
    58.         Catch exception As SocketException
    59.             txtDisplay.Text &= vbCrLf & "Error writing object"
    60.         End Try
    61.     End Sub
    62.  
    63.  
    64.  
    65.     'allow client to connect and display text sent by user
    66.  
    67.     Public Sub RunServer()
    68.         Dim listener As TcpListener
    69.         Dim counter As Integer = 1
    70.         'Dim port As Int32 = 5000
    71.         ' Dim localAddr As IPAddress = IPAddress.Parse("localhost")
    72.  
    73.      
    74.  
    75.         'wait for request, then establish connection
    76.         Try
    77.             listener = New TcpListener(5000)
    78.  
    79.             listener.Start()
    80.  
    81.             While True
    82.              
    83.               'made changes here
    84.               If Me.txtDisplay.InvokeRequired Then
    85.  
    86.                     Me.txtDisplay.Invoke(New MethodInvoker(AddressOf RunServer))
    87.  
    88.                 Else
    89.                 txtDisplay.Text = "Waiting for connection" & vbCrLf
    90.                 End If
    91.  
    92.                 connection = listener.AcceptSocket()
    93.  
    94.                 socketStream = New NetworkStream(connection)
    95.  
    96.                 writer = New BinaryWriter(socketStream)
    97.                 reader = New BinaryReader(socketStream)
    98.  
    99.                 txtDisplay.Text &= "Connection " & counter & "received." & vbCrLf
    100.  
    101.                 writer.Write("SERVER>>> Connection successful")
    102.  
    103.                 txtInput.ReadOnly = False
    104.  
    105.                 Dim theReply As String = ""
    106.  
    107.                 Try
    108.                     Do
    109.                         theReply = reader.ReadString()
    110.  
    111.                         txtDisplay.Text &= vbCrLf & theReply
    112.  
    113.                     Loop While (theReply <> "CLIENT >>> TERMINATE" AndAlso connection.Connected)
    114.  
    115.                 Catch inputOutputException As IOException
    116.                     MessageBox.Show("Client application closing")
    117.  
    118.                 Finally
    119.  
    120.                     txtDisplay.Text &= vbCrLf & "User terminated connection"
    121.  
    122.                     txtInput.ReadOnly = True
    123.  
    124.                     writer.Close()
    125.                     reader.Close()
    126.                     socketStream.Close()
    127.                     connection.Close()
    128.  
    129.                     counter += 1
    130.  
    131.                 End Try
    132.  
    133.             End While
    134.  
    135.         Catch inputOutputException As IOException
    136.             MessageBox.Show("Server applicatin closing")
    137.         End Try
    138.  
    139.     End Sub
    140. End Class
    Last edited by RaymondMR2; Aug 17th, 2006 at 01:39 AM.

  10. #10

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    VB Code:
    1. 'Client Side
    2.  
    3.  
    4. Imports System.Windows.Forms
    5. Imports System.Threading
    6. Imports System.Net
    7. Imports System.Net.Sockets
    8. Imports System.IO
    9.  
    10. Public Class Form1
    11.  
    12.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    13.  
    14.     End Sub
    15.  
    16.  
    17.     Private output As NetworkStream
    18.  
    19.     Private writer As BinaryWriter
    20.  
    21.     Private reader As BinaryReader
    22.  
    23.     Private message As String = ""
    24.  
    25.     Private readThread As Thread
    26.  
    27.     Public Sub New()
    28.  
    29.         MyBase.New()
    30.  
    31.         ' This call is required by the Windows Form Designer.
    32.         InitializeComponent()
    33.  
    34.         'txtDisplay.CheckForIllegalCrossThreadCalls = False
    35.         'txtInput.CheckForIllegalCrossThreadCalls = False
    36.  
    37.         ' Add any initialization after the InitializeComponent() call.
    38.  
    39.         readThread = New Thread(AddressOf RunClient)
    40.         readThread.Start()
    41.  
    42.     End Sub
    43.  
    44.     Private Sub Form1_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
    45.         System.Environment.Exit(System.Environment.ExitCode)
    46.     End Sub
    47.  
    48.     Private Sub txtInput_Keydown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtInput.KeyDown
    49.         Try
    50.             If e.KeyCode = Keys.Enter Then
    51.  
    52.                 writer.Write("CLIENT>>> " & txtInput.Text)
    53.  
    54.                 txtDisplay.Text &= vbCrLf & "CLIENT>>> " & txtInput.Text
    55.  
    56.                 txtInput.Clear()
    57.             End If
    58.         Catch exception As SocketException
    59.             txtDisplay.Text &= vbCrLf & " error writing object"
    60.  
    61.         End Try
    62.     End Sub
    63.  
    64.     Public Sub RunClient()
    65.         Dim client As TcpClient
    66.  
    67.         Try
    68.             txtDisplay.Text &= "Attempting connection" & vbCrLf
    69.  
    70.             client = New TcpClient()
    71.             client.Connect("127.0.0.1", 5000)
    72.  
    73.             output = client.GetStream()
    74.  
    75.             writer = New BinaryWriter(output)
    76.             reader = New BinaryReader(output)
    77.  
    78.             txtDisplay.Text &= vbCrLf & "Got I/O streams" & vbCrLf
    79.  
    80.             txtInput.ReadOnly = False
    81.  
    82.             Try
    83.                 Do
    84.                     message = reader.ReadString
    85.                     txtDisplay.Text &= vbCrLf & message
    86.  
    87.                 Loop While message <> "SERVER >>> TERMINATE"
    88.  
    89.             Catch inputOutputException As IOException
    90.                 MessageBox.Show("Client application closing")
    91.  
    92.             Finally
    93.  
    94.                 txtDisplay.Text &= vbCrLf & "Closing connection.' & vbCrLf"
    95.                 writer.Close()
    96.                 reader.Close()
    97.                 output.Close()
    98.                 client.Close()
    99.  
    100.             End Try
    101.  
    102.             Application.Exit()
    103.  
    104.         Catch inputOutputException As Exception
    105.             MessageBox.Show("Client application closing")
    106.  
    107.         End Try
    108.  
    109.     End Sub
    110.  
    111. End Class

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: how to make callback

    Alternatively you could have just editied your existing posts.

    I don't see where you've tried at all. The example code I posted even sets the Text of a TextBox, so if that's all you're trying to do then you've already got the code.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    sorry, forgot to put changes into server side, please have a look now.

    im getting an error saying that "only one usage of each socket address is normally permitted"

    Thanks

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: how to make callback

    You don't invoke RunServer because that will just try to run EVERYTHING again. You write a method just like my SetText method (or in your case AppendText might be better) and you call that. It will create the delegate if required.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  14. #14

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    I made the method AppendText

    VB Code:
    1. private Delegate Sub AppendTextDelegate(ByVal text As String)
    2.   Private Sub ApendText(ByVal text As String)
    3.         If Me.txtDisplay.InvokeRequired Then
    4.             Me.txtDisplay.Invoke(New AppendTextDelegate(AddressOf ApendText), text)
    5.         Else
    6.             Me.txtDisplay.Text = text
    7.         End If
    8.     End Sub

    i actually tried this before your post, then where do i call this in the while loop. i know the error is at

    txtDisplay.Text = "Waiting for conenction" & vbCrLf

    sorry about this, im new to VB.NET

  15. #15
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: how to make callback

    Firstly, you've changed the name of the method but not the implementation. That method is setting the Text, not appending it. If you want to be able to set or append text then you need two methods. You can use the same delegate for both though, because they have the same signature.

    Secondly, you've got the method there so call it. Wherever you want to append text to the TextBox you call that method.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  16. #16

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    man, i understand 60% of wat you saying here. yes the implementation is wrong, since txtDisplay displays whatever is in the textbox. and i still fail to apply this whole thing. Could you please show me how to do it man? cheers

  17. #17

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    some coding will be much more appreciate, then i'll undertand by relate your code back to my work. better to learn and understand, also saves time. cheers

  18. #18
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: how to make callback

    You already have the SetText method. If you want an AppendText method then instead of setting the Text:
    VB Code:
    1. myTextBox.Text = text
    you append it:
    VB Code:
    1. myTextBox.Text &= text
    or better:
    VB Code:
    1. myTextBox.AppendText(text)
    Now, wherever in your code you are currently setting the Text of the TextBox directly you call the SetText method instead. Likewise, wherever you are currently appending to the TextBox directly you call the AppendText method instead.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  19. #19

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    so basically you saying that
    VB Code:
    1. Private Delegate Sub AppendTextDelegate(ByVal text As String)
    2.  
    3.     Private Sub AppendText(ByVal text As String)
    4.         If Me.txtDisplay.InvokeRequired Then
    5.             Me.txtDisplay.Invoke(New AppendTextDelegate(AddressOf AppendText))
    6.         Else
    7.             Me.txtDisplay.AppendText(text)
    8.         End If
    9.     End Sub

    and then instead of using

    VB Code:
    1. txtDisplay.Text = "waiting for connection" & vbCrLf

    i should start using this new method AppendText
    VB Code:
    1. txtDisplay.AppendText("Waiting for connection" & vbCrLf)
    ???
    Thanks for your help

  20. #20
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: how to make callback

    This:
    VB Code:
    1. txtDisplay.Text = "waiting for connection" & vbCrLf
    is not appending. It is setting. If you need to be able to set the text or append to the text then you need both a SetText method and an AppendText method. Other than that you're exactly right. You just need to follow these steps:

    1. Declare the delegate exactly as I have in post #4.
    2. Declare and implement the SetText exactly as I have in post #4. If your TextBox is not named TextBox1 then change that appropriately.
    3. Declare and implement the AppendText method the same way as SetText, but make that one change as I did in post #18 and you did in post #19.
    4. Go through your code and everywhere that you're setting the Text of the TextBox directly you call your SetText method instead. If you're using just "=" then you're setting.
    5. Go through your code and everywhere that you're appending to the Text of the TextBox directly you call your AppendText method instead. If you're using "&=" then you're appending.

    That's it.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  21. #21
    Retired VBF Adm1nistrator plenderj's Avatar
    Join Date
    Jan 2001
    Location
    Dublin, Ireland
    Posts
    10,359

    Re: how to make callback

    ... this still ongoing?
    Microsoft MVP : Visual Developer - Visual Basic [2004-2005]

  22. #22

    Thread Starter
    New Member
    Join Date
    Aug 2006
    Posts
    14

    Re: how to make callback

    this is the end of the topic. its done....thanx jmcilhinney

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width