How did the code execution get inside this 'if' statement? - c#

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();
}

Related

Console app quits before foreach loop finishes (C#)

This console app ends before reaching the end, i know that because it usually scans a whole Table in a DB with 5000-10000 rows.
I have no idea as to why it quits halfway, because it has no exeptions or any information (it just shows no information in the logs it just "stops"), and after aproximatly 10-15 mins it abruply stops and exits like everything is fine and it just reached the end of it. When i check the db only 1000-2000 registers have been worked on.
The Code : (Rather simple function any clarification ask and i shall give it, not a reproductive example because its a big development but i will point out what type of information everything is with as much detail as possible)
private List<Item> artigos;
public void VerifyID()
{
//a list cointaining all the rows in the db
artigos = itemCore.GetAllSEAAll();
foreach (var artigo in artigos.ToList())
{
try
{
//Code Here
}
catch(Exception ex)
{
logger.LogInformation(ex.ToString());
}
}
}
TL:DR on code :
I get 5000-10000 rows from a table.
I check a specific field on it and compare to a value (irrelevant for the question) that comes from an api.
I update the db in order to register any anomalies.
(Updated to include only needed code)
It will reproduce the problem i have its just least predictable as to how long until it stops, I am pretty sure it HAS something to do with Garbace Collector or Memory Management
I have so far tried to stop the garbage collector from collecting my variable (artigos).
Resulting is a few (3-5) results of (Object not Initialized) before it quits.
From debbuging i managed to figure out that List artigos, at some point stops existing, GC.KeepAlive() does nothing.
I have searched the web for a similar issue without any luck.
That being and my lack of experience i am currently stuck on what to do, or even what "path" to take to figure out, any help is welcome and sorry if i am missing anything im not familiar with StackOverflow structure
I need to make this clear, i have debuged this program more then i care to remember.
It is not my code that sets artigos to null.
There is no exeption being thown.

Why having a stackoverflow exception before the function is even executed?

I wrote code that overrides object's Equals.
I realized, after I wrote it, that I'm going to have StackOverFlowException since I didn't yet implemented the IEquatable interface to handle the last line of code. Yet, I run the code to see what happen, and some strange thing happen, you can see for yourself in the following image:
The breakpoint isn't even hittable at this moment, seems like the code is being used even before my program is run. Is it something that is done by the CLR ? Is it something else ?
Thanks for the help !
The stack is exhausted (the very last straw that breaks camel's back) on
if (ReferenceEquals(right, null))
probably, the stack doesn't have another 4 (8) bytes to store right.
The actual reason seems to be at
return Equals(right as Quality)
if right is of Quality type, the code is doomed to call Equals again and again

C# and breakpoints - do we have any magician in here?

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

C# Error 'No overload for method 'getData' takes '1' arguments

I am getting the following error:
Error 49 No overload for method 'getData' takes '1' arguments
With this method on the 5th line.
[WebMethod]
public string getVerzekerde(int bsn)
{
ZDFKoppeling koppeling = new ZDFKoppeling();
return koppeling.getData(bsn);
}
The getData method looks like this:
public string getData(int bsn)
{
using (new SessionScope())
{
ZorgVerzekerde verzekerde = PolisModule.GetVerzekerde(bsn);
return "Verzekerde " + verzekerde.Naam;
}
}
I realy don't understand what is going wrong here.. The description of this error on the msdn site didn't help me.. http://msdn.microsoft.com/en-us/library/d9s6x486%28VS.80%29.aspx
Someone who has a solution?
Yeah; somehow you're compiling against a different version of that class. Do a clean build, and double check your references.
Put an error in the GetData() method, then do a full build and confirm that the compiler find the errors. You may be editing the wrong file if you have more then one copy of the source code on your machine, and this will show you if you are.
Also try renaming the ZDFKoppeling class without updating getVerzekerde() and check you get a compiler error. If not you are not picking up the changed class for some reason.
If the above does not give a compiler error, try a rebook, as a process my have the dll locked, and also try a complete rebuild.
These problems normally turn out to be very simple once you have tracked them down. But get take forever to track down.
If another programmer works in the same office, ask for his/her help, as often a 2nd set of eye on the machine can find it quickly.
(I am assuming that GetData() is defined in the ZDFKoppeling class, not some other calss)
This generally indicates that it's not referencing the method you thought it was, but instead a different one. You can generally find out what method that is in Visual Studio by right clicking the method call and selecting "Go to definition". This should help work out why it's calling the one it is and not the one you expect.
Where is the getData method defined? Is it in another assembly? Have you tried rebuilding?
It doesn't look like anything's wrong with your the code.

How can this code throw a NullReferenceException?

I must be going out of my mind, because my unit tests are failing because the following code is throwing a null ref exception:
int pid = 0;
if (parentCategory != null)
{
Console.WriteLine(parentCategory.Id);
pid = parentCategory.Id;
}
The line that's throwing it is:
pid = parentCategory.Id;
The console.writeline is just to debug in the NUnit GUI, but that outputs a valid int.
Edit: It's single-threaded so it can't be assigned to null from some other thread, and the fact the the Console.WriteLine successfully prints out the value shows that it shouldn't throw.
Edit: Relevant snippets of the Category class:
public class Category
{
private readonly int id;
public Category(Category parent, int id)
{
Parent = parent;
parent.PerformIfNotNull(() => parent.subcategories.AddIfNew(this));
Name = string.Empty;
this.id = id;
}
public int Id
{
get { return id; }
}
}
Well if anyone wants to look at the full code, it's on Google Code at http://code.google.com/p/chefbook/source/checkout
I think I'm going to try rebooting the computer... I've seen pretty weird things fixed by a reboot. Will update after reboot.
Update: Mystery solved. Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered.
Based on all the info so far, I think either "the line that's throwing is" is wrong (what makes you think that), or possibly your 'sources' are out of sync with your built assemblies.
This looks impossible, so some 'taken for granted assumption' is wrong, and it's probably the assumption that "the source code you're looking at matches the process you're debugging".
When things look right on the surface then it's likely something you would dismiss. Are you 350% positive that your DLL/PDB matches your source code thus giving you the right line?
Try manually deleting your assemblies and run whatever it is you're running. Does it fail as it should?
Try cleaning out your solution and recompiling. Copy the assemblies to wherever and run it again. Does it work this time? Null ref at the same spot?
Debug the surrounding lines for values you expect. parentCategory, etc. should match what you think.
Modify the code by throwing an exception. Do the stack trace lines match exactly the lines in your code?
I've had some extremely mind-boggling experiences just like this because one of my assumptions was wrong. Typical is a stale assembly. Question all assumptions.
What doesn't make sense, though, is that the OP states that the console.writeline outputs a valid int and it calls the same property as the line where he states the error is being thrown.
A stacktrace would be helpful, or being able to look at the actual unit test.
Yes, could we see the code of the category class .. in particular the Id property? Assuming the Id property is an int (and not a nullable int), the get method must be accessing a NULL object.
Id could be a nullable int type (int?) with no value, however I feel that the property Id must be doing more than just returning an int, and something inside that is null.
EDIT Your edit reveals this is more than peculiar, could you supply us with a stack trace?
I'm not an expert on C#, and am not sure if it makes a difference, but are you debugging in Debug mode, or Release mode? If you're in release mode, the line that your IDE is pointing to and the line the problem is actually on may be different (I know this is the case in C++ when using Visual Studio)
I'd have to agree with Brian... Maybe you're using outdated .pdbs and the code you're seen on debug mode does not comply with the code actually being debugged.
Try cleaning the project, and rebuilding it in debug mode.
Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered.

Categories