I have the following problem:
I use c++ library from my WPF app, the library throws an assertion in some very rare cases. It shows a nice dialog with c++ filename, the line number and assert expression. So the question is: can I disable asserts in the c++ library assuming that I don't have source code. What I really need is to "catch" this assertion and log it.
Thanks.
One way is to create a thread that performs EnumWindows every so often and detects if an assert window pops up, it can then capture the message and click the ignore button. This will still cause the window to show up for a short while (depending on your interval between EnumWindows but I assume you customers aren't going to be getting the debug DLL so it shouldn't matter.
Another option is calling _CrtSetReportMode(_CRT_ASSERT, 0) to disable asserts from being shown altogether.
If you want to PInvoke this from .NET note that _CRT_ASSERT is equal to 2.
Depending on your assembler skills and whether steps have been taken deliberately to block this type of stuff, it's usually possible to modify binary code to prevent this sort of message being displayed.
However, an assertion firing is often a precursor to some more spectacular crash or other misbehaviour, so just stopping the message box might not get you much further. Of course, some assertions are buggy, so this might be all you need.
If I had to modify this DLL, I would disassemble it with IDA and work out a patch. Hiding the assertion would probably be fairly easy, logging it quite a lot harder.
I recently had to fix some old code which relied on a DLL which sometimes popped up an assert message. I tried all the above suggestions, and the only one which I got working was to click on the Ignore button. The user above suggested running EnumWindows on a separate thread - I used FindWindow instead.
This is the function which finds the Assert popup message, finds the Ignore button within there, and then clicks it. It goes on a loop which checks a global variable each time (ugly but quick):
void CloseAssertBox (void *param) {
HWND window, button;
Sleep (200); //wait 200 milliseconds
while (!finishThread) { //see if we can stop checking
if ((window = FindWindow (NULL, L"Microsoft Visual C++ Runtime Library"))
&& (button = FindWindowEx (window, NULL, L"Button", L"&Ignore")))
SendMessage (button, BM_CLICK, 0, 0); //click the button
Sleep (50); //then check every 50 milliseconds
}
}
The title of your Assert box might be different. If your Ignore button is referenced differently, you can use EnumChildWindows to get the name of each child control including buttons.
Before the bit of code which pops up the assert, I start a new thread which calls the function above.
finishThread = 0; //this is set to 1 when the thread should finish
_beginthread (CloseAssertBox, 0, NULL); //begin the thread
After making it through the dangerous assert-prone code, I set:
finishThread = 1; //done threaded stuff
That way the thread will close next time round its loop. There's probably better ways of doing that.
I had to include these libraries to make it work:
#include <process.h> //for multithreading
#include <WinBase.h> //for Sleep function
int finishThread; //to tell the thread when encoding has finished
This was all done in Visual Studio 2010 using a library from 2006.
Related
I apologize in advance... I'm new to C# and am trying to teach myself (badly)!
I've been set a number of tasks to decipher some code and explain what it's doing, but on these three pieces I'm really struggling - I only have the code detailed - nothing else to put it onto context... otherwise I think I'd be fine.
if (HasMark && !MarkReference.Entity.IsValidOn(DateSignedUp.Value)) {
LogError(PersonMessages.MarkNotValidOnDateSignedUp(DateSignedUp));
My thought:
If HasMark variable is true and the DateSignedUp value is false, then call the PersonMessages error and specify the DateSigned up value.
if (From.HasValue && From.Value<Session.Current.VirtualNow) logError(PersonNonMessages.PastHoliday);
My thought: If From is true and From equals (whatever) "Session.Current.VirtualNow" is, through up the PersonNonMessages.PastHoliday error.
if (pastAuditLogs != null) pastAuditLogs.ForEach(x => x.AuditLogs = auditLogs);
My thought: If pastAuditLogs isn't null, for each entry in the pastAuditLog, loop through and find the latest entry for each.
Could anyone please advise on if any of my assumptions above are correct, or if I'm even close to understanding the code?
Apologies it's so vague - if there was any other supporting code or background scenario it'd be 10x easier to understand!
Many thanks
You're using Visual Studio, correct?
You can right click on any symbol (like HasMark) and then choose Show Definition. Then, you can see a white arrow in a blue circle at the upper left of your pane, that takes you back to where you were. This is an incredibly handy feature for code archaelogy.
Also, if you hover your cursor over code you often get a bit of explanation in a tooltop.
Let's tear apart this hunk of code bit by bit...
if (HasMark && !MarkReference.Entity.IsValidOn(DateSignedUp.Value)) {
LogError(PersonMessages.MarkNotValidOnDateSignedUp(DateSignedUp));
}
It means...
If HasMark is true....
Call the boolean-valued function MarkReference.Entity.IsValidOn() ...
Passing the value DateSignedUp.Value
If that function returns false (!) ...
Call the function PersonMessages.MarkNotValidOnDateSignedUp() ...
Passing the value DateSignedUp ...
and pass the returned value to the function LogError().
The && operator won't perform step 2 above if HasMark is false.
The order I've shown here is important. In this bit of code, the second line seems to have the side effect of marking something not valid. But maybe that MarkNotValidOnDateSignedUp() method just looks up some message to toss into LogError().
To know exactly what all this stuff means isn't possible without having your code base present. That's what you use Show Definition to do.
<CTRL><SHIFT><F> activates a Find All function. That's handy too.
Can you run this stuff in the debugger? If so, step through it with Step Into and see what it does.
Pro tip: There's an addon package to Visual Studio called Resharper. It helps with this kind of code archaelogy. They have a free evaluation and sell personal copies for short money.
This is trivial question but find myself thinking it all the time - often when debugging, I want to break right after a certain line of code executes, and rather than putting the breakpoint on the next line of code (which may be a ways down due to large comment blocks, or putting it on the last line of code and then hitting F10 to go over it after it breaks, I have this urge to put a short stub line on which I will set my breakpoint.
In VBA I'd use DoEvents for this, the shortest thing in c# I've found that doesn't create an annoying compiler warning (the variable 'x' is declared but never used) is:
int x = 1; x++;
Is this about as good as you can get, or is there some other obvious approach to this I'm not aware of?
Note: I am aware of suppressing warnings via:
#pragma warning disable 0168 // get rid of 'variable is never used warning'
...but find it sporadically doesn't work.
For debugging purposes, what I always do is use System.Diagnostics.Debugger.Break(). In practice, it's just like inserting a break point on a statement but is much easier to determine its function after the fact, and is maintained through source control between users and systems. It doesn't clutter your Breakpoints window. It also, helpfully enough, will not trigger when running in Release mode, allowing you to place these in areas of critical importance, and leave them in without harming your customer releases.
As an alternate suggestion, following InBetween's comment:
If, instead, you are looking for a "harmless" statement that you can simply set a breakpoint on when you desire, Thread.Sleep(0) should be similar enough to your anecdotal VBA solution to suffice for your debugging purposes.
Thread.Sleep(0). This tells the system you want to forfeit the rest
of the thread’s timeslice and let another, waiting, thread run.
-- http://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/
This would be a less ideal solution in my mind than my first suggestion, but it may be more what you're looking for.
So you need to
write code which does nothing, but can accept a breakpoint, and
tell other programmers that it does nothing (so they don't try and "fix" it).
Make a function which does nothing:
// Call it anywhere, so you can put a breakpoint on the code
public static void DoNothing()
{
// Any code which does nothing here
}
Then call it:
... some code ...
DoNothing();
... other code ...
I have been learning C# using the book "Programming in the Key of C#...", this book has been very good in helping me understand the language but only deals with Console programs. I am ready to move on to developing versions of my past coding projects as Windows form applications but one program in particular is causing me a lot of frustration. I developed a simple movie trivia program utilizing arrays to hold the questions, answer choices, and the correct answer. It worked by displaying on the console the questions, the possible answers and waited for the user to provide a response (basically A,B,C or D) by using Console.Readline() to assign the response.
Now I want to be able to have the user enter the answer by selecting 1 of 4 buttons (A through D). Based on my old code, I am unsure how I get the program to wait for the user to click one of the buttons. I assume i need to change the nature of the loops but I just cant figure out how. Any help would be much appreciated.
Here is a snippet of my Console code:
while (iAsked < 5)
{
iLocation = rand.Next(0, astrQuestions.GetLength(0));
if (list.Contains(iLocation))
rand.Next(0, astrQuestions.GetLength(0));
else
{
iAsked++;
list.Add(iLocation);
Console.WriteLine("Question {0}", iAsked);
Console.WriteLine("------------");
Console.WriteLine(astrQuestions[(iLocation)]);
Console.WriteLine(astrChoices[(iLocation)]);
Console.Write("Answer:");
iResponse = Console.ReadLine();
if (iResponse == astrAnswers[(iLocation)])
{
Console.WriteLine("Correct\n");
iPoints += 5;
iCorrect++;
}
else
{
Console.WriteLine("Incorrect\n");
}
}
Moving from a prompting-centric environment like a console program to an event-driven environment like Winforms, yes…that definitely will require at least some change in "the nature of the loops". :)
That said, the latest version of C# offers an async/await-based approach that can minimize some of the culture-shock that might come from moving from console to GUI. Writing and using async method is itself non-trivial, but IMHO the simpler scenarios are not too hard to understand. More importantly, because it allows you to structure the code in a more directly-imperative way, similar to that which would be used in a console program, it's very much worth learning this along with Winforms generally.
In your particular scenario, you have two separate things you'll need to deal with: prompting the user, and receiving the user's input.
Because of the way an event-driven system works, you need to separate these tasks. But .NET has a class, TaskCompletionSource, which we can use to keep the two glued together, even though they wind up in different places.
First, what happens when the user starts the process? Presumably, you'll have a form, where on that form is a button (or possible a menu item) which when clicked/selected, starts the whole thing. That might look something like this:
private TaskCompletionSource<bool> _completionSource;
private async void button1_Click(object sender, EventArgs e)
{
int[] questionIndexes = ShuffleQuestions();
for (int iAsked = 0; iAsked < 5; iAsked++)
{
textBoxQuestionNumber.Text = string.Format("Question {0}", iAsked);
textBoxQuestion.Text = astrQuestions[questionIndexes[iAsked]];
textBoxChoices.Text = astrChoices[questionIndexes[iAsked]];
_completionSource =
new TaskCompletionSource<bool>(astrAnswers[questionIndexes[iAsked]]);
button2.Enabled = true;
bool result = await _completionSource.Task;
MessageBox.Show(result ? "Correct" : "Incorrect");
if (result)
{
iPoints += 5;
iCorrect++;
}
button2.Enabled = false;
_completionSource = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (_completionSource != null)
{
_completionSource.SetResult(
textBoxUserAnswer.Text == (string)_completionsSource.Task.AsyncState);
}
}
(I have changed your question-selection logic above to something more efficient, by assuming that you have a ShuffleQuestions() method. See Is using Random and OrderBy a good shuffle algorithm? for details on how to implement that).
What the above code does is, in response to the user clicking the button1 button (which presumably has text like "Start" or something), executes a loop that is very similar to what you had in your console program. The two main differences are:
Where in your console program, you use Console.WriteLine() to display text to the user, here I have shown the use of TextBox controls in your form which are used to display the same text.
What in your console program, you use Console.ReadLine() to receive input from the user, this loop creates a TaskCompletionSource object for a completely different method to use. That method, which is executed with your button2 button (which presumably has text like "Check Answer" or something) will read the text entered in a text box by the user (here, I've given it the name textBoxUserAnswer), compare it to the correct answer for the question (which has been provided to this method by the other method via the AsyncState property of the Task created by the TaskCompletionSource object I created), and set the Task's result to true or false, depending on whether the user got the answer correct or not.
The tricky part above is that "under the hood", that first method actually returns as soon as it is done filling in the text for the first question and reaches the await statement in the loop. The compiler rewrites the entire method to facilitate this.
When button2 is pushed, and sets the result of the Task, the framework then knows to resume executing the first method where it left off at the await statement, continuing your loop.
This sequence continues until the user has answered all of the question.
Some final notes about the UI:
I have used TextBox's everywhere for user input and output. Of course, there are other ways to display text. Also, the default state for a TextBox is a single-line, read/write text. But for displaying to the user, you may find that setting the ReadOnly property of the TextBox to true is better (i.e. to prevent the user from accidentally changing the text), and/or that you prefer setting the Multiline property to true (i.e. so that more than one line of text is displayed).
The above also assumes that the initial state for the button2 button's Enabled property is false. I.e. that button can't be clicked until the first method above explicitly enables the button at the appropriate time.
UPDATE: turns out that this is a problem with the Mono compiler used by Unity3D. I'm not sure if the current version of Mono (3.10.0) fixes it, but the old version used in the engine (2.0.5) seems to not implement this feature for delegates, or simply work as it should.
At some point in a game I'm developing (in the Unity3D engine), the player unlocks several items at once. For each of them I must present a simple information dialog that the user must click to advance to the next, until all have been read.
I have a simple C# static method to show a dialog (just a colored overlay with some text in Unity, and NOT in any way related to C# UI frameworks):
ConfirmationDialog.Create("Item X Unlocked!", callback);
When the user finally presses the dialog, callback is called.
I wanted to chain all dialogs so that each one is only created when the previous is clicked on, so I tried this:
Action callback = delegate {};
foreach (string item in unlockedItems) {
var cb = callback; // I though this would create a closure for delegates too
callback = (() => ConfirmationDialog.Create(item + " Unlocked!", cb));
}
callback();
This made sense in my head, as the anonymous function would use a different "cb" delegate in each iteration of the cycle. It seems I'm mistaken, though, as this code seems to result in the same dialog being repeatedly called when clicked, as would happen in a recursive function (which I guess is what it became).
I know I can, for example, do int value = i; inside a for loop (where i is the loop iterator) to use the correct value of i inside the anonymous function (I found a lot of material on this). Delegates seem different, but what in particular makes them not work in the same way? Or am I doing something terribly wrong? Could I do this chaining in some similar way? I say "similar" because I can certainly think of doing this in other - more complicated - ways...
Note: please DO correct me if my use of the words "closure", "delegate", etc, is not right :)
Do you have control over the ConfirmationDialog.Create("Item X Unlocked!", callback); API? If so, instead of taking a callback, you should look at refactoring that to use Task. If you had that, you could simply chain a bunch of tasks as continuations and have them execute one after the other.
I know with game development, these things are often quite asynchronous in nature, the way UI gets shown and subsequently reacted to ... so you could use TaskCompletionSource so you have a handle to something that you can signal that your task is done.
I'd like to add "IDLE-like functionality" to C# WinForms application, but I don't quite have an idea how to do that and couldn't find anything useful with Google.
So basically I want interactive command line interface, where user could enter some Python code and execute it (not just expressions, should be possible to define new functions).
So, where to start? Are there any good tutorials or samples available?
If my memory serves me correctly there's a chapter on embedding Python in the book Python in a Nutshell. Perhaps you can find some useful information there, but since the book is not Windows specific, you may have to adapt it yourself.
I would setyp my WinForm like this: add 2 textboxes.
1: for output. Set the multiline property of the first to true, and make it read only.
2: for input. Use KeyUp Or KeyPress Event for e.g. the return key and use the text to do what you want: add command to output textbox, launch code against the engine and capture output of interpreter
This link (http://groups.google.com/group/ironpy/browse_thread/thread/5e61a944c7c94d4b/0cbf29ec0f5fbb64?pli=1) might give some answers about launching commands agains a python engine.
IronRuby comes with a command line interpreter. Doesn't IronPython also have one? If so, the source code would be a good start :)
Oh, and if it doesn't, be sure to look at the IronRuby interpreter, because both languages are based on the DLR and are therefore similar enough to learn from both.
Thru IronPython mailing list I found IronTextBox2, which is good example how things are done. It needs a little tweaking, to get it running, but otherwise is good solution.
Here go my most generic solution:
Point cursorPoint;
int minutesIdle=0;
private bool isIdle(int minutes)
{
return minutesIdle >= minutes;
}
private void idleTimer_Tick(object sender, EventArgs e)
{
if (Cursor.Position != cursorPoint)
{
// The mouse moved since last check
minutesIdle = 0;
}
else
{
// Mouse still stoped
minutesIdle++;
}
// Save current position
cursorPoint = Cursor.Position;
}
You can setup a timer running on 60000 interval. By this way you will just know how many minutes the user don't move the mice. You can also call "isIdle" on the Tick event itself to check on each interval.