ExecutionEngineException with SQL and LINQ - c#

My code is trying to load from a database using LINQ to SQL. At the moment as soon as i seem to touch what a query returns i get a crash with the error ExecutionExceptionError occured:
Currently my code is very simple, i have a standard dbml class that is meant to load a single table MC:
private void RibbonButton_Click(object sender, RoutedEventArgs e)
{
MultipleChoiceDataContext t = new MultipleChoiceDataContext();
var test =
from a in t.GetTable<MC>()
select a;
testbox.Content = test.First().question;
}
The error takes place on the line of
test.First().question;
I cannot find any help in the area or someone who has experienced this problem before, so i'm hoping someone may have an idea of how to fix this

ExecutionEngineException indicates an internal problem to the CLR. It means one of the following:
You used unsafe code or PInvoke to cause memory corruption. The CLR's data structures are now corrupt.
Some other library did this (a bug).
A bug in the CLR itself.
In all cases the solution is to work around the issue, maybe by changing things randomly until the application unbreaks. Try refactoring your code, comment out stuff until the error disappears. Factor things out into new methods. Think whether a library you are using might be doing unsafe stuff. Maybe the stack trace can tell you what functionality to avoid.
This is a deeply unmethodical approach but the best that I know of. Very hard to work around because you did nothing specific wrong. In particular, the line of code that you showed cannot normally cause memory corruption.

So turns out the problem was due to the installation of the preview of Visual Studio 2013, upon uninstalling that, the solution worked perfectly again on Visual Studio 2012
Thanks for all the help!

Related

Is there a way to determine the line of code that causes a type to be loaded?

The problem is that I often get a TypeLoadReflectionException and my ability to find the cause for them is very limited, essentially nil actually.
Today I again had a problem like this and couldn't solve it. For some reason my assembly required another assembly which never happened before and even reverting the code to a previously working state did not fix the issue. I'm stumped, there must be deeper issues here.
Is there any way to debug this properly? Ideally a tool like Reflector or IlSpy would be ably to tell me "dependent assemblies" and "type dependencies" per line.
Seeing as how the C# 4.5 Roslyn compiler is now open source, this should theoretically be doable, after all the compiler at some point during the compilation process decides "hey, i need this type for this stuff to compile". Correct? However these TypeLoadExceptions occur at runtime, so I'm not sure.

Can't fill CheckedListBox

I am trying retrieve data from a database. I have added a .sdf file and wrote the code shown below. My table name is info and it has three columns: id, name, and code.
What I want to do is to populate a CheckedListBox with this data, but nothing happens when I execute my code. CheckedListBoxis empty. What am I doing wrong?
SqlCeDataReader dr;
SqlCeConnection con;
SqlCeCommand cmd;
void loadData()
{
cmd.CommandText = "select column_name from Information_schema.columns where table_name='info' order by ordinal_position";
con.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read()) {
checkedListBox1.Items.Add(dr[0].ToString());
}
dr.Close();
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlCeConnection();
con.ConnectionString=#"Data Source=c:\users\xxx\documents\visual studio 2012\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database1.sdf";
cmd = new SqlCeCommand();
cmd.Connection = con;
loadData();
}
You are basically asking for your code snippet to be debugged. This is tricky for a couple of reasons. Firstly your code calls out to a database, and does a slightly weird query in that it is getting information on columns from a system database rather than something from your own table. No-one here knows exactly what the result of that will be. It might be possible to replace that line with something else which has a similar effect (eg a list which is initialized with some dummy values in the code), but by doing so we might change the behavior so that the bug disappears, and we would be none the wiser. We will come back to this idea in a minute.
A question like this is not ideal for StackOverflow. One reason is that which I have just outlined - it could be very difficult to replicate exactly what your code does in order to help you. Therefore you might not get a useful answer. Another, slightly opposed reason is that someone (slightly more diligent and observant than me) might spot a simple typo or gotcha in your code. This might have already happened while I type this. They will post an answer or a comment pointing this out to you, and you will fix your code. However, the question is then not particularly useful to anyone else. No-one is likely to make quite the same typo or slip as you. Even if they do, it will probably be in a slightly different context, unrelated to CheckedListBox or SqlCeDataReader, and they will never find this question.
Those type of questions-and-answers essentially add nothing to this site. They also won't be particularly helpful to you, and this is why: you won't learn to debug.
In my experience, great programmers are almost always good debuggers. Most of us make a lot of small mistakes - finding and fixing these quickly is the difference between average productivity and great productivity. Being a good debugger also means you have a different relationship with your thoughts and your (or someone else's) code. You are able to think more flexibly, holding many different cases and possibilities in your mind at the same time. This is called divergent thinking, and is slowly being recognized to be just as important as convergent thinking, thinking which leads to an answer.
What you should do to progress with your problem and as a programmer, is debug properly. If you had done this and were still faced with a difficult question (or maybe a bug in your tools), you would have a much shorter code snippet to post, and would be able to describe the unintended behavior much better.
There are basically two ways of debugging code like this - stepping through it, and 'print lines'. (Weird and difficult code like kernel code, multithreading and message passing might be much harder to debug - these two techniques will get you a long way with everything else.) The main idea in both is that you look at intermediate values of your variables, at different stages of evaluation. Debugging support for stepping through C# code in Visual Studio is very good, but to keep things simple and reasonably language independent, I will use print lines as an example.
Just add a line anywhere in your program, which you want to know if the execution flow gets there or not. For example
Console.WriteLine("We do have some rows");
should go after the if (dr.HasRows) { line. If this is a console program and you run it, you will see this output appear (or not) in the console window. Otherwise you could use Debug.Print to send the text to the 'Output' window of VS, or a Winforms MessageBox to display the text in an alert window.
You will find out straightaway if your query result has any rows or not. If it doesn't, you have a problem with your query or the way you execute it. You should first of all run the same query on the same database in a different way, for example sqlcmd or Sql Server Management Studio. The fact that you hadn't done this, and that you didn't know if dr.HasRows was true or not, showed me immediately that you weren't debugging properly. [Edit: #Leonardo also pinpointed exactly this same thing in a comment.] If you get some valid response rows when running the query elsewhere, but not when running this code, there is some problem with how you set up the connection or run the query in C#. If you don't get any rows, there is a problem with your query itself. Try different queries directly until you get the right one, then put it back into the C# code. (The third possibility is that 'no rows' is the right response, and that your code should know how to deal with this case properly.)
Suppose on the other hand that dr.HasRows is true. There is some problem with dr.Read or with adding to the checkbox. To eliminate the former, try using a printline in the inner loop. This time output the value you are interested in:
Debug.Print("Value to be added is: " + dr[0].ToString());
You will quickly see if these look reasonable or not. If they do, try and find out what is going wrong with checkListBox1. Print the value of checklistBox1 and/or checkListBox1.Items after each iteration of the loop. Try writing some different values, possible a string constant or a hard-coded list of strings to Items instead and see if it works. Make sure that checkListBox1 actually is empty, and that you actually call the code to fill it up before accessing it.
Well done, you've just learnt the main two parts of one of the two main methods of debugging. You can identify how the code loops and branches (by putting in information print lines)
Console.WriteLine("Got this far!");
and you can find out what the value of your data is (by printing the actual values of variables)
Console.WriteLine("x is currently equal to " + x.ToString());
The nice thing about printlines is that whenever you control some kind of output or logging, you can debug like this without any other tools.
Now you are going to test each step of the code, observing the data passed to it and back from it. Try and find out exactly which parts are working as expected, and which parts are already using bad information passed to them by a previous step. Any bit you are not sure about (like the db accesses), you try and re-run in a different way to how it's used in your code. For example, write a two-line program which creates and displays a ListCheckBox, to make sure you know how to do it.
If you are using some extremely experimental tool, you might end up finding a bug in it, and that your own code is fine. This is very very unlikely with what you're doing, using technology that has been extensively tried and tested by others. The most likely outcome is that you find your (probably simple) bug and fix it. Other than that, it is possible you come back to StackOverflow with a much smaller test case, asking about something non-obvious in the way you use the components or some other straightforward query that is hard to figure out yourself. (Both Winforms and SQL Server do contain many gotchas, which lead to good questions that help others..) When you do, you will be able to share the results of your debugging to let answerers know exactly where the code doesn't seem to behave as expected. It's also very likely that if you do have a problem like this, you can search and find that someone else has already come across it and had it answered.
Don't forget, once you've finished debugging you can take your working code to http://codereview.stackexchange.com to get advice about making it shorter, more elegant, better performing and more error-proof. Good luck!
Please try use the command text as below:
cmd.ComandText = "Select * from infor".

How to stop VisualStudio from expanding everything when deleting { } brackets

I asked this question few days ago and didn't get an answer, so I'll try again precising it a little.
I like to keep my code rolled up by collapsing methods, comments and xml summaries that I don't use at the moment. However, every time I edit some braces in a method, loop, switch statement or any part of the code (anything containing { or } brace), everything below expands after 1 second. Everything unfolds all the way down till the end of current file (or region, if edited code lies within it).
I can't take it anymore I'm tired of using Ctrl+M+O all the time and then re-finding edited field again. Is there any option or extension for VS2010, that would solve my problem?
Update
I'm starting to realize there's no way to solve the problem. However I could also accept an answer to a modified question: Is there a way or tool that would allow me to automatically delete { and } brace pairs containing only 1 instruction? It'd be an acceptable workaround for my problem.
If I understand what you need then you are asking how to stop the code below the line that I am editing from automatically expanding.I would like to tell there is no solution either from official sources or anything.Code collapsing a feature of ideal code editors like Visual Studio.
Let me explain you why this happens and how to prevent it.First let me explain essential conditions for code collapsing to work.Ideal code editors make use of Lexers and Parsers for the language the support,parsers make use of regular expressions to match language specific syntax entered by Coder or someone,in this sequence code editor stores all the locations where specific symbols like ;,{ and },".
In order for code collapsing to work effectively there must be equal number of theses symbols specified in exact order in the code being edited,whenever there is something in the source code which does not match the language specific syntax the parser flags reports the editing and formatting engine of this error.
Coming back to your problem,lets talk about what you face,to better understand it lets consider a simple code block;
and consider there are more functions below AddNumbers that are also collapsed.Now If I understood you,then you said if I editMultiplyNumbersand remove its starting curly brace{`,the all the code below this point automatically expands.
If this is the case then the problem is because parser tries to match the language syntax and searches for any terminating curly braces below this point which is found in AddNumbers's terminating curly brace.
Update :
In one line,there is no solution to this problem,this is because Visual Studio performs Real time parsing,that's how it shows you errors at real time.Actually this is not a problem that's why this has never been reported due to which there is nothing available from official sources.However you can prevent this by changing you coding habits a bit,like when you are creating a function suppose SomeFunction(int a,int b),try to first complete the outer side of function like below;
private void SomeFunction(int a,int b)
{
//Write code later.
}
First create the function outline as above and then write some code in it like below;
private void SomeFunction(int a,int b)
{
int z=a+b;
Console.WriteLine(z);
int x=a*b;
Console.WriteLine(x);
int p=a/b;
Console.WriteLine(p);
int q=a-b;
Console.WriteLine(q);
}
Next consider you are writing an if statement,first complete the outer side like this;
if(//We'll define condition later)
{
//Write function body later.
}
If you've used code snippets in Visual Studio,then you might have noticed Visual Studio generates the snipett's outer side first,then it places the caret to first argument.
So,these are some guidelines,something that can prevent the issue.
Now head towards solution,to prevent this situation when you create a function try to first place its { and } braces before writing any code in it.
Hope this prevents the issue you are facing.If there's anything more you are facing please let me know.
I am using folding myself for a static class containing localization text, and it is pretty nice to be able to hide/show things, similar to how TreeView does with nodes:
And I have never ever faced the described problem or been annoyed with something that VS does.
However, when you are editing code, such behavior is a bit too much for Intellisense I think (as already described in another answer). Perhaps you should change your "way of thinking" ?
Take a look:
You can quickly navigate between members or have a brief overview of them by using this special window, while having all the code unfolded.
I have seen some people like #region much. But you can achieve the same (if not better in all measures) by using partial and splitting single class into pieces.
p.s.: and with last your question, why don't you just select first what you need to delete and then press Delete ? Or what would that tool do for you? Automatically go through sources, detect that and delete? If you are a programmer, then making software that will do that shouldn't take more than writing you question here =D
I'm not sure exactly what the issue is here, as this certainly doesn't seem like normal behaviour (I've never experienced it).
There are a few options though (without knowing more about the problem) that might help you.
Firstly, someone has given a very good answer on another thread about customising the visual studio intellisense: Custom Intellisense Extension
If that isn't an option, perhaps have a look at the extensions that are provided for Visual Studio 2010.
Productivity Power Tools might help you out with some of your refactoring. You can get this through Visual Studio by going to Tools - Extension Mananger. And then select the option and Install it.
Power Tools is quite limited so this might not be enough. I'm sure people can offer other alternatives but I would certainly recommend ReSharper: http://www.jetbrains.com/resharper/.
You can get a free trial but after that period you have to pay for it. I use it and the extensions it provides are fantastic. You can completely change the way Visual Studio behaves for your personal preferences.
Sorry I can't offer any other help, but if you can provide some more information then maybe we can find a solution (e.g. What do you mean by other methods are expanding etc).
Well, this problem that you encounter is a universal one and it can be sometimes irritating. In my experience, visual studio goes haywire especially when you are writing a lot of block statements in a large code file, whenever such happens you can save your work and restart VS. But to answer your question, make sure that you first try to open any collapsed code you want to edit and as for copying/cutting try to highlight the collapsed code first before carrying out of the editing options this informs the editor that you want to edit the highlighted segment of code. Hope it helps
Maybe this can be of some help ?

How to catch and save compile time and run time errors of my solution project in Visual Studio 2008/2010

I am currently trying to figure out a way on how I can possibly save the compile time and runtime errors (in database tables) that the project/solution/website in my visual studio solution explorer could possibly throw.
Thanks for the help in advance.
Update: For now I would want to log the errors only for C# language.
I am desperately looking for a way or solution to implement this...any help will be deeply appreciated...
NiK.
Compile time errors are saved in a html buildlog, check your output window for the link. Shouldn't be too hard to put in a database. A piece of software that does use this information is CruiseControl.Net, so you could probably learn from looking at their code.
For runtime errors, it's impossible to answer. First of all, it's unclear what you are asking. By "runtime errors", do you mean exception eg divide by zero? Second, this is also very different between different languages supported in VS, eg .NET languages and straight C++.
Update: Since you're on the .NET platform, I suggest you either wrap your main function with a try/catch block that catches all thrown errors, and just log all the information you can get from that error to your database (eg stack trace, Exception kind, perhaps a minidump). This, of course, will not work with errors that are caught or swallowed. In case you would also want to log those (for whatever reason), you would have to do some more clever source transformations, for example by using reflection. An example would be to add logging to the constructor of the base class Exception.
My suggestion would be to look into developing an extension to visual studio, similar to Jetbrain's Resharper. Visual Studio exposes a rich api for interacting with the IDE itself. If you are using command line builds outside of visual studio, you may need to pipe the output to a file and parse it.
Here's a few links to get you started on developing an extension/add-in:
http://msdn.microsoft.com/en-us/library/dd885119.aspx
http://msdn.microsoft.com/en-us/vstudio/bb968855
And here's a link for a video for integrating with the error list:
http://msdn.microsoft.com/en-us/vstudio/cc563922
Runtime errors may be easier since there is an appdomain exception event that you can handle. You can wire up a handler to this event and log the exception.
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
For handled exceptions, there are a couple of techniques. Microsoft has an exception handling block that can be used, or you could create a custom exception type that you use throughout the application.
Sound like you want this for a website. You can create a Global class (Global.asax.vb) and then handle the error in the Application_Error event. This is where you deal with any unhandled exceptions (vb example is what I have):
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Fires when an error occurs
Dim appException As System.Exception = Server.GetLastError()
Dim tempException As System.Exception = Nothing
If appException Is Nothing Then
Return
End If
tempException = appException.InnerException
tempException will hold the unhandled exception and you can store it in a database, or email it to someone. Your choice.
You can do something very similar in winform apps by handling the _unhandledException event in the Application events.
Visual Studio Project files are MSBuild files which can contain custom compilation steps. Maybe it's possible to replace the compilation step with a custom step which calls the CSharp compiler and logs the error.
If you give us a bit more information on what you want to use it for, maybe we can provide alternative solutions. For example do you need to log the errors from inside visual studio or is it enough to have an external tool log these errors?
Only the C++ compiler does a buildlog. C# does not. You will have to either go the plugin/extension route (in which case, use Dave Ferguson's suggestions to get started) or you can use the command line to compile (csc.exe) and pipe the output to a file (csc.exe /options >> log.txt), and parse it.

Do you use regular builds as a coding tool?

We have a large (about 580,000 loc) application which in Delphi 2006 builds (on my machine) in around 20 seconds. When you have build times in seconds, you tend to use the compiler as a tool. i.e. write a little code, build, write some more code and build some more etc etc As we move some of our stuff over to C#, does anyone have a comparison of how long something that size would take to build? I only have small apps and components at the moment, so can't really compare. If things are going to take a lot longer to build, then I may need to change my style! Or is my style just lazy?
For example, if I'm changing the interface of a method call, rather than do a full search on all the app to find out where I need to make changes to calls, I'll use the compiler to find them for me.
Visual Studio 2008 SP1 now has background compilation for C# (it's always had it for VB.NET). Back in my VB days, I often used this to find where something was referenced by changing the name and then seeing where the background compiler said there was an error.
I never worked on anything quite this large. At my last job we had about 60,000 loc spread over about 15 projects and it took about 10 seconds to compile. Maybe someone else can post a slightly larger case study
I used to use the compiler as you describe, but since I've been using ReSharper I do this a lot less.
Also, for things like rename, the refactoring support (both in Visual Studio 2005 upwards and, even better, from ReSharper) mean I don't have to do search + replace to rename things.
One thing you can take advantage of, especially in desktop apps, as I imagine you are dealing with coming from Delphi, is Edit and Continue. This lets you change actual code while you are running in debug mode. You can change just about anything, except for adding class level variables, methods, or new classes, and still continue running without having to recompile your project.
I use only the "Syntax Check" to see if I forgot some typo on the code... And these are much reduced, since I the "Code Proofreader" of GExperts plugin.
Well, compiler doesn't have to be that fast to take advantage of it. Some IDEs support incremental compilation on every file save, or either on-the-fly. This works great.
You can split application in several projects ( by layer and/or module and/or etc... ) and you will compile only project, where do you actualy work.
The last part of your post scares me. I am not familiar with other IDEs but MSDev allows you to find all references to a method - so you don't have to compile just to find all the method calls you broke.
Use whatever works, but it is good you are open to new ways of doing things.

Categories