Multiplying Int and Char - c#

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.

Related

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 ?

Locating bug in complex application

This is going to be a very general question. I'm hoping to find some tool or trick within Visual Studio 2010 that I don't know about.
Long story short, I'm taking over a very big accounting application for a company; there is no documentation and comments in the code are sparse. Also I have no access to the previous developers. There is a bug they need fixed right away. Basically a negative number is appearing in the database and the number should be positive. Nobody has any idea where in the app the calculation is happening, or where the data is actually being written to the database. Does anything jump out at anyone as far as figuring out what class/function is doing this? I could watch the database while stepping through every line of code but that could take days.
Not the answer you are going to like to hear but if its repeatable, you could approach this like a binary search.
Step over each procedure until the value changes.
Rerun and step in the procedure that changed the value.
Goto 1.
Pro
It won't take you days
you don't have to think about it while doing it
I would be surprised if you haven't found it after repeating this a few ten times.
Cons
not fun to do at all.

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.

Verifying license information without a boolean check? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm currently using a simple XML file that contains license information along with the data's signature and public key. So far, this method is working great. However, I'm seeing one rather large security flaw...
When my ASP.NET MVC application starts, it verifies the license and sets the "ValidLicense" bool property accordingly. During each request, this property is checked and an error message is displayed if the license is invalid.
As you can guess, there's absolutely nothing to stop a competent user from simply modifying my assembly to set "ValidLicense" to true regardless of the license's validity. I know this can be done to pretty much any application, but it seems incredibly easy to do with .NET assemblies.
What are some ways that I can stop this from happening, or at least make it a little more difficult to crack the license verification procedure?
I'd rather stay away from assembly encryption and obfuscation systems, if possible. Go ahead and suggest them if you feel that they are good enough to warrant the cost and extra headache, however.
The only way to win is not to play.
The people who are going to steal your stuff (regardless of what protections you put in place), are not the people who are going to pay for it if it's too hard for them to break.
Instead of a simple boolean variable, you could perform a complex calculation every time you need to verify the license and base your logic on the result from that calculation. You do get a perf hit, though. And cracking your assembly wouldn't be that much harder anyway.
You could also employ some more advanced techniques, like dynamic mutation of the code and using the a corresponding mutable function to control the flow of your logic.
However, you should ask yourself does your assembly really contain such precious intelectual property, as to warrant the time and efforts to implement anything like this? It might be more viable and cheaper to go the legal route and battle the potential piracy if and when it occurs.
You can make it a bit more complicated but in the end it will come down to one (or several) booleans: Either you run the code or you don't. Non-obfuscated.NET code is pretty much the same as open source and it is ridiculously easy to crack open.
Even if obfuscation is not a full solution, I think it would make sense to obfuscate, just to prevent fringe amateurs from producing cracked versions.
Of course it won't stop a real cracker who is willing to spend the time, but just by putting the bar a little higher, you can weed out a lot of crackers wannabes.
Obfuscation can be pretty simple to implement for free. If you have a commercial version of Visual Studio, you can use DotFuscator (not with the "Express" editions). I never tried, but I guess it should be simple enough.
Otherwise, you can use Assemblur. (http://www.metapropeller.com/). The free version is a command line application (there is a GUI to create the setting file, but you need to run the settings from the command line).
All in all, it barely takes a couple minutes to obfuscate a simple exe file and it's free
If you want to make your license check a little more challenging, you can make different checks inside various methods, and you can also make sure that the license checking code does not actually output any string directly. (for instance, you do a license check in method A, but you output the error warning from method B, so that when a cracker looks for the license error message, he doesn't land right on the bit of code to be changed).
All it does is raise the bar for wannabe crackers and make things more complex for a real cracker.
Case 1: Non obfuscated .NET application with 1 license check method which output a "not licensed" error message.
Can be cracked in about 5 minutes by anyone who can run reflector.
Case 2: Obfuscated .NET application with a couple different license checks and no obvious string output.
Could take hours for a cracker and prove too hard for a wannabe.
You can get from case 1 to case 2 with about 1 hour of work, without spending a dime. Going beyond that is probably a waste of time (everything can be cracked) but at least, you can weed out the folks who open your application in Reflector just to see if it's going to be easy. If the guy opens the application in reflector and sees something like:
public bool ValidateLicense(string sLicense)
{
string sInvalidLicense = "Your license is not valid";
...
}
Guess what happens next?
//EDIT: In a comment, LC asked:
How do you not have it output any string message but still notify the user? Even if you do a license check and output in two different methods, you'll still have a the binary decision "if(!ValidateLicense(LicenseCode)) {NotifyUserOfInvalidLicense(); throw new LicenseException();}" or something, no?
Put yourself in the shoes of a cracker: You are looking for the License validation code. You are not going to study the whole code just to find it. Instead, you run the application unlicensed: The error message shows up.
You take that error message, you open the assembly in Refactor and you search for a part of that error message.
If that string is located inside "ValidateLicence()", you immediately find the ValidateLicence() function. From there, you only need to locate the return value and change that 1 byte. Done.
If the string is found instead inside "WhatEver()", you still needs to find what methods call "WhatEver()". It might not even be in the same assembly (in which case Refactor will not find it for you). This makes the job harder for your wannabe cracker. He will have to look at that method to see how it validates the code (which it doesn't). He might even be sloppy and change the return value of the wrong method, in which case he introduces a bug (if the method is obfuscated, figuring out what it does is not that simple).
Better yet, don't use a string at all: you can store the error message as a sequence of hex codes, and convert it to string dynamically when you need to display the message. No error string means that the cracker will have to rely on something else to locate your license validation code. And reading through obfuscated code is not fun.
You could also have a fake validation method containing the error message and suppress the warning to make it look like the crack worked.
So, a couple of simple, stupid tricks like these + simple obfuscation are very easy to implement and they can turn a 5 minutes "In and Out" cracking session into weeks of work for the cracker, because not only does he need to find and crack your validation code, but he also has to test to make sure that everything is working and that he didn't just fix a decoy or unwillingly created nasty bugs. Now, he just can't be sure without testing.
In the end, cracking an assembly is just a matter of changing a few bytes, and you can't prevent anyone from changing bytes in your assembly's files. Everything can be cracked.
However you can make it a hell of a lot harder to find which bytes have to be changed, and at the very least, you can avoid having a string that says "the byte you are looking for is right here".
An approach I met when trying to hack a little .NET product was to use an unmanaged .DLL for the licence checking. And not only that, the .DLL also contained a lot of code that was actually used in the software. So, to crack product I actually had to crack the unmanaged .DLL (or make a perfect wrapper). Needless to say, this stopped a wannabe cracker like me. :)

Categories