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".
Related
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 ?
So, I was going over some old code I wrote about 5 years ago for a project. I decided to copy/paste the old code and update the syntax/formatting and whatnot, since it was coded pretty poorly. Then I got to this line:
sp += sp3.Substring(sp3.Length - 3, 2) + (Convert.ToInt32(Convert.ToChar(sp3.Substring(sp3.Length - 3, 1))) * (Convert.ToChar(sp3.Substring(sp3.Length - 5, 1)))).ToString().Substring(1);
I'm guessing it was a typo, but because I don't really understand what's going on here, I can't seem to get the resulting code to function the same way as the original. Oddly enough, even copy/pasting the old code seems to produce different results. That may be unrelated to this code for all I know, but this was the only thing I could find that struck me as odd.
If you don't see what I'm talking about, it seems as though I omitted the conversion back to an integer on the last bit. Honestly I wasn't even aware you could multiply an integer and char value together, since I haven't started my .NET classes yet. I tried googling it, to no avail; so if anyone could provide some insight, that would be great. Anyway, all of the "sp" variables are strings with a length > 5.
Given that the code was written 5 years ago, you may want to revisit what the purpose of the code is and see if you can write it better. A developer can learn a lot in 5 years.
If you want to better understand what is actually in there, you should break it down into multiple statements and either use the debugger or Console.WriteLine (or Debug.WriteLine) to print out the intermediate values. This way you can see exactly what each step of the line of code does and how it affects the result.
Another helpful way to get more information is using the Visual Studio Debugger: you can highlight part of the line, right click, then click "Add Watch" to have the debugger evaluate just that sub-expression. This will also help you try out different inputs to see how it behaves.
Bonus points for writing unit tests for the different inputs and expected outputs to verify the behavior you are expecting.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I currently support an application at work that was originally written by a team of four but has now reduced to just me. We recently got a contractor in to look at some performance issues while I'm occupied with other things.
While the contractor has appeared to do a good job with the performance, they have also gone through large amounts of the code replacing the pre-existing style with their personal preference.
Unfortunately we don't have a coding standards doc, just a general rule to adhere to c# general rules.
As an example of what they've done, it includes:
removing nearly all the uses of the 'var' keyword
Anywhere with an if statement and a single line, they've added curly braces
Removing most of the lambdas and replacing it with more verbose code
Changing method signatures so every parameter is on a separate line rather than one line
We also operate a TDD policy but the test coverage, especially on the performance specific parts, is very low leaving very little documentation on what they've changed and making it even harder as their checkin comments aren't particularly helpful and the actual functional changes are lost amongst the swathe of 'tweaks'.
How do I talk to the contractor about this? Obviously there's not much impetus on them to change it given they have no responsibility to support the project and they don't seem particularly receptive to change.
Or should I just put up with it for the short duration of the contract then change everything back to the code formatting we used before?
Made community-wiki 'cos there's probably not one right answer here.
Anywhere with an if statement and a single line, they've added curly braces
This one and the only one may be beneficial.
removing nearly all the uses of the 'var' keyword
Removing most of the lambdas and replacing it with more verbose code
Changing method signatures so every parameter is on a separate line rather than one line
These ones make little sense to change.
Tell him he's not authorized to restyle code. You won't be paying for the time wasted for these activities and they'll have to use their own time to put things back. That should provide a refreshment.
These things should be discussed in advance. You should state clearly what activities are allowed and what not. Not a long ago there was another similar question here about a contractor who would put his initials all over the code including database entities. It was some perverse kind of self-promotion for which there is no place in someone else's code.
P.S. There may also be a possibility that by doing all these things your contractor is artificially creating extra workload to bill you more hours.
I'm a contractor (sometimes) and if I did this I would expect to be shown the door with great speed and no payment. Seriously, this person is hired by you and should be doing exactly what he is told to do, no more and no less. And don't worry about being "nice" - contractors don't expect that from permies.
How do I talk to the contractor about this?
Politely: explain why you want to minimize changes to the source code.
ALternatively, have a code inspection of the changes before check-in: and don't allow check-in of changes that you don't understand/don't want/haven't been tested.
Implement FxCop - this should be your first line of defense. Also if you use source control (if you don't then implement one ASAP), make sure to use dev labelling (only build on file that have been labelled for the build), and don't give him rights to move labels on the files. This way you can scrutinize his changes, and refuse to dev label his code until it meets your standards. Whatever he codes won't make it into QA until you move the dev label to the revision in question, so he's pretty much at your mercy there. Note that some shops don't use a single label for their sandbox builds, they like to apply new labels even to the sandbox, so you may be inclined to do that as well.
The problem has happened now, and as the other said it's an unjustifiable waste of your money and it's outright impolite (as correct as the curly braces thing may be).
Certainly to help prevent future problems, and maybe helpful to resolve this, I'd advise you set up a stylecop implementation - at the very least they can't fail to be unaware of when they are breaking your rules.
I think we all know the temptation of seeing coded we think is "not the way I'd do it". But we resist it.
I would have a chat about it with your boss first to get their take on it. But the first thing that springs to mind is that unless you specifically asked the contractor to do the work, he was not doing what he was hired to do, regardless of any benefit he thinks he may have been adding. So there needs to be a discussion about that.
The next thing that sprung to mind is that regardless of how good they may be or well intentioned, people who make bulk changes without discussing it with the owners of the code are bad news. They will piss people off, or worse introduce bugs and unforeseen behavior that you will have to clean up. He needs to be set straight that doing this sort of thing without permission on other peoples code is not acceptable.
When I see things I don't like in others code which are serious enough to warrant attention, I check with the owners of the code first. Even if there are obvious bugs, it
s their code and their decision about cleaning it up, not mine.
As others have said, these changes are simply for coding style. If he is there to improve performance, he is wasting time with these changes. If he can't cite how these changes will improve performance, then his OCD is just running up the bill.
I would say, "I appreciate your changes to the coding style, but lets focus on non-style changes to areas of the code that are causing the slowdown."
If a contractor did wholesale reformatting of code without authorization, I'd give him one and only one change to put things back the way they were -- and on his own time.
In addition to the valid points others make, consider the version-control nightmare this causes. Instead of the clean progression of a few lines added here, a few lines changed here, you now have this "rift" in your source control database, so that any comparisons between versions before and after this contractor's "improvements" will be meaningless.
Have the contractor back out all of his changes. Today. And on his own time.
This is quite common my experience, that people can't resist making 'improvements' and suddenly you find you're billed for stuff you didn't want. Sometimes I'm sure it's done deliberately to get more paying work, but mostly I think it's a developer getting side-tracked and unable to deal with leaving 'wrong' code.
It might require a bit of a battle, but you basically have to keep reiterating "don't change anything you're not asked to work on". Depending on his personality, you might just have to ask once nicely, or get someone higher to force him.
First, as others have said. You are paying the bill. He is not an employee. His job is to do what you ask him to do, and only what you ask him to do, otherwise you can show him the door. Always remember this. You are driving the boat, not him. You can try to not pay him, but that will be hard to do if you have a legal contract and there is nothing in it about leaving code as-is. But, you can simply let him go at any time.
Second, if you can't get him to stop and revert, and you can't get rid of him, you can tell him that if he plans to do style changes, then he should do all style changes in one check-in with absolutely NO code changes. This allows you to move forward from a base set of code that can be diffed to see code changes.
Third, make him explain the justification for the changes he's made. Removing var has no performance benefit.
Fourth, and this may suck a great deal, but youc an always use ReSharper to put the code back to your accepted style after the fact. It's more work, and you still have borked diffs, but oh well. The lambdas are harder, and that's the one you should really get on his case about.
Fifth, to drive home your point, force him to back out every change he's made and re-implement only the code changes, and not the style changes. That should open his eyes as to the mess he's created when he can't figure it out himself.
Finally, you may just have the bite the bullet and PAY him to revet back. Yes, it sucks, but since you made the mistake of not policing him, not specifying up front what you wanted, and what he's not allowed to do... You will pay the ultimate price. You can either pay him to do it, pay someone else to do it, pay you to do it, or live with it (and pay the price of the borked diffs). Any way you cut it, it will cost you money.
Well, smells like a solution wide code reformatting to me, that could be automated/enforced by settings in a tool like Resharper. I would think it very impolite and would ask him to refrain from pressing the "Reformat all code according to my personal taste" button.
To avoid the situation happening in the first place, introduce code review, particularly for any new developers joining who may not know your standards.
I'm a big fan of using git, feature branches and a service that supports pull requests (github or bitbucket). TFS isn't really up to the job, but thankfully Visual Studio supports git now. Doing code review before merging to master ensures it doesn't get forgotton. If you're paranoid you don't even need to give contractors write access to your primary repository.
Alternate point of view:
Your make two statements: "While the contractor has appeared to do a good job with the performance" and "they have also gone through large amounts of the code replacing the pre-existing style with their personal preference."
This raises many questions such as: Whenever you can "drop in" a contractor for a short period of time and gain performance enhancements. This indicates that there must have been very major flaws in the application in the first place. Anytime you need to bring in a contractor to "fix performance" this is a sign of very poorly written code or a very complex problem that requires high end expertise.
Next: When you complain that they have changed the code style even though you did not have any stated code style are you just making a pointless argument about your mojo being better than someone else's mojo. Maybe you should ask the person why they made changes which appear syntactical such that you have a complete picture.
I'm looking at the long list of one sided answers on this post and wondering what happened to the other side. Folks take the emotion out of it and look at it objectively. It's often amazing how many people will look past a beautiful algorithm solution to a complex problem just to notice that the variable naming convention has been altered from camel case to pascal case. I generally put this type of reaction down to justification of self worth by finding immaterial flaws.
Key question I have to ask is: Does the newly formatted code make the application any less readable. If you had budget constraints why did you not make it explicit that you wanted very specific fixes and nothing else. If you wanted to maintain a specific coding style then why not have that explicitly stated?
I have absolutely no idea how to start diagnosing this, and just wondered if anyone had any suggestions. I'm generating an Excel spreadsheet by calling some Macros from a C# application, and during the generation process it somehow breaks. I've got a VBA class containing all of my logging/error-handling logic, which I instantiate using a singleton-esque accessor, shown here:
Private mcAppFramework As csys_ApplicationFramework
Public Function AppFramework() As csys_ApplicationFramework
If mcAppFramework Is Nothing Then
Set mcAppFramework = New csys_ApplicationFramework
Call mcAppFramework.bInitialise
End If
Set AppFramework = mcAppFramework
End Function
The above code works fine before I've generated the spreadsheet, but afterwards fails. The problem seems to be the following line;
Set mcAppFramework = New csys_ApplicationFramework
which I've never seen fail before. If I add a watch to the variable being assigned here, the type shows as csys_ApplicationFramework/wksFoo, where wksFoo is a random worksheet in the same workbook. What seems to be happening is that while the variable is of the right type, rather than filling that slot with a new instance of my framework class, it's making it point to an existing worksheet instead, the equivalent of
Set mcAppFramework = wksFoo
which is a compiler error, as one might expect. Even more bizarrely, if I put a breakpoint on the offending line, edit the line, and then resume execution, it works. For example, I delete the word 'New' move off the line, move back, re-type 'New' and resume execution. This somehow 'fixes' the workbook and it works happily ever after, with the type of the variable in my watch window showing as csys_ApplicationFramework/csys_ApplicationFramework as I'd expect.
This implies that manipulating the workbook through the PIA is somehow breaking it temporarily. All I'm doing in the PIA is opening the workbook, calling several macros using Excel.Application.Run(), and saving it again. I can post a few more details if anyone thinks that it's relevant.
I don't know how VBA creates objects behind the scenes or how to debug this. I also don't know how the way the code executes can change without the code itself changing.
As previously mentioned, VBA has frankly gone a bit squiffy on me... Any thoughts?
If you look in task manager, are there any instances of excel running in the background? Just curious if it is creating an Excel object and not disposing of it properly.
I would suggest that somehow the PIA's are not working correctly. I would recommend unregistering them, removing all instances of them from your PC, and then regenerating them.
Of course this is not the rational explanation I would like to give, but it seems like sometimes COM just doesn't want to behave. I would love to know what really happens when things break down like this, but the only thing I have ever seem work is lots of stabs in the dark, followed by an attempt to retrofit a rational explanation once the weird refusal to work randomly disappears again.
Sorry for the lack of a 'REAL' answer
So I'm working on some legacy code that's heavy on the manual database operations. I'm trying to maintain some semblance of quality here, so I'm going TDD as much as possible.
The code I'm working on needs to populate, let's say a List<Foo> from a DataReader that returns all the fields required for a functioning Foo. However, if I want to verify that the code in fact returns one list item per one database row, I'm writing test code that looks something like this:
Expect.Call(reader.Read()).Return(true);
Expect.Call(reader["foo_id"]).Return((long) 1);
// ....
Expect.Call(reader.Read()).Return(true);
Expect.Call(reader["foo_id"]).Return((long) 2);
// ....
Expect.Call(reader.Read()).Return(false);
Which is rather tedious and rather easily broken, too.
How should I be approaching this issue so that the result won't be a huge mess of brittle tests?
Btw I'm currently using Rhino.Mocks for this, but I can change it if the result is convincing enough. Just as long as the alternative isn't TypeMock, because their EULA was a bit too scary for my tastes last I checked.
Edit: I'm also currently limited to C# 2.
To make this less tedious, you will need to encapsulate/refactor the mapping between the DataReader and the Object you hold in the list. There is quite of few steps to encapsulate that logic out. If that is the road you want to take, I can post code for you. I am just not sure how practical it would be to post the code here on StackOverflow, but I can give it a shot to keep it concise and to the point. Otherwise, you are stuck with the tedious task of repeating each expectation on the index accessor for the reader. The encapsulation process will also get rid of the strings and make those strings more reusable through your tests.
Also, I am not sure at this point how much you want to make the existing code more testable. Since this is legacy code that wasn't built with testing in mind.
I thought about posting some code and then I remembered about JP Boodhoo's Nothin But .NET course. He has a sample project that he is sharing that was created during one of his classes. The project is hosted on Google Code and it is a nice resource. I am sure it has some nice tips for you to use and give you ideas on how to refactor the mapping. The whole project was built with TDD.
You can put the Foo instances in a list and compare the objects with what you read:
var arrFoos = new Foos[]{...}; // what you expect
var expectedFoos = new List<Foo>(arrFoos); // make a list from the hardcoded array of expected Foos
var readerResult = ReadEntireList(reader); // read everything from reader and put in List<Foo>
Expect.ContainSameFoos(expectedFoos, readerResult); // compare the two lists
Kokos,
Couple of things wrong there. First, doing it that way means I have to construct the Foos first, then feed their values to the mock reader which does nothing to reduce the amount of code I'm writing. Second, if the values pass through the reader, the Foos won't be the same Foos (reference equality). They might be equal, but even that's assuming too much of the Foo class that I don't dare touch at this point.
Just to clarify, you want to be able to test your call into SQL Server returned some data, or that if you had some data you could map it back into the model?
If you want to test your call into SQL returned some data checkout my answer found here
#Toran: What I'm testing is the programmatic mapping from data returned from the database to quote-unquote domain model. Hence I want to mock out the database connection. For the other kind of test, I'd go for all-out integration testing.
#Dale: I guess you nailed it pretty well there, and I was afraid that might be the case. If you've got pointers to any articles or suchlike where someone has done the dirty job and decomposed it into more easily digestible steps, I'd appreciate it. Code samples wouldn't hurt either. I do have a clue on how to approach that problem, but before I actually dare do that, I'm going to need to get other things done, and if testing that will require tedious mocking, then that's what I'll do.