Perhaps you are an accidental programmer. You are the person at your organization who was in charge of some laborious business process and you thought "Gee, we have this InfoPath thing. Maybe I can build a little form for this?". You build the form...and suddenly everyone wants to know if you can do this or if you can do that. You run into a couple of the things that InfoPath doesn't do out of the box, and you see some code samples hanging around....
Next thing you know, you're writing managed code. Or at least copying and pasting managed code and trying to get it to work for your form.
With InfoPath 2007 came VSTA (Visual Studio Tools for Applications). This can be an incredible boon to the accidental programmer, because you can leverage the rich debugging experience of Visual Studio to find your code issues and errors. If you are trying to adapt someone else's code sample for your form, or follow a tutuorial that just isn't working for you, one of the first things you can do is run the project in debug mode.
For the purposes of this simple sample, I've added a loading event to my form.
VSTA opens with the event added:
I've written a little code to set a field's value:
Now, I'm going to add a breakpoint. Click in the margin of the code editor window by the line you want to stop at, and you'll see a big burgundy dot in the margin, as well as a highlight on the line:
We need to run the form from VSTA, so click the toolbar button that looks like an old school tape player's Play button (also under the Debug menu, Start Debugging):
When the form hits that line of code, you'll see it hightlighted:
And now we can have a little fun. Use the Step Over button to go to the next line:
And hover your mouse over the variable that you just set to see what value it has. You can also right click the variable and either Add Watch or Quick Watch to see its values:
Let's see what happens if I have the XPath wrong in my code (a frequent cause of errors -- I'd really have thought that the IP 2007 Copy XPath feature would have prevented those, but we all love our copy / paste too much when it comes to code....):
Not too surprisingly, my XPathNavigator is null, and look what happens when I try to set its value:
Everyone's favorite, the NullReferenceException! But now I at least know the source of my troubles -- that the XPathNavigator I'd created was null. I can focus on the line that is the problem, make adjustments and run my code again.
Setting breakpoints and walking through your code while it runs will not only help you find and understand errors, it will help you understand just what the code is doing in the first place. If you are an accidental programmer, watching your code run can help you learn the syntax and logic of the code sample you've found someplace online, and help you see what you need to do to get that sample to work with your unique form. Happy Debugging!