On a code of serial port communication - c#

I have come across the code on another question. It is an answer to the question with C# tag, but I couldn't understand some parts:
using System.Port.IO; ( ? System.IO.Ports)
System.Windows.Timers.Timer serialTimer; (There is no system.windows.timers ?)
serialPort1.DataReceived+=Tab Enter (What's the function of tab and enter here?)
serialPort1.Interval =100; ?
Would you please help me in understanding them?

The link I gave is an answer, not a topic. I am trying to understand what kind of code it is on the link, not to learn how to communicate with a port.
This code was typed by someone without compiling it, and it's full of syntactical and conceptual errors. I'll try to address the lines in your question:
using System.Port.IO; ( ? System.IO.Ports)
Yes, he probably meant to type System.IO.Ports.
System.Windows.Timers.Timer serialTimer; (There is no system.windows.timers ?)
No, there isn't. He either meant a System.Timers.Timer or a System.Windows.Forms.Timer.
serialPort1.DataReceived+=Tab Enter
(What's the function of tab and enter here?)
Those commands (though I usually TabTab) write an empty event handler for you, like:
void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
}
But that is makes little sense here, as his code already shows an event handler for that, so that line should actually read:
serialPort1.DataReceived += serialPort1_DataReceived;
serialPort1.Interval =100; ?
Typo again, he probably meant to set the timer's interval through serialTimer.Interval.
So I think the lesson here is: always assume the worst when you're copypasting someone's code off the web.

Related

C# EventHandler documentation code example

I am reading the .NET documentation on EventHandlers and do not understand this snippet of code from https://learn.microsoft.com/en-us/dotnet/standard/events/ :
class Counter
{
public event EventHandler ThresholdReached;
protected virtual void OnThresholdReached(EventArgs e)
{
EventHandler handler = ThresholdReached;
handler?.Invoke(this, e);
}
// provide remaining implementation for the class
}
What is the purpose of local variable handler? Why not invoke TresholdReached directly TresholdReached?.Invoke(this, e); ?
Similar examples are here:
https://learn.microsoft.com/en-us/dotnet/api/system.eventhandler-1?view=net-5.0
What is the purpose of local variable handler?
Probably none. There is certainly no reason in terms of code-correctness. It appears to be a holdover from the old, pre-null-conditional operator version of the documentation, in which copying the event field ThresholdReached into a local variable was required in order to safely resolve race conditions between raising the event and any other code that might be unsubscribing from it. As you point out, using the null-conditional operator, the code can simply be one line, invoking via the event field itself.
I only say "probably" because I guess there's a very small chance that the author of the documentation was hoping to achieve some other pedagogical goal with the more-explicit form of the code. But I can't imagine what that might be, and it's obviously interfering with general comprehension of the code (i.e. distracting from the important parts).
I submitted a comment on the page to let Microsoft know of the problem. I think there's also probably a place in the Microsoft Git repo where you can submit an issue for the documentation, if you like.
My experience has been that either way the problem is conveyed to Microsoft, they typically fix the problem in relatively short order. I would guess that in the next couple of weeks, that passage will be fixed, and this question will no longer be relevant. :)
Finally, I found the answer almost immediately after posting this question (that bugged me for days).
Reading #lc.'s answer with comments to this questions:
Events - naming convention and style
led me to this page:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/events-and-races
So the answer is: local handler variable effectively copies the immutable delegate and renders it thread safe.
They could have mention it on that doc page.
EDIT:
See #Peter Duniho answer and comments.

Using Process.Start to capture console output

unfortunately i'm new in C# and this should be a stupid question but i need it, hope someone should help..
Based on this article: http://csharptest.net/532/using-processstart-to-capture-console-output/
i need to use the first code example but applying the second one like described by the Author. He talk about substitute the second code in the first at one point, but i really don't understand how many code to delete and/or substitute..
If it's possible i like to have a working example of that...
Thanks in advance for the help :-)
Given the description:
you would remove the event subscription and the call to process.BeginOutputReadLine()
he is talking about those two lines:
process.OutputDataReceived += (o, e) => { if (e.Data == null) mreOut.Set(); else output(e.Data); };
process.BeginOutputReadLine();
Note that the code you substitute to this should be just:
new ReadOutput(process.StandardInput, mreOut);
ReadOutput class would be outside the Run method (since in C#, methods cannot contain classes).

System.Drawing.ImageAnimator.Animate and System.Drawing.ImageAnimator.StopAnimate explanation

i found this syntax from another article(C# How to stop animated gif from continually looping) but it seems i cant understand it. what is the meaning or purpose of s and e from
System.Drawing.ImageAnimator.Animate(txImage.Image, (s,e) => OnFrameChanged(s,e));
// start
System.Drawing.ImageAnimator.Animate(txImage.Image, (s,e) => OnFrameChanged(s,e));
// stop
System.Drawing.ImageAnimator.StopAnimate(txImage.Image, (s, e) => OnFrameChanged(s, e));
private void OnFrameChanged(object sender, EventArgs e)
{
// frame change
}
or simply can anyone explain this briefly. sorry for being stupid but im really new to programming but i really want to learn thank you
There are three basic ways in which you can write an event handler. Unfortunately the author of that code got it pretty wrong by inappropriately mixing them up. What he should have used is the original C# version 1 way:
ImageAnimator.Animate(txImage.Image, OnFrameChanged);
Which is quite straight-forward and easy to understand. Certainly the syntax you should strongly prefer in this case, it makes it very easy to call the StopAnimate() method. To answer your question, I need to show the other two ways, the ones you should not use. In C# version 2, an anonymous delegate can be used to write the code for the event handler in-place:
ImageAnimator.Animate(txImage.Image, delegate {
// Put the OnFrameChanged code here...
});
In C# version 3, lambda expressions became available to write an event handler in-place:
ImageAnimator.Animate(txImage.Image, (s, e) => {
// Put the OnFrameChanged code here...
});
Which is what you asked about. The (s, e) part of the lambda expression represent the two arguments that are passed to the event handler, s is the sender, e is the EventArgs object. Do note that you don't actually use those two arguments in your OnFrameChange code so the lambda syntax is superfluous, the anonymous delegate works just as well. Albeit that many C# programmers have stopped using them and prefer to use the lambda expression syntax everywhere. Which is fair. Even though you don't use the arguments, you must still write them to convince the compiler that your lambda is a proper substitute for the delegate. Much like you still had to write OnFrameChanged with two arguments to keep the compiler happy.
Understanding lambda expression syntax can be a bit of a speed-bump, any decent introductory book about the C# language will do a better job than I can do to explain it.
Last but not least, you'll find some hackorama code in this answer to show you how to pause an animation in a PictureBox without having to use the ImageAnimator class at all. Albeit with some odds that this just adds more questions :)
Animate and StopAnimate expect "an eventHandler object that specifies the method that is called when the animation frame changes."
You can read this as
System.Drawing.ImageAnimator.Animate(txImage.Image, new EventHandler(this.OnFrameChanged))

How to create IDLE -like functionality to WinForms application

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.

Are these interview questions too challenging for beginners? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
So I just interviewed two people today, and gave them "tests" to see what their skills were like. Both are entry level applicants, one of which is actually still in college. Neither applicant saw anything wrong with the following code.
I do, obviously or I wouldn't have picked those examples. Do you think these questions are too harsh for newbie programmers?
I guess I should also note neither of them had much experience with C#... but I don't think the issues with these are language dependent.
//For the following functions, evaluate the code for quality and discuss. E.g.
//E.g. could it be done more efficiently? could it cause bugs?
public void Question1()
{
int active = 0;
CheckBox chkactive = (CheckBox)item.FindControl("chkactive");
if (chkactive.Checked == true)
{
active = 1;
}
dmxdevice.Active = Convert.ToBoolean(active);
}
public void Question2(bool IsPostBack)
{
if (!IsPostBack)
{
BindlistviewNotification();
}
if (lsvnotificationList.Items.Count == 0)
{
BindlistviewNotification();
}
}
//Question 3
protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
ListViewDataItem item = lsvnotificationList.Items[e.ItemIndex];
string Email = ((TextBox)item.FindControl("txtEmailAddress")).Text;
int id = Convert.ToInt32(((HiddenField)item.FindControl("hfID")).Value);
ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext();
var compare = from N in db.NotificationLists
where N.ID == id
select N;
if (compare.Count() > 0)
{
lblmessage.Text = "Record Already Exists";
}
else
{
ESLinq.NotificationList Notice = db.NotificationLists.Where(N => N.ID == id).Single();
Notice.EmailAddress = Email;
db.SubmitChanges();
}
lsvnotificationList.EditIndex = -1;
BindlistviewNotification();
}
I don't typically throw code at someone interviewing for a position and say "what's wrong?", mainly because I'm not convinced it really finds me the best candidate. Interviews are sometimes stressful and a bit overwhelming and coders aren't always on their A-game.
Regarding the questions, honestly I think that if I didn't know C#, I'd have a hard time with question 3. Question #2 is a bit funky too. Yes, I get what you're going for there but what if the idea was that BindlistviewNotification() was supposed to be called twice? It isn't clear and one could argue there isn't enough info. Question 1 is easy enough to clean up, but I'm not convinced even it proves anything for an entry-level developer without a background in C#.
I think I'd rather have something talk me through how they'd attack a problem (in pseudo-code or whatever language they are comfortable with) and assess them from that. Just a personal opinion, though.
I am a junior programmer, so I can give it a try:
"active" is unnecessary:
CheckBox chkactive = (CheckBox)item.FindControl("chkactive");
dmxdevice.Active = chkactive.Checked
You should use safe casting to cast to a CheckBox object. Of course, you should be able to find the checkbox through its variable name anyway.:
CheckBox chkactive = item.FindControl("chkactive") as CheckBox;
The second function could be more concise:
public void Question2(bool IsPostBack)
{
if (!IsPostBack || lsvnotificationList.Items.Count == 0)
{
BindlistviewNotification();
}
}
Only have time for those two, work is calling!
EDIT: I just realized that I didn't answer your question. I don't think this is complicated at all. I am no expert by any means and I can easily see the inefficiencies here. I do however think that this is the wrong approach in general. These language specific tests are not very useful in my opinion. Try to get a feeling for how they would attack and solve a problem. Anyone who can get past that test will be able to easily pick up a language and learn from their mistakes.
I think you are testing the wrong thing. You are obviously looking for a C# programmer, rather than a talented programmer (not that you cannot be a talented C# programmer). The guys might be great C++ programmers, for example. C# can be learned, smarts cannot. I prefer to ask for code during an interview, rather than presenting code in a specific language (example: implement an ArrayList and a LinkedList in any language).
When I was looking for 3 programmers earlier this year, to work mostly in C#, Java, PL/SQL, Javascript and Delphi, I looked for C/C++ programmers, and have not been disappointed. Any one can learn Java, not everyone has a sense of good arachitecture, data strutures and a grasp of new complex problems. C++ is hard, so it acts as a good filter. If I had asked find errors in this Java code, I would have lost them.
BTW, I am a team lead, been programming for 20 years with dozens of large projects developed on time and on budget, and I had no clue with what was wrong with question 2 or 3, having only a passing familiarity with C#, and certainly not with Linq, Not that I could not learn it.... I figured it out after a couple minutes, but would not expect a recent graduate to grasp it, all the LINQ code in question 3 is a distraction that hides the real problems.
Do you think these questions are too harsh for newbie programmers?
Yes, IMO they are too harsh.
Neither applicant saw anything wrong with the following code.
While there are plenty of 'possible problems', like not checking for null pointers, casting, etc, there don't appear to be any 'actual problems.' (eg: given sane input, the program looks like it will actually run).
I'd guess that a newbie programmer will get hung up on that.
As linq is pretty new, and still not in wide use, it's going to go way over the head of your newbies.
What is an ESLinqDataContext? If people have no idea what your object is or how it behaves, how are they supposed to know if it is being used correctly or not?
evaluate the code for quality and discuss
You only really learn to pick up stuff like invalid cast exceptions (let alone being able to judge and comment on 'code quality') from reasonable experience working with code similar to what's in front of you.
Perhaps I'm misunderstanding, but to me, an "entry level" position pretty much by definition has no expectation of prior experience, so it doesn't seem fair to grade them on criteria which require experience.
I am not a C# programmer so I don't know what BindlistviewNotification does, but changing
public void Question2(bool IsPostBack)
{
if (!IsPostBack)
{
foo();
}
if (lsvnotificationList.Items.Count == 0)
{
foo();
}
}
to
public void Question2(bool IsPostBack)
{
if (!IsPostBack || lsvnotificationList.Items.Count == 0)
{
foo();
}
}
changes the function! If IsPostBack is false, foo is executed. If lsvnotificationList.Items.Count == 0 then foo is executed again. The revised code will only execute foo once.
You could argue that BindlistviewNotification can be executed several times without side effects or that IsPostBack can never be false and lsvnotificationList.Items.Count equal 0 at the same time, but those are language dependent and implementation dependent issues that cannot be resolved with the given code snippet.
Also, if this is a bug that's "supposed" to be caught in the interview, this isn't language agnostic at all. There's nothing that would tell me that this is supposed to be a bug.
As a newbie, I would expect employers to care more about what my thought processes were rather than whether the answer was "correct" or not. I could come up with some answers to these questions, but they probably wouldn't be right. :)
So with that said, I think you could get by with these questions, but you should definitely be a bit more liberal with what the "correct" answer is.
As long as those conditions were made clear, I think that it's a bad thing to get a blank sheet with no thoughts. This means that they either genuinely think the code is perfect (which we know is almost never true) or are too sheepish to share their thoughts (which is also a bad thing).
I don't think 1 and 2 are too difficult, #3 requires a decent understanding on how databinding and LINQ works in .NET, so it may be somewhat hard for an entry level person. I think these are fairly good questions for junior level developers who have some .NET experience.
For what its worth, my notes:
Question 1:
Using an integer as boolean
No null check on findControl
Excessive verbosity
My revision:
public void Question1()
{
CheckBox chkactive = item.FindControl("chkactive") as CheckBox;
if (chkActive != null)
dmxdevice.Active = chkActive.Checked;
else
dmxdevice.Active = false;
}
Question 2:
Excessive verbosity
Databinding will happen twice if its not a postback, and there are no items to bind.
My revision:
public void Question2(bool IsPostBack)
{
if (!IsPostBack || lsnotificationList.Items.Count == 0)
{
BindlistviewNotification();
}
}
Question 3:
Replace indexed loopup with getting e.Item.DataItem;
Add nullchecks to findControl calls.
Switch to TryParse and add a default id value.
Added better error handling
Document some major architectural issues, why are you querying the database from the frontend? Those LINQ queries could be optimized too.
Why not check for duplicates within the list items collection, and why not batch all updates with a single submit later?
So you asked this to someone with no c#, .net, asp.net or linq knowledge? I wouldn't expected anything on the paper?
My only advice is to make sure your test questions actually compile.
I think the value in FizzBuzz type questions is watching HOW somebody solves your problems.
Watching them load the solution in to the IDE, compile it, step through the code with a step through debugger, write tests for the apparent intended behavior and then refactoring the code such that it is more correct/maintainable is more valuable than knowing that they can read code and comprehend it.
Not knowing C#, it took me a bit longer, but I'm assuming #1 could be expressed as
dmxdevice.Active = ((CheckBox)item.FindControl("chkactive")).Checked == true
And in #2 the two conditions could be joined as an A OR B statement?
If that's what you're looking for, then no, those aren't too hard. I think #1 is something you might learn only after programming for a little while, but #2 seems easier.
Are you looking for them to catch null pointer exceptions also?
I think the first two are fine. The third may be a wee bit complicated for a graduate level interview, but maybe not, it depends whether they've done any .net coding before.
It has LINQ statements in there, and that's pretty new. Especially since many unis/colleges are a bit behind in teaching the latest technology. So I would say run with 1 & 2 and either simplify 3 or heavily comment it as others have mentioned
The first two appear to be more a test to see if a person can follow logically and realize that there is extra code. I'm not convinced that an entry level developer would understand that 'less is more' yet. However, if you explained the answer to Question 1 and they did not then extraplolate that answer to #2, I would be worried.
Question 3 appears to be a big ball of mud type of implementation. This is almost expected to be the style of a junior developer straight from college. I remember most of my profs/TAs in college never read my code -- they only ran the executable and then put in test sets. I would not expect a new developer to understand what was wrong with it...
What did you expect to get out of this interview? Do your employees have to debug code without a debugger or something? Are you hiring somebody who will be doing only maintenance programming?
In my opinion these questions do little to enlighten you as to the abilities of the candidates.
This is a fine question if you're looking for a maintenance programmer, or tester.
However, this isn't a good test to detect a good programmer. A good programmer will pass this test, certainly, but many programmers that are not good will also pass it.
If you want a good programmer, you need to define a test that only a good programmer would pass. A good programmer has excellent problem solving skills, and knows how to ask questions to get to the kernel of a problem before they start working - saving both them and you time.
A good programmer can program in many different languages with only a little learning curve, so your 'code' test can consist of pseudo code. Tell them you want them to solve a problem and have them write the solution in pseudo code - which means they don't have access to all those nifty libraries. A good programmer knows how the libraries function and can re-create them if needed.
So... yeah, you're essentially asking textbook knowledge questions - items that show memorization and language knowledge, but not skills necessary to solve a problem.
-Adam
It's funny to see everyone jumping to change or fix the code. The questions targeted "efficiently? could it cause bugs?" Answers: Given enough time and money, sure each one could probably be made more efficient. Bugs, please try to avoid casting and writing difficult to read code (code should be self-documenting). If it doesn't have bugs it might after the next junior programmer tries to change it... Also, avoid writing code that appears to rely on state contained outside the scope of the method/function, those nasty global variables. If I got some insightful comments like this it might be appropriate to use this as a tool to create some good conversation. But, I think some better ice-breakers exist to determine if a persons critical thinking skills are appropriate and if they will fit in with the rest of the team. I don't think playing stump the programmer is very effective.
Question #1
boolean active = true;
Question #2
if ((!IsPostBack) || (lsvnotificationList.Items.Count == 0))
Question #3:
Do a total re-write and add comments. After a 30 second read I still can't tell what the code is trying todo.
I'm not a C# programmer. On Q1, there seem to be undeclared objects dmxdevice and item, which confuses me. However, there does seem to be a lot of obfuscation in the rest of the code. On Q2, lsvnotificationList is not declared, and it not clear to me why one test is abbreviated with ! and the other with == 0 -- but the tests could be combined with ||, it seems. In Q3, lsvnotificationList is not self-evidently declared, again. For the rest, it seems to be doing a database lookup using LINQ. I'd at least expect that to be factored into a function that validates the hidden field ID more transparently. But if you have other ideas, well...I'm still not a C# programmer.
Disclaimer: I come from a 4 year degree and a year's worth of professional Java experience.
The first two questions are quite straightforward and if a candidate doesn't see a better approach I would suspect it's because they haven't been paying attention in class ;-)
Most of the answers to the second question presented so far alter the functions behaviour. The function could very well be evaluated twice in the original code, although I can't say if that is the intent of the function. Side effects are important.
I would probably one-line the first function, myself.
The questions are fairly language agnostic, but they're not library agnostic, which I would argue is equally as important. If you're specifically looking for .NET knowledge, well and good, but without Google I couldn't tell you what an ESLinq.DataContext is, and my answer to the third question suffers accordingly. As it is, it's nearly incomprehensible to me.
I think you also have to be careful how you present the questions. There's nothing incorrect about the first two methods, per se. They're just a little more verbose than they should be.
I would just present them with the sheet and say, "What do you think of this code?"
Make it open ended, that way if they want to bring up error-handling/logging/commenting or other things, it doesn't limit the discussion.
A cursory glance indicates that most of the rest of the code suffers from poor structure and unnecessary conditionals etc. There's nothing inherently "wrong" with that, especially if the program runs as expected. Maybe you should change the question?
On the other hand, the casting doesn't look like it's being done correctly at all eg. (cast)object.Method() vs (cast)(object.Method()) vs ((cast)object).Method(). In the first case, it's not a language agnostic problem though - it depends on rules of precedence.
I don't think it was that hard, but it all depends on what you wanted to test. IMO, the smart candidate should have asked a lot of questions about the function of the program and the structure of the classes before attempting to answer. eg. How are they supposed to know if "item" is a global/member var if they don't ask? How do they know it's type? Do they even know if it supports a FindControl method? What about FindControl's return type?
I'm not sure how many colleges teach Linq yet though, so maybe you should remove that part.
No one's answering #3 with code. That should indicate how people feel about it. Usually stackoverflowers meet these head-first.
Here's my stab at it. I had to look up the EventArgs on msdn to know the properties. I know LINQ because I've studied it closely for the past 8 months. I don't have much UI experience, so I can't tell if the call to bind in the event handler is bad (or other such things that would be obvious to a UI coder).
protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
string Email = e.NewValues["EmailAddress"].ToString();
int id = Convert.ToInt32(e.NewValues["ID"]);
using (ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext(connectionString))
{
List<NotificationList> compare = db.NotificationLists.Where(n => n.ID = id).ToList();
if (!compare.Any())
{
lblmessage.Text = "Record Does Not Exist";
}
else
{
NotificationList Notice = compare.First();
Notice.EmailAddress = Email;
db.SubmitChanges();
}
}
lsvnotificationList.EditIndex = -1;
BindlistviewNotification();
}
While people here obviously have no trouble hitting this code in their spare time, as someone who went through the whole job search/interviewing process fresh out of collage about a year ago I think you have to remember how stressful questions like these can be. I understand you were just looking for thought process, but I think you would get more out of people if you brought questions like this up casually and conversationally after you calm the interviewee down. This may sound like a cop out, but questions about code that will technically work, but needs some pruning, can be much more difficult then correcting code that doesn't compile, because people will assume that the examples are suppose to not compile, and will drive themselves up a wall trying to figure out the trick to your questions. Some people never get stressed by interview questions, but alot do, even some talented programmers that you probably don't want to rule out, unless you are preparing them for a situation where they have to program with a loaded gun to their head.
The code itself in question 3 seems very C# specific. I only know that as LINQ because someone pointed it out in the answers here, but coming in as a Java developer, I would not recognize that at all. I mean do you really expect colleges to teach a feature that was only recently introduced in .net 3.5?
I'd also liked to point out how many people here were tripped up by question 2, by streamlining the code, they accidentally changed the behavior of the code. That should tell you alot about the difficulty of your questions.
Ok, so after staying up well past my bedtime to read all the answers and comment on most of them...
General concensus seems to be that the questions aren't too bad but, especially for Q3, could be better served by using pseudo-code or some other technique to hide some of the language specific stuff.
I guess for now I'll just not weigh these questions in too heavily.
(Of course, their lack of SQL knowledge is still disturbing... if only because they both had SQL on their resume. :( )
I'll have to say that my answer to these problems is that without comments (or documentation) explaining what the code is MEANT to do, there is little reason to even look at the code. The code does EXACTLY what it does. If you change it to do something else, even change it to prevent throwing an exception, you may make it do something unintended and break the larger program.
The problem with all three questions is that there is no intent. If you modify the code, you are assuming that you know the intent of the original coder. And that assumption will often be wrong.
And to answer the question: Yes, this is too difficult for most junior programmers, because documenting code is never taught.
Okey I'm not going to answer the C# questions from what I see here you have enough candidates that would do fine in a job interview with you.
I do think that the tests won't give you a good view of a persons programming skills. Have a look at Joel's interviewing Guide:
http://www.joelonsoftware.com/articles/fog0000000073.html
He talks about two things when it comes to possible candidates: are they smart AND do they get the job done (now that's a powerful combination).Let your candidates talk a bit about projects they did or what they're toying around with at home. Find out if they are passionate about programming. Some experience is nice of course, just don't ask them to do tricks.
Q1 also has a potential InvalidCastException on the item.FindControl() line.
I don't think Q1 or Q2 are outside the realms of being too hard, even for non C# users. Any level code should be able to see that you should be using a boolean for active, and only using one if statement.
Q3 though atleast needs comments as someone else noted. That's not basic code, especially if you're targeting non-C# users with it too.
In question 2 for better modularity I would suggest passing the count of lsvnotificationList.Items as a parameter:
public void Question2(bool IsPostBack, int listItemsCount)
{
if (!IsPostBack || listItemsCount == 0)
BindlistviewNotification();
}

Categories

Resources