I have this:
public static void ByLinkText(string text)
{
for (var i = 0; i < 50; i++)
{
try
{
Setup.Driver.FindElement(By.LinkText(text)).Click();
return;
}
catch (Exception)
{
}
}
}
(The weird code in the middle is selenium - lets just skip that, it's not the case here)
Okay, so I have this ByLinkText() method, what you don't see here, is that I repeat this method infinitely until this middle thingy will execute correctly and then hit that return after.
So: This middle code is NOT executing correctly, and I want to know why, so what am I doing? I put a breakpoint in the catch section. What is happening? Nothing (and ByLinkText() still keeps going infinitely!).
Now, you would tell me "Hey! That middle code is just not throwing anything!", but oh sweet wishes... That middle code can do two things: either throw something at me, or do it like it should (prove1 and prove2).
So finally, what is this all about? About breakpoints. As soon as I put my breakpoint on that return (right after magical code!) that code executes properly! HOW in the programical world is that possible, that breakpoint repairs my application!?
When breakpoints make your application behave it means that there is probably a timing issue with your code. Whenever you stop at a break point the stop introduces a delay that may let other processing go on without error.
This is why you sometimes see Thread.Sleep(N); thrown into code here and there. That's a coder throwing his/her arms up and saying "I don't know. Just put a Sleep in there."
In fact, give it a try. Put a Thread.Sleep(3000); where the break point goes and see what happens. I don't ever recommend that this be the solution but it could be a good test of the theory.
I think this has more to do with selenium than you seem to believe. Have a look at implicit and explicit waits for finding the element.
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
Another thing to try is to save the IWebElement result into a temp var, put on small sleep and then click it. Sometimes the browser ui can't handle the commands as fast as selenium issues them.
var el = Setup.Driver.FindElement(By.LinkText(text));
Thread.Sleep(750);
el.Click();
Trying adding a call to System.Diagnostics.Debugger.Break() instead. Or writen the exception.ToString() result to the console.
You are reinventing the wheel here. Selenium can do this method for you:
http://selenium.googlecode.com/git/docs/api/dotnet/html/AllMembers_T_OpenQA_Selenium_Support_UI_WebDriverWait.htm
Related
Look at the following code:
public static string GetCleanURL(string baseURL, string url)
{
string cleanUrl = url.ToLower();
if (cleanUrl.StartsWith("http://"))
{//It already starts with http:// It is already in the correct form return it.
return cleanUrl;
}
The 'url' value passed in is "123.123.123.123:1234/myurl/withstuff.xml". In the 'if' statement, the value for 'cleanUrl' is "123.123.123.123:1234/myurl/withstuff.xml". But for some reason, the code execution goes inside of the if block and 'return cleanUrl;' gets executed.
Here is a screenshot of the current value for 'cleanUrl':
When I plug cleanUrl.StartsWith("http://") into the 'Immediate Window' of my debugger, it returns false. Which is what I would expect. However, the execution is somehow going into the if block as though it had returned true.
Can anybody please explain how this is possible?
SOLVED !!!
I appreciate those of you who helped me out on this one.
I needed to Clean and Rebuild my project and Close and Reopen Visual Studio 2013 about 4 times before the code base and debug stuff was actually in sync. It now appears to be working correctly.
Not sure why it ever got that way, or why I needed to do Clean/Rebuild several times before things synced up. But it is working now.
So, friends, if ever you find your code is just acting crazy and not doing what it should do. Just realize that anybody in their right mind would never become a programmer. Then do a clean / rebuild a few times and pray that the oddity goes away never to return.
Thanks for all your help on this one.
I LOVE fighting with the development tools...
No, StartWith isn't buggy, and works as expected.
Try the minimal code below. Reduce your code to the minimum amount to reprouce the problem. Does this happen everytime?
Does it happen with more than one candidate string? Or only that string?
Something else is going on sorry, the following writes Doesn't start
static void Main(string[] args)
{
string cleanUrl = "123.123.123.123:1234/SomeFile.xml";
if (cleanUrl.StartsWith("http://"))
Console.WriteLine("Starts");
else
Console.WriteLine("Doesn't start");
Console.ReadLine();
}
Is it possible to get run-time information about where a method has returned?
I mean, if the method returned after running all its lines of code, or because of an earlier
return statement that occurred due to some condition.
The scenario is using interceptor for creating UnitOfWork that should exists in method scope.
For example, lets consider this code:
[UnitOfWork]
public void Foo()
{
// insert some values to the database, using repositories interfaces...
DoSomeChangesInTheDataBaseUsingRepositories();
var result = DoSomethingElse();
if (!result) return;
DoMoreLogicBecuseTheResultWasTrue();
}
I have interceptor class that opens thread static unit of work for methods that are flagged with [UnitOfWork] and when the scope of the method ends it run commit on the UoW and dispose it.
This is fine, but lets consider the scenario above, where for some reason a programmer decided to return in the middle of the method due to some condition, and in that scenario the changes made by the repositories should not be persisted.
I know that this can indicate wrong design of the method, but be aware that it is a possible scenario to be written by a programmer and I want to defend my database from these kind of scenarios.
Also, I don't want to add code to the method itself that will tell me where it ended. I want to infer by the method info somehow its returned point, and if it is not at the end of its scope the interceptor will know not to commit.
The simple answer is use BREAKPOINTS and Debugging.
Edit:- As mentioned by Mels in the comments. This could be a useful suggestion.
If your application is very timing-sensitive, set conditional breakpoints such that they never actually stop the flow of execution. They do keep track of Hit Count, which you can use to backtrace the flow of execution.
Just for your attention. From the microsoft site:-
For those out there who have experience debugging native C++ or VB6
code, you may have used a feature where function return values are
provided for you in the Autos window. Unfortunately, this
functionality does not exist for managed code. While you can work
around this issue by assigning the return values to a local variable,
this is not as convenient because it requires modifying your code. In
managed code, it’s a lot trickier to determine what the return value
of a function you’ve stepped over. We realized that we couldn’t do the
right thing consistently here and so we removed the feature rather
than give you incorrect results in the debugger. However, we want to
bring this back for you and our CLR and Debugger teams are looking at
a number potential solutions to this problem. Unfortunately this is
will not be part of Visual Studio 11.
There are a couple ways that normally indicate that a method exited early for some reason, one is to use the actual return value, if the value is a valid result that then your method probably finished correctly, if its another value then probably not, this is the pattern that most TryXXX methods follow
int i;
//returns false as wasn't able to complete
bool passed = int.TryParse("woo", out i);
the other is to catch/trhow an exception, if an exception is found, then the method did not complete as you'd expect
try
{
Method();
}
catch(Exception e)
{
//Something went wrong (e.StackTrace)
}
Note: Catching Exception is a bad idea, the correct exceptions should be caught, i.e NullReferenceException
EDIT:
In answer to your update, if your code is dependant on the success of your method you should change the return type to a boolean or otherwise, return false if unsuccessful
Generally you should use trace logs to watch you code flow if you cant debug it.
You could always do something like this:
private Tuple<int, MyClass> MyMethod()
{
if (condition)
{
return new Tuple<int, MyClass>(0,new MyClass());
}
else if(condition)
{
return new Tuple<int, MyClass>(1, new MyClass());
}
return new Tuple<int, MyClass>(2,new MyClass());
}
This way you´ll have an index of which return was returning your MyClass object. All depends on what you are trying to accomplish and why - which is at best unclear. As someone else mentioned - that is what return values are for.
I am curios to know what you are trying to do...
There are multiple questions (1,2,3,4 etc. etc.) called "Why isn't this exception caught". Sadly, none of these solutions work for me... So I am stuck with a truly uncatchable exception.
I have a piece of code (.NET 4.0) that checks a large textfile for digits and numbers. Whilst testing I got a runtime exception:
What you see here is a try-catch pattern with a catchblock for an ArgumentOutOfRangeException. But during runtime, the try block throws an ArgumentOutOfRangeException that is not being caught.
I read the C# language specification section about the try-catch structure, and it says:
A catch block of a try statement is reachable if the try statement is reachable.
So in theory the above code should catch the exception.
Then I thought it might had something to do with the fact that this code is running in a task (during the processing of the textfile I also want to update the UI so I do it asynchronous). I searched around and then I found this answer by Jon Skeet. Basically suggesting I use Task.Wait in a try-catch block to catch any exceptions.
The problem I am facing now is that I can't really call Task.Wait because that would block the calling thread which is my UI thread! Then I figured that I could create an extra tasklayer to wait for that task:
//Code called from the UI
System.Threading.Tasks.Task.Factory.StartNew(()=>
{
//Create a new task and use this task to catch any exceptions
System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Factory.StartNew(MethodWithException);
try
{
task.Wait();
}
catch(Exception)
{
MessageBox.Show("Caught it!");
}
});
But this still gives the same result... Then I thought that it could be because of the fact I am not specific enough with my Exceptiontype. But the C# Language Specification states:
Some programming languages may support exceptions that are not representable as an object derived from System.Exception, although such exceptions could never be generated by C# code.
So unless you use some sketchy third party API you're always good when you use Exception. So I found myself with an suggested answer by Jon Skeet that didn't quite work for me. That's when I knew I should just stop trying...
So does anyone know what is going on? And how can I fix this? I know I could just check if i is equal or bigger than text.Length but understanding what's happening is more important than working code.
This is simply an artifact of the debugger.
In the Debug menu, there's an option called Exceptions... Click it, and make sure to uncheck the "Thrown" checkbox here:
Many times, you'll want to see the error in context, even if it's inside a try/catch, which is what this setting is for. In this case, that is exactly what you ought to be doing, so that you can see compare i to the length of text and see where your problem is.
If you ran the code without the debugger (such as by double-clicking the executable or using the "Start without Debugging" option), you would "correctly" throw away the error without any alerts.
I just wrote the following test:
[TestMethod]
public void ArgumentOutOfRangeExceptionTest()
{
string test = "abc";
int i = 0;
try
{
while (true)
{
test.ElementAt(i);
i++;
}
}
catch (ArgumentOutOfRangeException)
{ }
}
It is working fine. I believe that you had another exception, which is not called in your calling code.
There is only one exception I know which can't be caught. It's the StackOverflowException. See this question about it.
I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form.
Just let the exception propagate up - you should only catch the exception if you can actually handle it. Exceptions are the "abort mechanism" in .NET. You're currently swallowing the signal that everything's gone wrong, and returning as if all were well.
Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions.
I was really hoping for some sort of like "abort mechanism" that I
could use. Is there any other ways of working around this? Any
interesting work-arounds for this?
Yes, there is. It is called exception handling.
Let's rewrite your code:
namespace PHOEBE
{
public class Analyzer
{
public Analyzer()
{
try
{
DoAnalysis();
DoFurtherAnalysis();
}
catch
{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
public class DoAnalysis()
{
Convert.ToInt32("someNumber...."); //obviously fails..
}
}
Now, the constructor will abort and not run the second method since the exception will "bubble through" and be catched where you want it.
On an unrelated note: Please try to catch as specific exceptions as possible, in this case a FormatException
You are subverting the existing "abort" mechanism by catching an exception that you are not doing anything about and swallowing it.
You should not use a try{}catch{} block in this case and let the exception bubble up and cause the application to abort.
The easiest work-around is don't catch the exception. If that were to happen, it'd go straight past the DoFurtherAnalysis() function and out to the original caller.
Don't see anything anoying in returning and checking bool return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code.
Make code sumple and streghtforward. It's not anoying, it's good.
In your specific case if you want just abort everything, just do not catch exception it will abort your program.
use a try...catch in the constructor?
Well, you've got several issues mixed up here. First, it looks like you do possibly-very expensive processing from your constructor. If that processing can throw, you really don't want to call it from your constructor becuase you don't even have the option of returning an error code.
Second, (and you'll read in many threads here,) how you handlee errors really depends on the application and expectation of your users. Some errors could be corrected by changes to inputs. Others might happen in the middle of the night if analysis takes a long time and you might want to continue with another analysis, logging this error.
So I think we're really going to punt back to you for more information about the above.
You could just move DoFurtherAnalysis(); into the the try block
And I would do this entire process somewhere other than the constructor.
Only thing I ever do in the constructor is initialize properties.
Following method shall only be called if it has been verified that there are invalid digits (by calling another method). How can I test-cover the throw-line in the following snippet? I know that one way could be to merge together the VerifyThereAreInvalidiDigits and this method. I'm looking for any other ideas.
public int FirstInvalidDigitPosition {
get {
for (int index = 0; index < this.positions.Count; ++index) {
if (!this.positions[index].Valid) return index;
}
throw new InvalidOperationException("Attempt to get invalid digit position whene there are no invalid digits.");
}
}
I also would not want to write a unit test that exercises code that should never be executed.
If the "throw" statement in question is truly unreachable under any possible scenario then it should be deleted and replaced with:
Debug.Fail("This should be unreachable; please find and fix the bug that caused this to be reached.");
If the code is reachable then write a unit test that tests that scenario. Error-reporting scenarios for public-accessible methods are perfectly valid scenarios. You have to handle all inputs correctly, even bad inputs. If the correct thing to do is to throw an exception then test that you are throwing an exception.
UPDATE: according to the comments, it is in fact impossible for the error to be hit and therefore the code is unreachable. But now the Debug.Fail is not reachable either, and it doesn't compile because the compiler notes that a method that returns a value has a reachable end point.
The first problem should not actually be a problem; surely the code coverage tool ought to be configurable to ignore unreachable debug-only code. But both problem can be solved by rewriting the loop:
public int FirstInvalidDigitPosition
{
get
{
int index = 0;
while(true)
{
Debug.Assert(index < this.positions.Length, "Attempt to get invalid digit position but there are no invalid digits!");
if (!this.positions[index].Valid) return index;
index++;
}
}
}
An alternative approach would be to reorganize the code so that you don't have the problem in the first place:
public int? FirstInvalidDigitPosition {
get {
for (int index = 0; index < this.positions.Count; ++index) {
if (!this.positions[index].Valid) return index;
}
return null;
}
}
and now you don't need to restrict the callers to call AreThereInvalidDigits first; just make it legal to call this method any time. That seems like the safer thing to do. Methods that blow up when you don't do some expensive check to verify that they are safe to call are fragile, dangerous methods.
I don't understand why you wouldn't want to write a unit test that exercises "code that should not happen".
If it "should not happen", then why are you writing the code at all? Because you think it might happen of course - perhaps an error in a future refactoring will break your other validation and this code will be executed.
If you think it's worth writing the code, it's worth unit testing it.
It's sometimes necessary to write small bits of code that can't execute, just to appease a compiler (e.g. if a function which always throw an exception, exits the application, etc. is called from a function which is supposed to return a value, the compiler may insist that the caller include a "return 0", "Return Nothing", etc. statement which can never execute. I wouldn't think one should be required to test such "code", since it may be impossible to make it execute without seriously breaking other parts of the system.
A more interesting question comes with code that the processor should never be able to execute under normal circumstances, but which exists to minimize harm from abnormal circumstances. For example, some safety-critical applications I've written start with code something like (real application is machine code; given below is pseudo-code)
register = 0
test register for zero
if non-zero goto dead
register = register - 1
test register for zero
if non-zero goto okay1
dead:
shut everything down
goto dead
okay1:
register = register + 1
if non-zero goto dead
I'm not sure how exactly one would go about testing that code in the failure case. The purpose of the code is to ensure that if the register has suffered electrostatic or other damage, or is otherwise not working, the system will shut down safely. Absent some very fancy equipment, though, I have no idea how to test such code.
Part of the purpose of testing is to test both things that should happen and things that can happen.
If you have code that should never execute, but could under the right (or wrong) conditions, you can verify that the exception occurs in the right conditions (in MS's Unit Test Framework) by decorating your test method with:
[ExpectedException(typeof(InvalidOperationException))]
To rephrase the issue, basically: how do you test an invalid state of your system when you've already gone to a lot of trouble to make sure that the system can't get into that invalid state in the first place?
It will make for slightly slower tests, but I would suggest using reflection to put your system into the invalid state in order to test it.
Also notice that reflection is precisely one of the possible ways for your system to get into that invalid state, which will execute your supposedly impossible to reach code.
If your code was truly impossible to reach, which is not quite the case in your example as far as I see, then you should remove the code. Eg:
public int GetValue() {
return 5;
throw new InvalidOperationException("Somehow the return statement did not work!");
}
I also would not want to write a unit test that exercises code that should never be executed.
What do you mean by "should" here? Like, that it ought not to be executed? Surely it should be ok for the code to be executed in a test. It should be executed in a test.