How do I convert this VB.NET invokerequired code to c#? - c#

I inherited an old VB.NET program that was written long before I got to this job. I'm having to rewrite it in C#. I have been unable to find anything that seems to be a conversion for this. Can someone show me a translation for this in C#, please?
Private Sub Log(Message As String)
Try
If txtLog.InvokeRequired Then
txtLog.Invoke(Sub()
Log(Message)
End Sub)
Else
txtLog.AppendText(Message & Environment.NewLine)
End If
Catch ex As Exception
End Try
End Sub

This is the code converted to C#:
private void Log(string Message)
{
try
{
if (txtLog.InvokeRequired == true)
{
txtLog.Invoke(() =>
{
Log(Message);
});
}
else
{
txtLog.AppendText(Message + Environment.NewLine);
}
}
catch { }
}

Related

Conversion between VB.net TO C# (new EventHandler) NO overload matches delegate

I am new to C# and I need to convert my code from VB.NET to C#.
Here is my VB.NET code
Private Sub Receive()
Dim inp As NetworkStream
Dim income As BinaryReader
inp = TCP.GetStream
income = New BinaryReader(inp)
While (State = "Connected")
Try
msg = income.ReadChar
Application.OpenForms(0).Invoke(New EventHandler(AddressOf prin))
Catch ex As Exception
Try
Me.Det = False
If TCpThread.IsAlive = True Then TCpThread.Abort()
TCP.Close()
msg = ex.Message
Catch ex1 As Exception
Application.OpenForms(0).Invoke(New EventHandler(AddressOf prin))
End Try
State = "IDLE"
End Try
End While
End Sub
Private Sub prin()
Message &= msg
Check(Message)
End Sub
It works fine, I converted it to:
private void Receive()
{
NetworkStream inp = default(NetworkStream);
BinaryReader income = default(BinaryReader);
inp = TCP.GetStream();
income = new BinaryReader(inp);
while (State == "Connected")
{
try
{
msg = System.Convert.ToString(income.ReadChar());
Application.OpenForms[0].Invoke(new EventHandler(prin));
}
catch (Exception ex)
{
try
{
this.Det = false;
if (TCpThread.IsAlive == true)
{
TCpThread.Abort();
}
TCP.Close();
msg = ex.Message;
}
catch (Exception)
{
Application.OpenForms[0].Invoke(new EventHandler(prin));
}
State = "IDLE";
}
}
}
private void prin()
{
Message += msg;
Check(Message);
}
But I get
Error 1 No overload for 'prin' matches delegate 'System.EventHandler'
for this line Application.OpenForms[0].Invoke(new EventHandler(prin));. Based on the multi-threading I need to invoke a function in order to follow my thread while it is running.
what is my mistake?
Any help will appreciate.
Use
Application.OpenForms[0].Invoke(new Action(prin));
The type EventHandler represents a delegate with two parameters (a generic object and an EventArgs object). Your method prin doesn't match that description.
If you just want to create a delegate for your method, use a delegate type that has the same arguments as your method (in this case none). In this case, this is the Action delegate.
The Action delegate should also have been used in the VB code in the first place:
Application.OpenForms(0).Invoke(New Action(AddressOf prin))
However, using EventHandler works in VB because the AddressOf operator in VB is not really type safe.
Here are some VB.NET code to C# conversions. Some work, some don't
Invoke(AddressOf prin) ' doesn't compile
Invoke(Sub() prin())
Invoke(New Action(AddressOf prin))
Invoke(New NoParameterVoid(AddressOf prin))
Invoke(New EventHandler(AddressOf prin)) ' doesn't compile with Option Strict On (original code)
' ...
Delegate Sub NoParameterVoid() ' required for 4th item
Invoke(prin); // doesn't compile
Invoke(() => prin()); // doesn't compile
Invoke(new Action(prin));
Invoke(new NoParameterVoid(prin));
Invoke(new EventHandler(prin)); // doesn't compile
// ...
delegate void NoParameterVoid(); // required for 4th item
So the only two which are directly convertible to C# code which compiles are
Invoke(New Action(AddressOf prin))
Invoke(New NoParameterVoid(AddressOf prin))
and since the Delegate Sub NoParameterVoid() we need to create is identical to Action(), there's no point in creating it, in my opinion. So the only reasonable option, when trying to convert directly to c#, is:
Invoke(New Action(AddressOf prin))
Invoke(new Action(prin));
This might not have been a question if you had Option Strict On to begin with; you may have come up with Action() on your own.

How to collect errors from different functions?

I am doing a project on C#. It's a project to send message using GSM Modem. In my project, I have several function that may give errors. I have used a string variable to store error message. The basic flow is like this.
class SMS{
string message;
public string getport(){
if(ErrorCondition)
message="Error Finding port";
return port;
}
public void executecommand(command){
if(ErrorCondition1)
message="Error Executing Command";
else(ErrorCondition2)
message="No Response from device";
}
public void sendMessage(int number, string text, out string error){
findport();
executecommand(command);
error = message;
}
}
NB:This is not the working code
This is the way I have thought to collect error message, but I not sure if I am doing it the right way. I need your help on this. Is there a better approach? Error string does not save any string.
Update: As the answers of Exception are coming, I am confused about arrangement of try catch, here I have my actual code so that I'll help to give further suggestions.
public string ReadResponse(SerialPort port, int timeout)
{
string buffer = string.Empty;
try
{
do
{
if (receiveNow.WaitOne(timeout, false))
{
string t = port.ReadExisting();
buffer += t;
}
else
{
if (buffer.Length > 0)
message = "Response incomplete";
else
message = "Error on Modem";
}
}
while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
}
catch (Exception ex)
{
throw ex;
}
return buffer;
}
Your (pseudo) code can be refactored to use the de facto way of managing errors in C#, which are exceptions. Based on your code right there, you're used to using a special variable or return value as an error message and there's nothing wrong with that, it just won't be what other C# developers would expect.
Here's some (pseudo) code that demonstrates what I'm typing about.
class SMS {
public string GetPort() {
if (ErrorCondition) {
throw new PortNotFoundException("Error finding port.");
}
return port;
}
public void ExecuteCommand(Command command) {
if(ErrorCondition1) {
throw new UnknownErrorException("Error Executing Command");
}
else(ErrorCondition2) {
throw new NoResponseException("No Response from device");
}
}
public void SendMessage(int number, string text) {
FindPort();
ExecuteCommand(command);
}
}
You'll note that there's no out variable in SendMessage to handle passing out the error to calling code. That's handled by the thrown exceptions. The calling code is at liberty to determine how best to handle the exception.
You can declare
string message;
to
private List<string> message;
and add message to list, will help to catch multiple errors as well. Also make it private so that other class cant access the same.

Return the calling function

I use C# for testing purpose. A test consists of several test steps. If one test step fails, the whole test should be aborted. One test step could look like this:
Variable1.Value = 1;
Variable1.write();
Variable1.read();
if (Variable1.Value != 1)
{
Console.WriteLine("Fail");
return; //this return aborts the test
}
//next test steps
I'd like to transfer some commands into own functions to allow efficient test case programming. The function for the code above would look like this.
private void verifyValue (TypeOfVariable Var, double Value)
{
Var.read();
if (Var.Value != Value)
{
Console.WriteLine("Fail");
return;
}
}
And the test would look like this
Variable1.Value = 1;
Variable1.write();
verifyValue(Variable1, 1);
//next test steps
My Problem is now, that the return in function verifyValue only effects verifyValue but not the calling function (aka test).
Is there any possibility to abort the calling function?
This is typically done via Exceptions. They propagate through the call stack automatically. Here's an example based on your code:
public class TestFailedException : Exception
{
public TestFailedException(string message) : base(message) { }
}
void Test()
{
try
{
Variable1.Value = 1;
Variable1.write();
verifyValue(Variable1, 1);
//next test steps
...
Console.WriteLine("Test succeeded");
}
catch (TestFailedException ex)
{
Console.WriteLine("Test failed: " + ex.Message);
}
}
private void verifyValue(TypeOfVariable Var, double Value)
{
Var.read();
if (Var.Value != Value)
{
throw new TestFailedException("Actual value: " + Var.Value.ToString()
+ ", expected value: " + Value.ToString());
}
}
Its better if you use Transaction and then on any exception abort all the operation. For your current code you can through an exception and let the program stop itself. like:
throw new Exception("Test Failed - Stopping the program execution");

How to set value of variable in "BeginInvoke" delegate function in C#?

I have this code on different thread:
string sub = "";
this.BeginInvoke((Action)(delegate()
{
try
{
sub = LISTVIEW.Items[x].Text.Trim();
}
catch
{
}
}));
MessageBox.Show(sub);
what I want is to get the value of "LISTVIEW.Items[x].Text.Trim();" and pass it to "sub". please note that the LISTVIEW control is on the main thread. now how can I accomplish this?
enter code here
Func<string> foo = () =>
{
try
{
return LISTVIEW.Items[x].Text.Trim();
}
catch
{
// this is the diaper anti-pattern... fix it by adding logging and/or making the code in the try block not throw
return String.Empty;
}
};
var ar = this.BeginInvoke(foo);
string sub = (string)this.EndInvoke(ar);
You, of course, need to be a bit careful with EndInvoke because it can cause deadlocks.
if you prefer delegate syntax you can also change
this.BeginInvoke((Action)(delegate()
to
this.BeginInvoke((Func<String>)(delegate()
you stll need to return something from all branches and call end invoke.

How to explicitly pass a program flow into the finally block in C#?

In Delphi I could do something like this:
try
if not DoSomething then
Exit;
if not DoSomething2 then
Exit;
if not DoSomething3 then
Exit;
finally
DoSomethingElse;
end;
In other means if method DoSomething results false then the program flow is transffered to the finally block and DoSomething2 and DoSomething3 are not executed.
How to achieve such behaviour in C#?
Thanks in advance.
Edit1:
The below example doesn't compile in VS 2008
Edit2: I am sorry I was to fast and forget the return statement;
XElement OrderStatus(q_order_status Request)
{
XElement Response;
try
{
if (DoSomething() != 0 )
{
return;
}
}
catch(Exception e)
{
// catch some errors and eventually pass the e.Message to the Response
}
finally
{
Response = new XElement("SomeTag", "SomeResponse");
}
return Response;
}
Edit3:
After testing it seems that the easiest way to achieve this is to throw an exception if the result of DoSomething1 is false. I can throw my own execption, write a specific message and pass it to the finally clause.
You really shouldn't be using exception handling constructs for flow control. That said, Exit is comparable to return in C#. As the MSDN Documentation about the [return keyword][1] says:
If the return statement is inside a try block, the finally block, if one exists, will be executed before control returns to the calling method.
In general a finally-block will almost always execute if the corresponding try-block has been reached. There are a few rare situations where it is impossible to guarantee that the finally-block executes, but they are all fatal errors, upon which programs should likely immediately crash.
How your code would look in C#:
try
{
if (!DoSomething())
return;
if (!DoSomething2())
return;
if (!DoSomething3())
return;
}
finally
{
DoSomethingElse();
}
But again, don't do this. try and finally are intended for handling exceptions, not for normal flow control.
Reply to your edit:
In your code return doesn't compile because the return type of the method is XElement and return by itself can only be used when the return type is void. You could use return new XElement("SomeTag", "SomeResponse");, as that is what the finally would be doing anyway, or you could assign Response earlier and do return Response;.
Note though that while the finally always executes, the return Response; that comes after it doesn't execute if the reason went into the finally-block is because you did a return inside the try-block.
Answer to updated question:
The reason you're having trouble doing this in an elegant way, is because you seem to be using a combination of return values and exceptions. You should consider manually raising an exception instead of using return values if the sitation is, well, exceptional.
Assuming there is a good reason for the return values however, I'm thinking it might be clearer to go without a finally block altogether, and to include a return at the end of the try block and also in your catch block. That would save you from passing the exception message in a messy way.
I can't really say what the best solution would be, since your code snippet does not show what Response would be if DoSomething() returns a non-zero value.
Original answer:
It depends a little on what you're trying to accomplish. Are exceptions actually being thrown in any of the methods? Otherwise there is no good reason to use a try-finally pattern. This would be equivalent (though maybe not advisable for readability):
bool doneEverything = DoSomething() && DoSomething2() && DoSomething3();
DoSomethingElse();
If there are exceptions being thrown, and handled at a higher level, I'd recommend isolating this code in a separate method, so you can use a return statement*.
void DoStuff()
{
try
{
if (!DoSomething())
return;
if (!DoSomething2())
return;
if (!DoSomething3())
return;
}
finally
{
DoSomethingElse();
}
}
To answer your question about when the finally code block is executed: it is always executed, unless the executing thread terminates prematurely.
*: Some restructuring is recommended, because there is no equivalent of the Delphi Exit. The break statement comes closest, but it can only be used in loop constructs or switch blocks. To mimic Exit behavior, you would need goto and a label. We wouldn't want that, now would we? :)
Why not make the three try-lines a common if/else block? Instead of exit, call the DoSomethingElse. Like so:
if (DoSomething() == false)
{
DoSomethingElse();
}
else if (DoSomething2() == false)
{
DoSomethingElse();
}
else if (DoSomething3() == false)
{
DoSomethingElse();
}
I would like to say that "C# is not Delphi", but that would be a bit arrogant.
In C#, finally is executed as well when return is called inside the try statement.
bool doSomething = false;
bool doSomething2 = true;
try
{
if( !doSomething )
{
Console.WriteLine ("not dosomething");
return;
}
if( !doSomething2 )
{
Console.WriteLine ("not dosomething 2");
return;
}
}
finally
{
Console.WriteLine ("In finally");
}
What about switch case of course If you don't mean the finally in c# by saying finally block. default case is the finally block then and you can also find flow control example and here at msdn : Flow Control (C# vs. Java)
static void Main(string[] args)
{
switch (args[0])
{
case "copy":
//...
break;
case "move":
//...
goto case "delete";
case "del":
case "remove":
case "delete":
//...
break;
default:
//...
break;
}
}
In this sort of situation, understanding the question as dealing exclusively with the non-exception handling case, I would refactor the contents of the try into a private helper method, like this
void BranchOnContext()
{
if (!DoSomething())
return;
if (!DoSomething2())
return;
// last one will drop out and return anyway
DoSomething3();
}
void DoStuff()
{
BranchOnContext(); // Assumed not to throw
DoSomethingElse(); // Always the next thing to be executed
}
EDIT -- tracking the changed requirement
void DoStuff()
{
string message = string.Empty;
try {
BranchOnContext();
} catch (MyExpectedException me) { // only catch exceptions I'm prepared to handle
message = me.Message;
}
DoSomethingElse(message); // Always the next thing to be executed
}
Taking another crack at this with the updated info:
I want DoSomethingElse to be executed
always and I want it to include
message from possible exception
If any of the DoSomething's return 0, null is returned. If not, the generic message is created. If there was an exception, it is caught and a message with its info is returned. How about this?
XElement OrderStatus(q_order_status Request)
{
try
{
if (DoSomething() != 0 )
{
return null;
}
else
{
return new XElement("SomeTag", "SomeResponse");
}
}
catch(Exception e)
{
// catch some errors and eventually pass the e.Message to the Response
return new XElement(e.tag, e.response);
}
}
Im still struggling with how to, in a good way, put finally into this.
I find it quite similar in behavior to the Delphi's one which I have shown on the beginning. I am interested in your comments. Response is dependent on the DoSomethings result.
XElement OrderStatus(q_order_status Request)
{
XElement Response;
int result = 0;
string Message = "";
try
{
result = DoSomething1();
if (result != 0)
{
throw new DoSomethingException("DoSomething1 has failed!");
}
result = DoSomething2();
if (result != 0)
{
throw new DoSomethingException("DoSomething2 has failed!");
}
result = DoSomething3();
if (result != 0)
{
throw new DoSomethingException("DoSomething3 has failed!");
}
Message = "All tests has been passed.";
}
catch(DoSomethingException e)
{
Message = e.Message;
}
catch(Exception e)
{
Message = e.Message;
}
finally
{
Response = new XElement("SomeTag", Message);
}
return Response;
}
What do you think?
void funcA()
{
if (!DoSomething())
return;
if (!DoSomething2())
return;
if (!DoSomething3())
return;
}
void funcB()
{
funcA();
DoSomethingElse;
}
This appears to replicate the delphi:-
try
{
if(DoSomething())
if(DoSomething2())
DoSomething3();
}
finally
{
DoSomethingElse();
}
an alternate style (some people will hate this style, others will love it.):-
try
{
DoSomething() && DoSomething2() && DoSomething3();
}
finally
{
DoSomethingElse();
}
I get the impression you want some other behaviour though?
Goto version?
try
{
if (!DoSomething())
goto Exit;
if (!DoSomething2())
goto Exit;
if (!DoSomething3())
goto Exit;
Exit:;
}
finally
{
DoSomethingElse();
}
Note the irritating ; after the label, it seems a label must precede a statement.
Just had an epiphany:-
Func<bool>[] somethings = new Func<bool>[] {DoSomething, DoSomething2, DoSomething3};
try
{
foreach (Func<bool> something in somethings)
{
if (!something())
break;
}
}
finally
{
DoSomethingElse();
}

Categories

Resources