How to terminate void function in c#? - c#

i have a trouble terminating a void function in C#, i tried to put all the function body in a try and created catch body to throw nothing but termination, my question Is this method the best to terminate void function, Or you have another better solution?
Code Below
public void funCall(string element, TreeNode tree){
try
{
string[] constraintsOfFunction = { };
try
{
constraintsOfFunction = splitter(symbol[element].Key.ToString());
}
catch (Exception e)
{
errorHandler(3);
}
string paramsCount = constraintsOfFunction[0];
foreach (var x in tree.Nodes)
{
MessageBox.Show(x.ToString());
}
for (int i = 1; i <= Convert.ToInt32(paramsCount); i++)
{
MessageBox.Show(constraintsOfFunction[i]);
}
}
catch (Exception e)
{ }
}

You can do so by adding this line:
return;
For foreach, for, and while loops, you must use the following to exit the loop:
break;

Have you tried a finally{} for the try catch? Ultimately, you just need to return;

Related

How can I prevent C# and Selenium from exiting code 0

while (1 == 1)
{
int questions = 0;
Thread.Sleep(500);
try
{
driver.FindElement(By.XPath("//*[#id='root']/div/main/div[2]/div/div[1]/button[1]"));
questions++;
}
catch (Exception e)
{
return;
}
try
{
driver.FindElement(By.XPath("//*[#id='root']/div/main/div[2]/div/div[1]/button[2]"));
questions++;
}
catch (Exception e)
{
return;
}
try
{
driver.FindElement(By.XPath("//*[#id='root']/div/main/div[2]/div/div[1]/button[3]"));
questions++;
}
catch (Exception e)
{
return;
}
try
{
driver.FindElement(By.XPath("//*[#id='root']/div/main/div[2]/div/div[1]/button[4]"));
questions++;
}
catch (Exception e)
{
return;
}
if (questions == 0)
{
return;
}
else if (questions == 1)
{
MessageBox.Show("1", "1");
driver.FindElement(By.XPath("//*[#id='root']/div/main/div[2]/div/div[1]/button[1]")).Click();
}
else if (questions == 2)
{
MessageBox.Show("2", "2");
String[] av2 = { "//*[#id='root']/div/main/div[2]/div/div[1]/button[1]",
"//*[#id='root']/div/main/div[2]/div/div[1]/button[2]"};
Random random = new Random();
int a = random.Next(av2.Length);
driver.FindElement(By.XPath(av2[a])).Click();
}
else if (questions == 3)
{
MessageBox.Show("3", "3");
String[] av3 =
{
"//*[#id='root']/div/main/div[2]/div/div[1]/button[1]",
"//*[#id='root']/div/main/div[2]/div/div[1]/button[2]",
"//*[#id='root']/div/main/div[2]/div/div[1]/button[3]"
};
Random random = new Random();
int a = random.Next(av3.Length);
driver.FindElement(By.XPath(av3[a])).Click();
}
else if (questions == 4)
{
MessageBox.Show("4", "4");
String[] av4 =
{
"//*[#id='root']/div/main/div[2]/div/div[1]/button[1]",
"//*[#id='root']/div/main/div[2]/div/div[1]/button[2]",
"//*[#id='root']/div/main/div[2]/div/div[1]/button[3]",
"//*[#id='root']/div/main/div[2]/div/div[1]/button[4]"
};
Random random = new Random();
int a = random.Next(av4.Length);
driver.FindElement(By.XPath(av4[a])).Click();
}
Console.WriteLine(questions + " <");
}
I'm not experienced at all, and don't know why this class keeps exiting with code 0. I've tried multiple things, but none worked. So, what I am trying to have it do is have this piece of C# code check for an xpath with selenium every .5 seconds. but as it is right now, it exits with exit code 0. How can i fix this?
return statement, if placed in the Main function, stops execution of the program. Move your code to function, and add some logic to prevent console application from closing
using System;
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
DoYourThings();
Console.WriteLine("Press any key to close application...");
Console.ReadKey(); // application hangs here until user clicks any button,
// so you have time to examine console window
}
static void DoYourThings()
{
while (true)
{
try
{
// some code
}
catch (Exception e)
{
Console.WriteLine(e.Message); // output exception message
return; // exits DoYourThings function
}
}
}
}
}
It appears that you want to select a random item from several XPaths (if found) and click it. The problem is that instead of ignoring exceptions (by not doing anything) you're calling return;, which will exit the method.
Instead, you can just remove the return statement from inside your catch blocks, and that should resolve your issue.
Additionally, you seem to have a lot of repeated code which can be simplified if we store some of the results in lists and then loop over those lists (and choose a random element from a list). Also, you only need to initialize the instance of Random once.
For example:
// Only initialize random one time
var random = new Random();
// Store our XPaths in a list so we can loop over them
var buttonXPaths = new List<string>
{
$"//*[#id='root']/div/main/div[2]/div/div[1]/button[1]",
$"//*[#id='root']/div/main/div[2]/div/div[1]/button[2]",
$"//*[#id='root']/div/main/div[2]/div/div[1]/button[3]",
$"//*[#id='root']/div/main/div[2]/div/div[1]/button[4]",
};
// Endless loop
while (true)
{
// Sleep for half a second
Thread.Sleep(500);
// Create a list to hold any WebElements we find
var elements = new List<WebElement>();
// For each XPath, try to find the element and add it to our list
foreach (var buttonXPath in buttonXPaths)
{
try
{
elements.Add(driver.FindElement(buttonXPath));
}
catch
{
// Ignore any exceptions. The next line isn't necessary, but I
// included it so you can see the syntax for explicitly skipping
// a loop iteration and starting it over again (you were using 'return')
continue;
}
}
// If we found any elements. This is the same as: if (elements.Count > 0)
if (elements.Any())
{
// Display the number of elements found in a message box
MessageBox.Show(elements.Count.ToString(), elements.Count.ToString());
// Choose a random element from our list
WebElement randomElement = elements[random.Next(elements.Count)];
// Click it
randomElement.Click();
// This was in your code, not sure why
Console.WriteLine($"{elements.Count} <");
}
}

Execute multiple functions, but stop when an error occured

I want to use multiple functions after each other but if something went wrong in the first function the other functions shouldn't be executed. At the moment I'm using a while loop with a switch. Is there a way to skip the whole while/switch part with something else? Maybe something like an event?
while (!ErrorActive && iStep != 3)
{
switch (iStep)
{
case 0:
DoSomething(); // this can trigger ErrorActive
iStep = 1;
break;
case 1:
DoSomething2(); // this can trigger ErrorActive
iStep = 2;
break;
case 2:
DoSomething3(); // this can trigger ErrorActive
iStep = 3;
break;
}
}
the DoSomething functions have something like this:
public void DoSomething()
{
try
{
//calculate something
}
catch
{
ErrorActive = true;
}
}
Is there a way to skip the whole while/switch part and replace it with something else (like an event maybe?) or should I always keep something in between each function to check if everything is all right?
Just move the catch one level up:
// true if all steps executed, false otherwise
bool DoSteps()
{
int lastExecutedStep = 0;
try{
DoSomething();
lastExecutedStep = 1;
DoSomething1();
lastExecutedStep = 2;
DoSomething2();
lastExecutedStep = 3;
}
catch( IOException ioex )
{
// log IO Exception
}
// ... catch more expected exception types
return (lastExecutedStep == 3);
}
void DoSomething(){
// NO try/catch here
}
Even possible without stepcounter:
// true if all steps executed, false otherwise
bool DoSteps()
{
try{
DoSomething();
DoSomething1();
DoSomething2();
return true;
}
catch( IOException ioex )
{
// log IO Exception
}
// ... catch more expected exception types
return false;
}
For a more academical approach you may want to explore Chain of responsibility pattern
You can do as follows , why you use so mach code when solution is very simple.
if(!ErrorActive){
DoSomething(); // this can trigger ErrorActive
}
if(!ErrorActive){
DoSomething1(); // this can trigger ErrorActive
}
if(!ErrorActive){
DoSomething2(); // this can trigger ErrorActive
}
You can simplify the while loop to a for loop and make use of the new switch expression syntax to simplify things a bit. Also, have the functions return a success state rather than setting some shared variable:
void Run()
{
var keepRunning = true;
for(int i = 0; keepRunning; i++)
{
keepRunning = i switch
{
0 => DoSomething(),
1 => DoSomething2(),
2 => DoSomething3(),
_ => false
};
}
}
bool DoSomething()
{
try
{
return true;
}
catch
{
return false;
}
}
bool DoSomething2()
{
try
{
return true;
}
catch
{
return false;
}
}
bool DoSomething3()
{
try
{
return true;
}
catch
{
return false;
}
}

using do-while and skipping the next lines

I want to run a method _doing() that loops infinitely until a shutdownEvent is triggered. This is basically executed/started on a new Thread(). But I need not _doSomething if it is true somewhere. what should i do after if (_doSomething)? Code snippet below. Thanks.
private HighResolutionLapseTimer _lapseTimer;
private int _timeToNext
{
get
{
int lapseTime = _lapseTimer.LapseTime();
int next = DO_PERIOD - lapseTime;
if (next > 0)
{
return next;
}
else
{
return 1;
}
}
}
int DO_PERIOD = 60000;
private void _doing()
{
int _nextDoing = DO_PERIOD;
Thread.Sleep(_nextDoing);
do
{
LogInfo("Starting _doing");
lock (this)
{
if (_doSomething)
{
// skip this time because we are currently archiving
}
_doSomething = true;
}
try
{
_lapseTimer.Start();
DoSomethingHere(); //takes long processing
}
catch (Exception ex)
{
LogException(ex);
}
finally
{
lock (this)
{
_nextDoing = (int)_timeToNext;
_doSomething = false;
}
}
} while (!shutdownWaitHandle.WaitOne(_nextDoing, false));
LogInfo("Stopping _doing");
}
You could use the continue; statement.
Ohw! I just realized that a do-while is similar to a while. And to 'skip' the execution, you just have to use the continue; if the if statement is true

Find exception hiding/swallowing in C# code in VS2013

is there some way built in function/extension/tool to find all exception hidings/exception swallowing in C# solution(ASP.NET WebForms)n in VS2013.
Thanks
EDIT:
I have existing solution in which some programmers use hide/swallow exceptions(empty catch, catch only with some useless code). And I am looking for some way to find all these places in code, analyze them, and then fix them.
You can write some code using Roslyn to handle this pretty easily.
I actually wrote some code to do exactly that for a friend. It was my first attempt at using the Roslyn SDK, so my code is probably a terrible mess, but it was definitely functional.
static void Main(string[] args)
{
var result = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseFile(#"..\..\Test.cs");
var root = result.GetRoot();
var exceptionNodes = FindCatchNodes(root);
foreach (var node in exceptionNodes)
{
var line = node.GetLocation().GetLineSpan().StartLinePosition.Line + 1;
if (IsTotallyEmptyCatch(node))
{
Console.WriteLine("Totally empty catch: line {0}", line);
}
if (JustRethrows(node))
{
Console.WriteLine("Pointless rethrow: line {0}", line);
}
}
}
static List<SyntaxNodeOrToken> FindCatchNodes(SyntaxNodeOrToken node)
{
var exceptions = new List<SyntaxNodeOrToken>();
var isCatchBlock = node.IsKind(SyntaxKind.CatchClause);
if (isCatchBlock)
{
exceptions.Add(node);
}
foreach (var result in node.ChildNodesAndTokens().Select(FindCatchNodes).Where(result => result != null))
{
exceptions.AddRange(result);
}
return exceptions;
}
static bool IsTotallyEmptyCatch(SyntaxNodeOrToken catchBlock)
{
var block = catchBlock.ChildNodesAndTokens().First(t => t.CSharpKind() == SyntaxKind.Block);
var children = block.ChildNodesAndTokens();
return (children.Count == 2 && children.Any(c => c.CSharpKind() == SyntaxKind.OpenBraceToken) &&
children.Any(c => c.CSharpKind() == SyntaxKind.CloseBraceToken));
}
static bool JustRethrows(SyntaxNodeOrToken catchBlock)
{
var block = catchBlock.ChildNodesAndTokens().First(t => t.CSharpKind() == SyntaxKind.Block);
var children = block.ChildNodesAndTokens();
return (children.Count == 3 && children.Any(c => c.CSharpKind() == SyntaxKind.OpenBraceToken) &&
children.Any(c => c.CSharpKind() == SyntaxKind.CloseBraceToken) && children.Any(c=>c.CSharpKind() == SyntaxKind.ThrowStatement));
}
Given this test file:
using System;
namespace RoslynTest
{
public class Test
{
public void Foo()
{
try
{
var x = 0;
}
catch
{
}
}
public void Bar()
{
try
{
var x = 0;
}
catch (Exception ex)
{
throw;
}
}
public void Baz()
{
try
{
var x = 0;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
The output is:
Totally empty catch: ....\Test.cs: line 12
Pointless rethrow: ....\Test.cs: line 24
Pointless rethrow: ....\Test.cs: line 37
I don't know about the built-in methods. But you can write your own tool to find such places. Just regex all your files in solution and count catch and throw. There should be the same amount for each file :)

How to pause the "for" loop until getting response

I am using a for loop for making Calls for a list of numbers.
I want to take the first number from the list and make a call and to wait for the response and then proceed to the next number in the list.
I have used AutoResetEvent to do this.But it is not working.
for (int k = 0; k < list_Items.Count; k++) {
Number_To_Call = "9" + list_Items[k].ToString();
phoneCall.Start();
waitingToPickUp.Set(); //AutoReset Event
Thread.Sleep();
waitingToPickUp.WaitOne();
string detector = VoiceDetected;
if (detector == "Machine") {
//code
} else if (detector == "Human") {
//code
} else {
//code
}
}
Code for getting response form the call
void phoneCall_CallStateChanged(object sender, VoIPEventArgs<CallState> e)
{
if (e.Item.IsInCall())
{
phoneCallAudioReceiver.AttachToCall(phoneCall);
phoneCallAudioSender.AttachToCall(phoneCall);
manchineDetector.Start();
waitingToPickUp.Set();
string str = VoiceDetected;
}
else if (e.Item.IsCallEnded())
{
phoneCallAudioReceiver.Detach();
phoneCallAudioSender.Detach();
manchineDetector.Stop();
phoneCall = null;
//Number_To_Call = string.Empty;
InvokeOnGUIThread(() =>
{
Number_To_Call = string.Empty;
});
}
}
Code for Detecting Machine or Human
void manchineDetector_DetectionCompleted(object sender, VoIPEventArgs<AnswerMachineDetectionResult> e)
{
try
{
string VoiceDetected = e.Item.ToString();
}
catch (Exception ex)
{
}
}
Set and immediately WaitOne makes no sense - wait will not need to wait for anything and immediately continue.
Most likely should be reset-call-wait:
waitingToPickUp.Reset();
phoneCall.Start();
waitingToPickUp.WaitOne();

Categories