Solved

How to comunicate from process and main program vb.net

Posted on 2011-02-14
20
388 Views
Last Modified: 2012-08-14
In VB.Net
from an "A application",
using a process I open another vb.net app called "B application".
So, there a Process method, property, to look the progress
of the B application?
Is possible for B application, to write some text that can be
read from the A application in real time while the B application process is running?
0
Comment
Question by:bobdylan75
  • 9
  • 8
  • 3
20 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34889634
Many, many ways to do this...

What is the nature of the data being passed from B to A?  Is it really ONLY a string value? How often is the data sent and how much is sent?  Is it simple, plain text?...or do you need to send control characters as well?
...or do you need to pass other types of data?
Would sending ONE numeric value back to A from B after B completes be sufficient?

What VERSION VB.Net are you working with?

Will there be only ONE instance of A running?...or does each spawned instance of B need to be "paired" with the particular instance of A that ran it?

I assume that both A and B are running on the same machine?...

Details, details, details...  =)
0
 

Author Comment

by:bobdylan75
ID: 34889731
Vb.net 2005.
I need to pass only a string for each step in a FOR cycle which will execute
some operation (sending emails)
So when it will send an email I want to alert my "A application" which will display on the screen this information.

And at the end, I want to return a Codeexit value,
but for this last issue I know how to do, with process.exitcode property
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34889742
Will there be only ONE instance of 'A' running?
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 420 total points
ID: 34890413
*The robust answer is to use .Net Remoting:
http://msdn.microsoft.com/en-us/library/kwdt6w2k(VS.71).aspx

Assuming you only need one instance of 'A' running, though, a SIMPLE approach would be to use the Application.StartupNextInstance() event:
http://msdn.microsoft.com/en-us/library/b9z4eyh8(VS.80).aspx
http://msdn.microsoft.com/en-us/library/w3xx6ewx(VS.80).aspx

The basic idea is that 'B' would simply run 'A' again for each value that needs to be passed, and pass that string as a command-line argument.  'A' would be a single instance application by checking the "Make single instance application" box in Project --> Properties.  As a single instance application, that ONE running instance of 'A' would receive a StartupNextInstance() event each time 'B' passes it a value.

Here is a simple Console App B that simulates the sending of the emails and communicates back with App A:
 
Module Module1

    Public Sub Main()
        Dim AppA_FullPath As String = "C:\Users\Mike\Documents\Visual Studio 2010\Projects\AppA\AppA\bin\Debug\AppA.exe"
        For i As Integer = 1 To 25
            ' Send the Email:
            System.Threading.Thread.Sleep(500)

            ' Update the Status of AppA:
            Process.Start(AppA_FullPath, "Email #" & i)
        Next
        Environment.ExitCode = 1
    End Sub

End Module

Open in new window


Here is the code for a WinForms App A that launches App B and receives back status updates via the Application.StartupNextInstance() event:
*Remember that the "Make single instance application" box has been CHECKED for this app!
 
Public Class Form1

    Private WithEvents P As Process

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button1.Enabled = False

        Dim P As New Process
        P.StartInfo.FileName = "C:\Users\Mike\Documents\Visual Studio 2010\Projects\AppB\AppB\bin\Debug\AppB.exe"
        P.EnableRaisingEvents = True
        AddHandler P.Exited, AddressOf P_Exited
        P.Start()
    End Sub

    Private Sub P_Exited(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim P As Process = DirectCast(sender, Process)
        Dim ExitCode As Integer = P.ExitCode
        MessageBox.Show("ExitCode = " & ExitCode, "Done", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Button1.Enabled = True
    End Sub

End Class

Open in new window


To get the StartupNextInstance() event in App A, click on Project --> Properties, then click on the "View Application Events" button in the bottom right:
 
Namespace My

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication

        Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
            Dim data As String = String.Join(" ", e.CommandLine.ToArray)
            Form1.Label1.Text = data
        End Sub

    End Class


End Namespace

Open in new window

0
 
LVL 83

Assisted Solution

by:CodeCruiser
CodeCruiser earned 80 total points
ID: 34896069
Idle_Mind has done a good job. I would just post a link to a tutorial and sample project

http://anoriginalidea.wordpress.com/2007/08/09/simple-inter-process-communication-in-vbnet/



Another option for inter process communication is Named Pipes

http://www.codeproject.com/KB/threads/dotnetnamedpipespart1.aspx

http://www.codeproject.com/KB/threads/dotnetnamedpipespart2.aspx
0
 

Author Comment

by:bobdylan75
ID: 34904344
Yes but,
Perhaps I don't understand well,
but:
I have a big "A-application" which is the main application,
In this application I have a Watcher form which has to monitor the situation,
I cannot start A application every time.
Perhaps I could start every time the B-application but it's not my request
0
 

Author Comment

by:bobdylan75
ID: 34904352
I have to read better your solution...
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34905055
You question was about communication between A-Application and B-Application (two separate applications) but now it looks like you have A-Application and a FORM which is started from A-Application. Is that correct?
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34906577
"I cannot start A application every time."

'A' is a SINGLE instance application (check the "Make single instance application" in Project --> Properties) so even though we are starting 'A' multiple times there is ONLY one instance ever running.  That ONE running instance gets a StartupNextInstance() event EVERY time that 'B' runs 'A' again.
0
 

Author Comment

by:bobdylan75
ID: 34908433
I have a very beautiful A-Application.
I love it.
My A-application does many things.
One of this things is:
(MAcro code)
For each document in tableDocs
sendemail(document)
Next

Now, the user at the moment has to wait 1 hour
and he can already cancel the process, and he can already view the progress status,
beacuse I used application.doevents function, but the cancel option isn't performant as I want
but if he wants use my A-application for other functions, he cannot do it while
the "sendEmail process" has not ended to send 400 emails and their attachments.

Now, I dont want to open another A-application,

I want to demand the "sendemail process" code to another B-application that I will create,
How to monitor the progress of b-application from a-application without using
a text file? If I will use a process to start b-application I will able to close it in a second if I want.
at the moment I think only the "text file solution" at the moment
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34908494
In that case, the solutions provided should work. Personally though, I dont think the effort involved in implementing those solutions is worth just to get rid of text file. Do you use a DB in your apps? You can use DB to share info.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34908538
"I dont want to open another A-application"

*My approach will still work and it doesn't open another A-application because it has been set to SINGLE INSTANCE.  Create a new project and enable this setting to see how it works.  You can double click the executable all you want and the same instance will stay open with creating new ones.

Communicating via text file is not necessary.  The whole point of my posts was that you can communicate using the built-in abilities of the .Net framework.

Yes, if you relegate the mail sending to B-application you can cancel it as well.  You could do this forcefully by using the Process() instance and issuing a CloseMainWindow() or Kill() command.  You could even use the SAME technique of SINGLE INSTANCE for B-application and send it a command-line parameter to cancel it.

*** BUT *** it really sounds more like you need to better design A-application with MULTI-THREADING in mind.  Instead of maintaining UI responsiveness with DoEvents(), you move the mail sending code to another thread.  The easiest way to do this is through use of the BackgroundWorker() control:
http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34908541
*That first paragraph should say "without creating new ones" at the end. =\
0
 

Author Comment

by:bobdylan75
ID: 34908581
;) Ok,
I have only to read slowly your solution and so to understand it.
Thanks, See you later ;)
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34908621
If you want do it all within A-application (without an external B-application) then please let us know.  It may be fairly easy to move the mail sending code to a background thread and provide an easy method to cancel it.

Just show us your existing mail sending code and we should be able to tell pretty quickly if it's worth the effort.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34913079
@CodeCruiser...just thought I'd let you know that I tried to follow the tutorial in the first link you posted...and I failed miserably.  I got lots of errors and exceptions...

@Everyone...

I found this tutorial, though, and made a similar version of it in VB.Net:
http://www.codeproject.com/KB/IP/remotinggui.aspx

I created "AppA_Remoting.exe" and "AppB_Remoting.exe", and was able to communicate from B to A via Remoting.

AppA simply had a Label, and AppB simply had a TextBox.  When the TextBox in B changes, the Label in A is updated automatically.  I did note a significant delay when the connection was first made, but afterwards the connection was quite smooth and responsive.

Here is my code for AppA_Remoting:
' Add a Reference to System.Runtime.Remoting (Project --> Add Reference --> .Net Tab)
Imports System.Threading
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp

Public Class Form1

    Private WithEvents mas As MasterAppServer

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ChannelServices.RegisterChannel(New TcpChannel(50050), False)
        mas = New MasterAppServer
        RemotingServices.Marshal(mas, "Master")
    End Sub

    Private Sub mas_SlaveStatus(ByVal status As String) Handles mas.SlaveStatus
        Label1.Text = status
    End Sub

End Class

Public Class MasterAppServer
    Inherits MarshalByRefObject

    Public Event SlaveStatus(ByVal status As String)

    Private SC As WindowsFormsSynchronizationContext

    Public Sub New()
        SC = WindowsFormsSynchronizationContext.Current
    End Sub

    Public Sub UpdateStatus(ByVal status As String)
        If Not IsNothing(SC) Then
            SC.Post(New SendOrPostCallback(AddressOf SynchronizedRaiseEvent), status)
        End If
    End Sub

    Private Sub SynchronizedRaiseEvent(ByVal status As Object)
        ' ... we are already on the main UI thread when we raise the event below ...
        RaiseEvent SlaveStatus(status)
    End Sub

End Class

Open in new window



Here is my code for AppB_Remoting:
*Note at the top that I added a Reference to AppA_Remoting*
' Add a Reference to System.Runtime.Remoting (Project --> Add Reference --> .Net Tab)
' Add a Reference to the "Master" Remoting App (Project --> Add Reference --> Browse Tab)
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp

Public Class Form1

    Private Master As AppA_Remoting.MasterAppServer = Nothing

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Process.GetProcessesByName("AppA_Remoting").Length > 0 Then
            ChannelServices.RegisterChannel(New TcpChannel(), False)
            Master = Activator.GetObject(GetType(AppA_Remoting.MasterAppServer), "tcp://localhost:50050/Master")

            ' Replace "localhost" with a computer name to communicate on a LAN!
            ' For example:
            ' Master = Activator.GetObject(GetType(AppA_Remoting.MasterAppServer), "tcp://Mike-Laptop:50050/Master")
            ' The above allowed me to use the Client from another laptop on my LAN...the master app on this laptop responded correctly
        End If
    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        If Not IsNothing(Master) Then
            Try
                Master.UpdateStatus(TextBox1.Text)
            Catch ex As Exception
            End Try
        End If
    End Sub

End Class

Open in new window



Just run 'A' first, then 'B' and start typing in the box.  Hope it helps in your project!
0
 

Author Comment

by:bobdylan75
ID: 34924012
@ Idle_Mind
thank you very much!
Your solution it's excellent!
Sorry but only today I have found time to look at it...
thank you to every body,
I would like to give you 5000 points but it's impossible at the moment ;)
0
 

Author Closing Comment

by:bobdylan75
ID: 34924027
thank you!
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34925700
Glad you finally were able to get something working.
0
 

Author Comment

by:bobdylan75
ID: 34925770
And it works fine ;)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now