Click here to Skip to main content
14,934,103 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have a class which executes a Process (runs a command line command). On receiving the output from the command execution, I want to check various lines and throw exception. My code is :

C#
************ This is a library class
public int ConnectToServer()
{
    int error = 0;
    connected = false;
    try
    {
        process = Process.Start(processInfo);

        process.BeginOutputReadLine();
        process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
    }
    catch (Exception e)
    {
        Console.WriteLine("Error Processing ConnectToServer : " + e.Message);
        errorMsg = e.Message;
        error = -1;
    }

    return error;
}

private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    string d = e.Data;
    Console.WriteLine("LINE = " + d);
    if (d != null)
    {
        if (d.IndexOf("Completed") > 0)
        {
            connected = true;
            Console.WriteLine("********* Connected = " + connected);
        }
        else if (isInValidLine(d))
            throw new Exception(d);    // HERE I get Exception not handled
    }
    return;
}

private bool isInValidLine(string line)
{
    if (line.IndexOf("Cannot load file") > 0)
        return true;
    return false;
}



GUI CODE where I am calling it :
***************************
C#
try
{
    StartConnect();
}
catch (Exception ex)
{
    string msg = ex.Message;
    if (msg.Equals("NotConnectedException"))
        MessageBox.Show("Error connecting  : Connection Time Out "Time Out", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    else if (msg.IndexOf("Cannot load file") > 0)
        MessageBox.Show("Error connecting : Problem with File \n Unable to Load or Find required file.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}

C#
private void StartConnect()
{
    DateTime start = DateTime.Now;

    int timeout = 40000, timepassed = 0;

    oc = new OpenConnect(cmd, timeout);
    int retVal = oc.ConnectToServer();
    while (!oc.Connected)
    {
        timepassed = (int)(DateTime.Now - start).TotalMilliseconds;
        if (timepassed > timeout)
        {
            connectedToVpn = false;
            throw new Exception("NotConnectedException");
        }
        Thread.Sleep(100);
    }


Can anyone help me solve the mistake? What I want is the Exception that are thrown in Process_OutputDataReceived should be handled in ConnectToServer() or handled in try{} that calls StartConnect().
Why do I get a runtime Exception at throw @ new Exception("Cannot find file") line?

Any help is appreciated. I am stuck up want to handle such many cases by reading the output of the command.

Thanks
Posted
Updated 2-Feb-11 1:15am
v2

Since you're using asynchronous processing, what you want cannot be (simply) achieved. In your call to ConnectToServer you are starting a process and hook up to the OutputDataReceived event handler. The errors that happen inside the event handler cannot be directly propagated to the main gui thread.
   
Comments
All Time Programming 2-Feb-11 8:09am
   
then how to achieve it ?

My process wont be completed as I am connecting to server so it has to stay untill I disconnect it from app.

Can you help me our guide me for the above .

Thanks
Espen Harlinn 4-Feb-11 11:36am
   
Good explanation, 5+
Try it this way:

C#
//-----------------------------------------------------------------------------
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    connected = false;
    string d = e.Data;
    if (!string.IsNullOrEmpty(d))
    {
        Console.WriteLine("LINE = " + d);
        if (d.StartsWith("Completed"))
        {
            connected = true;
            Console.WriteLine("********* Connected = " + connected);
        }
        else if (isInValidLine(d))
        {
            throw new Exception(string.Format("Invalid line: {0}", d));
        }
    }    
}

//-----------------------------------------------------------------------------
private bool isInValidLine(string line)
{
    return (line.StartsWith("Cannot load file"));
}
   
Comments
All Time Programming 2-Feb-11 9:50am
   
John, the server prints date and time prior to message, so I can' use startsWith(). But changed string.isullOrEmpty(d).
The out was :
LINE = Wed Feb 02 20:15:56 2011 Cannot load file :fopen:No such file or directory: error:2006D080:BIO routines:BIO_new_file:no such file: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib
LINE = Wed Feb 02 20:15:56 2011 Exiting
Execution Completed

This says that "Cannot load file" has come from output. But when I debug, the cursor goes once in ConnectServer() and then stays in while loop only.
I found solution to achieve my goal and hence thought to share with all of you, as it might help someone.

I added a new property "ErrorMessage" in class and assigned the value of line in isInvalid() if specified text is found.

In process_OutputDataReceived, if isInvalid() returns true, the function returns.

And in StartConnect(), after checking timePassed, also check the length of ErrorMessage. if its > 0, then throw new Exception(ErrorMessage).

Finally in try..catch block that calls StartConnect(), all exceptions are handled here only.

The Code is :
<pre>
private bool isInValidLine(string line)
{
if (line.IndexOf(&quot;Cannot load file&quot;) &gt; 0)
{
ErrorMessage = line;
return true;
}
return false;
}

private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
string d = e.Data;

if (!string.IsNullOrEmpty(d))
{
if (sb != null)
sb.Append(d + &quot;\n&quot;);
Console.WriteLine(&quot;LINE = &quot; + d);
if (d.IndexOf(&quot;Completed&quot;) &gt; 0)
{
connected = true;
Console.WriteLine(&quot;********* Connected = &quot; + connected);
} else if (isInValidLine(d))
{
connected = false;
errorMsg = d;
return;
}
}

private void StartConnect()
{
......
while (!oc.Connected)
{
timepassed = (int)(DateTime.Now - start).TotalMilliseconds;
if (timepassed &gt; timeout)
{
oc.DisconnectServer();
throw new Exception(&quot;NotConnectedException&quot;);
} else if (oc.ErrorMessage.Length &gt; 0)
{
oc.DisconnectServer();
throw new Exception(oc.ErrorMessage);
}
}
.......
}


try
{
StartConnect();
}
catch (Exception ex)
{
IOUtility.DeleteFile(LOGIN_FILE);
LOGIN_FILE = &quot;&quot;;

i = -1;
string msg = ex.Message;
ExceptionData ed = null;
if (msg.Equals(&quot;NotConnectedException&quot;)) // TIME OUT
MessageBox.Show(&quot;Error connecting to the Server : Connection Time Out \n Unable to connect to the Server&quot;, &quot;Time Out&quot;, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else if (msg.IndexOf(&quot;Cannot load file&quot;) &gt; 0)
MessageBox.Show(&quot;Error connecting to the Server : Problem with File \n Unable to Load or Find required file.&quot;, &quot;Failed to Connect&quot;, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}

</pre>

Hope this help someone like me.

Thanks a lot to all.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900