I'm writing a Windows service in C# (Visual Studio 2013).
The service activates a thread for each server it connects with.
The 'server' object is defined as 'ThreadStatic' (so each thread should access it as a different object):
[ThreadStatic]
public static Server CurServer
On debug- I sometimes get the error:
ArgumentOutOfRangeException
Index was out of range. Must be non-negative and less than the size of the collection.
It occures in the following line (inside the method of the 'server' thread):
EventConn.FindString = G.CurServer.FilesList[G.CurServer.nFilesIndex].SearchString;
But the strange thing is that the debugger shows that the values are ok:
G.CurServer.FilesList.count = 1
G.CurServer.nFilesIndex = 0
So there should'nt be any error!!!
When I press F11 (debugger step), it keeps on debugging as if everything is fine and the assignment also works...
Why????? :0
Is it a bug in the Visual Studio that prompts the error before assigning the current thread's values? Or that I'm not using threads saftley (more likely)?
I can't explain the bad display of VS, but I found the cause of the error:
I used object assignment in the thread's method like this:
G.CurServer = server;
Instead of cloning the object like this (How to Clone Objects):
G.CurServer = (Server).Clone();
This first assignment caused values of G.CurServer to change in the different threads even though it is [ThreadStatic].
I hope it helps someone...
Best wishes, Eyal. http://reginiano.com
Related
I am fairly new to the testing environment but I am stuck with a problem.
i have created a test case (a few tests combined in an ordered test) and when I run them on my own pc they always pass (tried it many times to be sure) but when I run the test on our server the test fails at random times.
examples - he doesn't right click a list to get the context menu
- he seems to forget to click on a button so he cant access the next window. etc
if i run the test again he may go over the previous fail but fails on something else.
so far. out of +- 30 times i have run he test i had 5 success runs. and this should be a base test so there should be no bug or known problem.
i have the feeling that the server needs more time to complete the test. so i did research and already added many playbacksettings and a Playback_PlaybackError.
test case made in Visual studio 2013 part with recording part written code. build in visual studio and server tested with microsoft test manager 2013, win8 envir
is there anything i do wrong? or is there something wrong with the server configuration?
Thanks in advance.
so far I tried some of these (and repeat in every testmethod)
public CodedUITest1()
{
Playback.PlaybackSettings.MatchExactHierarchy = true;
Playback.PlaybackSettings.SmartMatchOptions = SmartMatchOptions.Control;
Playback.PlaybackSettings.SmartMatchOptions = SmartMatchOptions.TopLevelWindow;
Playback.PlaybackSettings.SmartMatchOptions = SmartMatchOptions.None;
Playback.PlaybackSettings.SearchTimeout = 2000;
Playback.PlaybackSettings.ShouldSearchFailFast = true;
Playback.PlaybackSettings.ThinkTimeMultiplier = 2;
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.AllThreads;
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.UIThreadOnly;
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.Disabled;
Playback.PlaybackSettings.WaitForReadyTimeout = 2000;
Playback.PlaybackError -= Playback_PlaybackError;
Playback.PlaybackError += Playback_PlaybackError;
}
/// <summary> PlaybackError event handler. </summary>
private static void Playback_PlaybackError(object sender, PlaybackErrorEventArgs e)
{
// Wait a second
System.Threading.Thread.Sleep(1000);
// Retry the failed test operation
e.Result = PlaybackErrorOptions.Retry;
}
Try to use
yourcontrol.WaitForControlReady()
function as well before performing any action on control. This function will stop the thread till your control becomes ready for accepting any action.
Seems the problem was server based. I added a global delaybetweenactions and the test seems to run very smooth. Problem fixed
I had the similar problem with a set of 20 odd Coded UI Tests in my project, which used to randomly fail on the server, but always ran fine locally. We looked out for a number of troubleshooting techniques to overcome this mysterious 'random' factor. The biggest problem while analyzing these test failures is that the error stack trace might indicate the line of code which might be completely unrelated to the actual cause of failure.
We figured out that we can enable HTML logging in our Coded UI tests. This is very easy and can either be enabled for individual tests or for all the tests in the project. Just add the below code to your app.config file
Once you have the tracing enabled, the tests will display step by step details of how Coded UI tried to execute the tests - with screenshots of your application. This is very beneficial in troubleshooting the actual cause of test failures.
First I've read all the posts here regarding this issue and I manged to progress a bit. However it seems I do need your help :)
I have a program with several threads, sometimes (not always) the CPU usage of the program is increasing up to 100% and never reduced until I shut down the program.
As I read in other similar posts, I ran the app using the visual studio (2012 - Ultimate).
I paused the app, and open the threads window.
There I pauses the threads until I've found the 4 threads which stuck the app.
The all refer to the same line of code (a call for constructor).
I checked the constructor inside and outside and couldn't find any loop which could cause it.
To be more careful I've added break point to almost every line of code and resume the app. None of them have been triggered.
This is the line of code:
public static void GenerateDefacementSensors(ICrawlerManager cm)
{
m_SensorsMap = new Dictionary<DefacementSensorType, DefacementSensor>();
// Create instance of all sensors
// For any new defacement sensor, don't forget to add an appropriate line here
// m_SensorsMap.add(DefacementSensorType.[Type], new [Type]Sensor())
try
{
if (m_SensorsMap.Count <= 0)
{
m_SensorsMap.Add(DefacementSensorType.BackgroundSensor, new BackgroundSensor());
m_SensorsMap.Add(DefacementSensorType.TaglinesSensor, new TaglinesSensor(cm.Database));
m_SensorsMap.Add(DefacementSensorType.SingleImageSensor, new SingleImageSensor());
}
}
catch (Exception)
{
Console.WriteLine("There was a problem initializing defacement sensors");
}
}
The second "m_SensorsMap.Add" is marked with green arrow, as I understand it, it means it's still waiting to the first line to finish.
By the way, the m_SensorsMap.Count value is 3.
How can I find the problem?
Is it a loop?
Or maybe a deadlock (not make sense because it shouldn't be 100% cpu, right?)
It's pointless to upload a code because this is a huge project.
I need more general help like how to debug?
Is it could something else than a loop?
Because it's a bug that returns every while and than I'm not closing the app until I found the problem :)
Thanks in advance!!
Edit:
The constructors:
public TaglinesSensor(IDatabase db)
{
m_DB = db;
}
I couldn't found the problem so I've changed the design on order not to call those constructors anymore.
Thanks for the guys who tried to help.
Shaul
I am attempting to call/push a semi-large tiff and a Gal file to a java webservice.
The platform is Visual Studio 2013, C# windows forms application.
I am pointing to the WSDL file and "The Platform" is generating a service reference class for me.
This is all very abstracted from me, which is a good thing as I am a relative newbie to this arena.
I left the "Generate Task based Code" checked and I get an addSample and addSampleAsync method.
I populate the class fields and push the code up.
The addSample code works fine but blocks the UI.
The async code, addSampleAsync, also works, bit is slower and is not completely asynchronous.
addSampleAsync locks the UI for about half of the processing time and the function call to fncTestUpload does not return for that same period of time.
//Dimensioned at class level
//private static addSamplePortClient Service = new addSamplePortClient();
//private static addSampleResponse Myresult = new addSampleResponse();
//ThisRequest is the WSDL modeled class object.
//This code works, but is slow, 30 seconds on wifi
ResponseType Myresult = Service.addSample(ThisRequest.Request);
MessageBox.Show(Myresult.Message + Myresult.Code);
//This code locks up the UI for about 15 - 20 seconds then takes another 15 to display the messagebox
fncTestUpload(ThisRequest);
async void fncTestUpload(addSampleRequest SentRequest)
{
Myresult = await Service.addSampleAsync(SentRequest.Request);
MessageBox.Show(Myresult.Response.Message + " - " + Myresult.Response.Code);
}
I made the response object a class level variable in hopes of doing something with it in the function that calls fncTestUpload, which it thought would return immediately when calling an Async function. It does not return until after 15 seconds.??
I have spent several hours googling this and have not found any answers as to why the addSampleAsync is not working as advertised.
Microsoft's tutorials may as well be written in Dilbert's Elbonian. I can't follow them and don't find them helpful, so please don't direct me to one.
When you use the 'await' keyword in your method you are saying "Ok, you go ahead and do work, I will return to my caller, let me know when you're done".
So the 15 seconds of waiting is the time it takes your service to process the request, then invoking the state machine generated by the async method to return to the method after the previously awaited method has finished. That is the normal behavior for await.
About the MessageBox that is taking 15 seconds, it could be that the Response property is lazyloading and actually trying to load the code / message for the first time wheb you access those properties.
I've got a rather complex Xamarin.Mac application. In fact, it's a windows forms application, but we're using Mono for Mac compatibility with a native Mac GUI. One of our business logic components involves watching the filesystem for changes using FSWatcher. Unfortunately, FSWatcher on Mac is horribly broken, leaving us to use the native FSEvents API via Xamarin.Mac.
Deep down in business logic, I've got a custom class called CBFileSystemWatcher which wraps the .NET FSWatcher, and on mac provides an adapter between the FSWatcher-expecting business logic and FSEvents on mac. INSIDE this compatibility class, I've got
private FSEventStream eventStream;
//...
this.eventStream.ScheduleWithRunLoop (NSRunLoop.Main);
which schedules the filesystem events on the main run loop. Unfortunately, this means the GUI blocks FS event handling, so suddenly if a modal dialog is open, for example, fs events stop getting processed.
My thought is to create a new runloop for the FS event scheduling, which I figure looks like
NSThread.Start(()=>{
// Some other code
this.eventStream.ScheduleWithRunLoop (NSRunLoop.Current);
});
The snag is, I think, that this code runs inside maybe two other layers of thread starts. For testing purposes, I've got the following code where I NEED the above code:
NSThread.Start(()=>{
int i = 0;
});
with a breakpoint on the middle line to determine whether it was hit. 9 times out of ten I get the following stack overflow:
Stack overflow in unmanaged: IP: 0x261ba35, fault addr: 0xb02174d0
Stack overflow in unmanaged: IP: 0x261ba35, fault addr: 0xb02174d0
(the addresses change, though often recur)
One time out of ten the code works exactly as expected and I break on i=0
To test this further, I placed the above test inside my main AppDelegate.cs FinishedLaunching method. There, the code reliably works.
To further confuse matters, I placed the following code at the start of FinishedLaunching:
var fooThread = new Thread(() =>
{
var barThread = new Thread(()=>{
NSThread.Start(() =>
{
int i = 4;
});
});
barThread.Start();
});
fooThread.Start();
With breakpoints on fooThread.Start();, barThread.Start();, and int i = 4; the code works exactly as expected, where the points are hit in reverse order.
My question is, does anyone have any ideas on how to even begin deubgging this? The SO is so out of the blue I don't even know where to start.
A year later, I have this answer for you:
http://forums.xamarin.com/discussion/37451/more-modal-problems-nsmenu-nsstatusitem
I'm having an issue with the ShareLinkTask function from WP8.
I have an app with different pages (to view Comics - one to navigate through the Comics and one page to list a thumbnailpreview of all Comics).
The ShareLinkTask function works just fine as long as I stay in the MainPage.xaml. But when I switch to the Thumbnails.xaml (via NavigationService.Navigate...), select a new cartoon and share it the ShareLinkTask.Show() will show the sharing page and then crash the whole app.
If I make a try-catch around the ShareLinkTask.Show() no exception is thrown.
Here is the ShareLink function - it's called via the "Hold gesture":
ShareLinkTask shareLink = new ShareLinkTask();
shareLink.Title = "a";
shareLink.LinkUri = new Uri(b);
shareLink.Message = "Look at that handsome cartoon!";
try
{
shareLink.Show();
}
catch (Exception a)
{
MessageBox.Show(a.ToString());
}
From the console I get this error line: "System.Runtime.Serialization.InvalidDataContractException" occoured in System.Runtime.Serialization.ni.dll
Now Google doesn't now anything about this problem somehow - to be honest I don't really get / understand what's happening - I don't think that I serialize anything anywhere...
I suggest that I do something wrong by switching back to the MainPage.xaml. All indices etc. are correct and every other function of the app is just working fine.
Does anyone know where to look for the error?
Thanks in advance.
When you call Show, your application is put into a dormant state and may be terminated if the user navigates away instead of completing the task.
When your app is put into a dormant state your data gets serialized, but only classes with "DataContact" attributes can be serialized correctly. So the problem is - you are holding some UNSERIALIZABLE data in you app (Like in PhoneApplicationService.Current.State) . Find out what class causes exception.
Your exception should be like this:
System.Runtime.Serialization.InvalidDataContractException: Type 'TYPE HERE' cannot be serialized.
That will give you a hint of what's going on.