I am trying to replace all (or at least most) the Thread.Sleep() in my tests and it seems System.Timers can do the work but I don't know how to implement it.
Or if you guys know another replacement please let me know.
I would really appreciate it if somebody helps me here.
Thank you.
Edit: Sorry, it's my first question here, I should have given an example:
public void AdditionalCardIssueNoBankBranchSelected()
{
additionalCardApplicationPage.ClearBankConsultantCodeField();
additionalCardApplicationPage.TypeSalesOfficer();
additionalCardApplicationPage.TypeEIKBankCustomerAndPressGetDataButton();
additionalCardApplicationPage.ChooseMainCard();
chooseMainCardPage.TypeCustomerEikAndPressSearchButton();
Thread.Sleep(1000);
bankCardSearchPage.SelectFirstValidBankCardOther();
chooseMainCardPage.PressChooseMainCardButton();
additionalCardApplicationPage.PressStartApplicationButton();
Thread.Sleep(1000);
IAlert alert = driver.SwitchTo().Alert();
alert.Accept();
Assert.IsTrue(additionalCardApplicationPage.BankBranchCodeAlert.Displayed);
}
So pretty much everywhere I have Thread.Sleep() is because I am waiting for the page to load in full because if it doesn't next action will not happen as the element I want to interact with is not visible yet.
Sometimes bankCardSearchPage.SelectFirstValidBankCardOther() will not go thru because the table where the cards are is not visible yet.
I hope I explained it well. Thank you.
Thread.sleep()
is an explicit wait but worst of it's kind.
best one is below (Explicit wait):
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//span[text()='OK']/..")));
You can pretty much replace everything with the dynamic wait mentioned above.
What it would do is that to look for web element in DOM for every 500ms until 20 seconds (as we have defined 20 in the above object creation), if found it would return the web element, if not a Timeout exception will be raised.
I've got a method that I'm calling ... well, very often. And now the GC is becoming a problem, because apparently this method is creating garbage, but I can't seem to figure out why.
Item item;
foreach (Point3D p in Point3D.AllDirections)
{
item = grid[gridPosition + p];
if (item != null && item.State != State.Initialized)
else
return;
}
OtherMethod(this);
This method is inside the Item class and figures out the state of neighbouring items. The gridPosition variable is obviously the position of this item inside the grid and the Point3D is a struct that just contains 3 ints, one for each axis. It also contains a few predefined static arrays such as AllDirections which itself only contains Point3Ds.
Now, the state of items can change at any time and once all neighbours have a specific state (or rather aren't in the Initialized state) I do some other stuff (OtherMethod), which also changes the state of the item so this method is no longer called. As such the produced garbage is only a problem when neighbours don't change their state (for example when there is no user input). I guess you could think of this as a substitution for an event driven system.
I admit that I have a rather limited understanding of memory management and I tend to only really understand things by doing them, so reading up on it didn't really help me much with this problem. However, after reading about it I got the impression that every value type, that is defined within a method and doesn't leave it, will be collected upon leaving the method. So I have a little trouble figureing out what's actually left after the return.
Any ideas on what's actually generating the garbage here ? Of course the best case would be to produce no garbage at all, if at all possible.
(Just in case this is relevant, I'm working in Unity and the method in question is the Monobehaviour Update)
Edit for all the comments:
Holy cow you guys are quick. So...
# Jeppe Stig Nielsen: There is nothing between if and else, there was once but I didn't need that anymore. It's just a quick way to leave if no neighbour was found. Also, Indexer ! Completely forgot about that, here it is:
public Item this[Point3D gridPosition]
{
get
{
Item item;
items.TryGetValue(gridPosition, out item);
return item;
}
}
Could the TryGetValue be the reason ?
# Luaan: I already tried a normal for loop, didn't change anything. That looked something like this:
for (int i = 0; i < 6; i++)
{
item = grid[gridPosition + Point3D.AllDirections[i]];
}
If it was the enumerator, that should've fixed it, no ?
# Rufus: Yes that's a better way to write the if, will fix that. The whole thing is a work in progress right now, so that's just a remnant of past experimentation. There is currently is nothing else in the if statement.
# Tom Jonckheere: Well there isn't really much else. It's just Unitys Update() followed by two if statements for the State. And that's really just because I currently only work with two states but have already setup more, so someday there will probably be a switch instead of ifs.
# Adam Houldsworth: Well yes, the problem is certainly that I call it so often. The odd thing is, the amount of garbage produced varies wildly. As far as I can tell it's in the range of 28 bytes to 1.8KB. As for the whole red herring thing, I don't think that's the case. The profiler points to the Update method, which only contains two ifs, one which is the code from above, the other one isn't being used when no state changes occur. And when testing, there are no state changes, except for intial setup.
Also, sorry for the wrong tag, first time I've visited this site. Looks like I'll have some reading to do :)
foreach calls GetEnumerator, which, in turn, creates a new instance of Enumerator every time it's called.
So after Jeppe Stig Nielsen and Luaan made me remember that I'm infact using an indexer I did some googleing and found out that this is not a new issue. Apparently Dictonary.TryGetValue works by calling Equals(object o) on the keys. Now these have to be unboxed which, as far as I understand it, creates the garbage. I now followed the advice I found on Google and implemented the IEquatable interface in my Point3D struct, which does not requiere any boxing. And as it turns out, a big chunk of the garbage is gone.
So the generated garbage per call went from ~28B-1.8KB down to ~28B-168B. Which is pretty good, no more GC spikes. Though I'm still curious where the rest of the garbage is coming from.
Anyway, this was already a big help, so thanks for your answers guys.
Edit: Figured out where the rest of the garbage was comeing from. I just called base.GetHashCode, because I didn't know any better. I did some research into pretty much everything related to hash codes and then implemented it correctly. And now I'm down to exactly 0 bytes of garbage. Pretty neat.
It's very clear in the debugger that the dictionary is populated with the values; so why does it not even ENTER the loop at all? I've tried stepping through and I get nothing. It just skips over the loop. Period. I use similar techniques elsewhere and have no issues. This is all on the same thread so I don't understand.
You can see a video of some of the frustration here: http://youtu.be/XernyY5-BAo
I expect the name == e.Name is false
The compiler probably optimized stepping in this case.
or maybe name is null and it has an exception?
I hate to be that guy and answer my own question but I feel like someone else could learn something from my error.
It turns out, the EntityManager from the base class was implemented separately by the base class in this case, it was over-ridden with the new keyword. This was causing the lists to separate and cause all sorts of ugly issues. Don't hide your inheritance trees, everyone! Always double check your implementations! Thanks for all the help everyone; I still don't know why Visual Studio was displaying different values than it should have so if anyone has any information pertaining to why this might be the case - I'll mark you best answer!
Suppose that we have the code shown below,
LoadOperation lop=_dsrvX.Load(_dsrvX.GetUserDetails(userID));
lop.Completed +=(s,a)=>
{
Debug.WriteLine("Completed but,
First I load it then I registered Completed evet!");
}
I see this type code everywhere so I wonder is it right?
As I know when you call domainService methods this automatically fills domain service object's related EntitySet.
Suppose that LoadOperation(Can be Submit,Invoke ops.) completed rapidly and when I passed to the next line where I register completed event everything has done.Is it possible? It seems hard to achive that but can you give me 100% guarantee?
If you can't guarantee that I'm asking if there is a method of calling OperationBase objects manually?
Any comment will be appreciated.
Well, this is a crazy world, I would not give 100% guarantee of anything :P - But I do not think it should be a problem. If this bothers you, you can pass the callback as a parameter, like this:
_dsrvX.Load(_dsrvX.GetUserDetails(userID), userDetailsCallBack, null);
(...)
void userDetailsCallBack(LoadOperation<UserDetails> op)
{
//do anything with the results
}
or, to simplify even further:
_dsrvX.Load(_dsrvX.GetUserDetails(userID), (op)=>
{
//do anything with the results
}, null);
Yes you can trust it - 100% guaranteed!
If you dig into the code behind the asynchronous Load method, you will see that it starts up another thread, to do the actual load, then returns immediately.
That separate thread then prepares for a service call, performs the service call, and eventually returns the resulting data.
It cannot trigger the Completed event until that is all done and we are talking "a lot" of code to get through, not to mention waiting on a web-service, whereas the return is pretty much instantaneous after the thread was started. i.e. no chance for the other thread to complete and interrupt it.
There is 0% chance that the load will complete before you add the handler on the next line.
The usual approach is to provide a callback or anonymous method instead, but your existing code is fine. MS knew what they were doing when the designed it that way :)
I had this argument with Jon Skeet, on a related question, and his reaction was that you don't know what the Load method is doing so it "might" happen faster than the return... My pragmatic answer was that we know exactly what is going on, by design, and it 100% returns before the Load even commences
In C# I use the #warning and #error directives,
#warning This is dirty code...
#error Fix this before everything explodes!
This way, the compiler will let me know that I still have work to do. What technique do you use to mark code so you won't forget about it?
Mark them with // TODO, // HACK or other comment tokens that will show up in the task pane in Visual Studio.
See Using the Task List.
Todo comment as well.
We've also added a special keyword NOCHECKIN, we've added a commit-hook to our source control system (very easy to do with at least cvs or svn) where it scans all files and refuses to check in the file if it finds the text NOCHECKIN anywhere.
This is very useful if you just want to test something out and be certain that it doesn't accidentaly gets checked in (passed the watchful eyes during the diff of everything thats commited to source control).
I use a combination of //TODO: //HACK: and throw new NotImplementedException(); on my methods to denote work that was not done. Also, I add bookmarks in Visual Studio on lines that are incomplete.
//TODO: Person's name - please fix this.
This is in Java, you can then look at tasks in Eclipse which will locate all references to this tag, and can group them by person so that you can assign a TODO to someone else, or only look at your own.
If I've got to drop everything in the middle of a change, then
#error finish this
If it's something I should do later, it goes into my bug tracker (which is used for all tasks).
'To do' comments are great in theory, but not so good in practice, at least in my experience. If you are going to be pulled away for long enough to need them, then they tend to get forgotten.
I favor Jon T's general strategy, but I usually do it by just plain breaking the code temporarily - I often insert a deliberately undefined method reference and let the compiler remind me about what I need to get back to:
PutTheUpdateCodeHere();
An approach that I've really liked is "Hack Bombing", as demonstrated by Oren Eini here.
try
{
//do stuff
return true;
}
catch // no idea how to prevent an exception here at the moment, this make it work for now...
{
if (DateTime.Today > new DateTime(2007, 2, 7))
throw new InvalidOperationException("fix me already!! no catching exceptions like this!");
return false;
}
Add a test in a disabled state. They show up in all the build reports.
If that doesn't work, I file a bug.
In particular, I haven't seen TODO comments ever decrease in quantity in any meaningful way. If I didn't have time to do it when I wrote the comment, I don't know why I'd have time later.
//TODO: Finish this
If you use VS you can setup your own Task Tags under Tools>Options>Environment>Task List
gvim highlights both "// XXX" and "// TODO" in yellow, which amazed me the first time I marked some code that way to remind myself to come back to it.
I'm a C++ programmer, but I imagine my technique could be easily implemented in C# or any other language for that matter:
I have a ToDo(msg) macro that expands into constructing a static object at local scope whose constructor outputs a log message. That way, the first time I execute unfinished code, I get a reminder in my log output that tells me that I can defer the task no longer.
It looks like this:
class ToDo_helper
{
public:
ToDo_helper(const std::string& msg, const char* file, int line)
{
std::string header(79, '*');
Log(LOG_WARNING) << header << '\n'
<< " TO DO:\n"
<< " Task: " << msg << '\n'
<< " File: " << file << '\n'
<< " Line: " << line << '\n'
<< header;
}
};
#define TODO_HELPER_2(X, file, line) \
static Error::ToDo_helper tdh##line(X, file, line)
#define TODO_HELPER_1(X, file, line) TODO_HELPER_2(X, file, line)
#define ToDo(X) TODO_HELPER_1(X, __FILE__, __LINE__)
... and you use it like this:
void some_unfinished_business() {
ToDo("Take care of unfinished business");
}
It's not a perfect world, and we don't always have infinite time to refactor or ponder the code.
I sometimes put //REVIEW in the code if it's something I want to come back to later. i.e. code is working, but perhaps not convinced it's the best way.
// REVIEW - RP - Is this the best way to achieve x? Could we use algorithm y?
Same goes for //REFACTOR
// REFACTOR - should pull this method up and remove near-dupe code in XYZ.cs
I use // TODO: or // HACK: as a reminder that something is unfinished with a note explaining why.
I often (read 'rarely') go back and finish those things due to time constraints.
However, when I'm looking over the code I have a record of what was left uncompleted and more importantly WHY.
One more comment I use often at the end of the day or week:
// START HERE CHRIS
^^^^^^^^^^^^^^^^^^^^
Tells me where I left off so I can minimize my bootstrap time on Monday morning.
// TODO: <explanation>
if it's something that I haven't gotten around to implementing, and don't want to forget.
// FIXME: <explanation>
if it's something that I don't think works right, and want to come back later or have other eyes look at it.
Never thought of the #error/#warning options. Those could come in handy too.
I use //FIXME: xxx for broken code, and //CHGME: xxx for code that needs attention but works (perhaps only in a limited context).
Todo Comment.
These are the three different ways I have found helpful to flag something that needs to be addressed.
Place a comment flag next to the code that needs to be looked at. Most compilers can recognize common flags and display them in an organized fashion. Usually your IDE has a watch window specifically designed for these flags. The most common comment flag is: //TODO This how you would use it:
//TODO: Fix this before it is released. This causes an access violation because it is using memory that isn't created yet.
One way to flag something that needs to be addressed before release would be to create a useless variable. Most compilers will warn you if you have a variable that isn't used. Here is how you could use this technique:
int This_Is_An_Access_Violation = 0;
IDE Bookmarks. Most products will come with a way to place a bookmark in your code for future reference. This is a good idea, except that it can only be seen by you. When you share your code most IDE's won't share your bookmarks. You can check the help file system of your IDE to see how to use it's bookmarking features.
I also use TODO: comments. I understand the criticism that they rarely actually get fixed, and that they'd be better off reported as bugs. However, I think that misses a couple points:
I use them most during heavy development, when I'm constantly refactoring and redesigning things. So I'm looking at them all the time. In situations like that, most of them actually do get addressed. Plus it's easy to do a search for TODO: to make sure I didn't miss anything.
It can be very helpful for people reading your code, to know the spots that you think were poorly written or hacked together. If I'm reading unfamiliar code, I tend to look for organizational patterns, naming conventions, consistent logic, etc.. If that consistency had to be violated one or two times for expediency, I'd rather see a note to that effect. That way I don't waste time trying to find logic where there is none.
If it's some long term technical debt, you can comment like:
// TODO: This code loan causes an annual interest rate of 7.5% developer/hour. Upfront fee as stated by the current implementation. This contract is subject of prior authorization from the DCB (Developer's Code Bank), and tariff may change without warning.
... err. I guess a TODO will do it, as long as you don't simply ignore them.
This is my list of temporary comment tags I use:
//+TODO Usual meaning.
//+H Where I was working last time.
//+T Temporary/test code.
//+B Bug.
//+P Performance issue.
To indicate different priorities, e.g.: //+B vs //+B+++
Advantages:
Easy to search-in/remove-from the code (look for //+).
Easy to filter on a priority basis, e.g.: search for //+B to find all bugs, search for //+B+++ to only get high priority ones.
Can be used with C++, C#, Java, ...
Why the //+ notation? Because the + symbol looks like a little t, for temporary.
Note: this is not a Standard recommendation, just a personal one.
As most programmers seem to do here, I use TODO comments. Additionally, I use Eclipse's task interface Mylyn. When a task is active, Mylyn remembers all resources I have opened. This way I can track
where in a file I have to do something (and what),
in which files I have to do it, and
to what task they are related.
Besides keying off the "TODO:" comment, many IDE's also key off the "TASK:" comment. Some IDE's even let you configure your own special identifier.
It is probably not a good idea to sprinkle your code base with uninformative TODOs, especially if you have multiple contributors over time. This can be quite confusing to the newcomers. However, what seems to me to work well in practice is to state the author and when the TODO was written, with a header (50 characters max) and a longer body.
Whatever you pack into the TODO comments, I'd recommend to be systematic in how you track them. For example, there is a service that examines the TODO comments in your repository based on git blame (http://www.tickgit.com).
I developed my own command-line tool to enforce the consistent style of the TODO comments using ideas from the answers here (https://github.com/mristin/opinionated-csharp-todos). It was fairly easy to integrate it into the continuous integration so that the task list is re-generated on every push to the master.
It also makes sense to have the task list separate from your IDE for situations when you discuss the TODOs in a meeting with other people, when you want to share it by email etc.