.NET Applications: Open Source by Default

If you have been developing .NET applications for much time, I hope you have come to realize that your Windows applications are not very secure. What do I mean by that? Let’s take a very simple application as an example:

using System;
 
namespace InsecureApp
{
    class Program
    {
        static void Main(string[] args)
        {
            for (; ; )
            {
                Console.WriteLine("Enter your password:");
                if (Console.ReadLine() == "secret")
                {
                    Console.WriteLine("Logged in. My social security number is 123-45-6789.");
                    Console.WriteLine("Your session has expired. Logged out.");
                }
                else
                {
                    Console.WriteLine("Incorrect password.");
                } 
            }
        }
    }
}

I realize this example is trivial, but I am trying to illustrate a point. I’ll do it in two ways: first, using ildasm.exe and second by using Telerik JustDecompile. No, this isn’t a product endorsement. I just needed to find a free decompiler.

You can run IL DASM with the Visual Studio Command Prompt. Here’s the output from my test program:

IL DASM Example Image

Please don’t sign me up for too many credit cards!

Not that scary, right? Potential crackers can only see the login password and your social security number. In an actual application, an email address, password, or authentication token could be visible in plain text. Remember, I did this with a free tool. I didn’t even have to download anything! What if I did, you ask?

Decompiled Code

Oh, bother.

Not only is the code reasonably close to what it actually was (to the point where it is easy-to-understand), I could look at the code in VB.NET if I wanted to and there is syntax highlighting! This is another free tool that you can use without even understanding CIL. But, say you did. Back in the day (and I do mean “in the day”, perhaps four or five years ago), I became interested in what was going on behind-the-scenes in .NET and learned some CIL. I also learned that you can use /OUT=”location” with IL DASM to actually output CIL to a file. Oh, I forgot to mention – there is a corresponding IL ASM to put the program back together.

Let’s say I’m a lazy cracker, so I am going to just jump to being logged in and then never log out. I changed the CIL for Main to look like this:

  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       81 (0x51)
    .maxstack  2
    .locals init ([0] bool CS$4$0000)
 
	ldstr "Cracked by 1337 H4x0r or something"
	call void [mscorlib]System.Console::set_Title(string)
 
    IL_0026:  ldstr      "Logged in. My social security number is 123-45-6789."
    IL_002b:  call       void [mscorlib]System.Console::WriteLine(string)
 
	call string [mscorlib]System.Console::ReadLine()
	pop
	ret
  } // end of method Program::Main

I then reassembled my program and ran it. There was no need to log in, and the program conveniently waited for me to hit enter before closing!

Simple Program Cracked

It took a surprising number of tries to assemble this application properly.

So, what can you do? Can you strong name your assembly? Sure, but it won’t do much to anyone that knows his or her stuff. Can you obfuscate it? Sure, but it’s only a roadblock. I did some reading about protecting .NET Windows applications from piracy, and the consensus seems to be that much protection isn’t worth it. Would you rather spend your time keeping people that will not pay for your software from using it or adding features to make more people willing to pay for it?

The important thing to take away from this post is to realize that anyone can see and modify what you write. You should not handle tasks that should be secure (such as anything that requires password or key storage) on the client side. Server-sided code is much better suited to secure tasks (since you cannot download ASP.NET binaries from a server unless something is seriously wrong), so anything that has to remain a secret should remain remote. Remember, transmitted data can be intercepted, so I am not telling you to send your passwords from the server to the client. I am telling you to have the client ask the server to do its dirty work.

The bigger message I wish to convey, though, is that you should minimize the amount of data that needs to be protected.

 

Will it Rain this Weekend?

While browsing MIT+K12 open projects, I came across an entire course proposal about probability. Now, I have very little formal probability training outside of one unit in precalculus last year, but I was intrigued by the idea of writing a program to simulate 10,000 trials. Obviously, 10,000 trials isn’t enough to get a really good data set so I added a few zeros to my C# for loop and ran 1,000,000 trials.

So, in keeping with the MIT course proposal, I checked the forecast for the weekend and found out that this weekend, the chance of rain on Saturday is 10% and the chance of rain on Sunday is 30%. My first reaction was mild aggravation because I went camping last weekend in the rain and I simply could’ve waited a week. My second reaction was, “Alright. Let’s get started.”

Probability Tree Image

Mr. Whalen, I hope you’re proud of me.

The next step was to write a program to test my calculations. I came up with a program structure that I hope is “random” enough. I am going to use System.Random instead of RNGCryptoServiceProvider because it is way faster and I believe it fine for something this simple. When I originally wrote this program, I used lists, populated them with true or false values, randomized them, and picked from them over and over again. I am not sure what kind of awful state of mind I was in when I wrote that code (whatever it was, there wasn’t enough caffeine), but I’ve come up with a way more elegant solution – Random.NextDouble(). If the double is less than the probability of rain, it rained. Otherwise, it didn’t. We also need three counters – one for when it rains sometime during the weekend at least once, one for when it rains exactly once and one for when it rains twice.

There is one other case: when it doesn’t rain, but 1,000,000 – the number of times it rained at least once takes care of that. Some operators make determining which case we’re dealing with easy – XOR is true if exactly one of two cases is true, OR is true if at least one case is true, and AND is true if both cases are true.

With that taken care of, all that was left was to write the code in a console application:

static void Main(string[] args)
{
    double probRainSat = 0.1;
    double probRainSun = 0.3;
 
    int rainyWeekends = 0;
    int oneDayRainyWeekends = 0;
    int bothDayRainyWeekends = 0;
 
    Console.WriteLine("Simulating one million weekends...");
    Console.WriteLine();
 
    Random rand = new Random(Environment.TickCount);
 
    // one million trials
    for (int i = 0; i < 1000000; i++)
    {
        if (i % 100000 == 0)
        {
            Console.WriteLine("{0}...", i);
        }
 
        bool rainedSat = rand.NextDouble() < probRainSat;
        bool rainedSun = rand.NextDouble() < probRainSun;
        if (rainedSun || rainedSat)
        {
            rainyWeekends++;
        }
        if (rainedSat ^ rainedSun)
        {
            oneDayRainyWeekends++;
        }
        else if(rainedSat && rainedSun) // We can use else if because it can't rain on exactly one and both days.
        {
            bothDayRainyWeekends++;
        }
    }
 
    Console.WriteLine("Rain on only 1 day: {0}/1,000,000 ({1})", oneDayRainyWeekends, oneDayRainyWeekends / 1000000);
    Console.WriteLine("Rain during the weekend: {0}/1,000,000 ({1})", rainyWeekends, rainyWeekends / 1000000);
    Console.WriteLine("Rain on both days: {0}/1,000,000 ({1})", bothDayRainyWeekends, bothDayRainyWeekends / 1000000);
    Console.WriteLine("Rain on neither day: {0}/1,000,000 ({1})", 1000000 - rainyWeekends, (1000000 - rainyWeekends) / 1000000);
    Console.ReadLine(); // Keep the program from closing.
}

Now you can run your new creation:

Probability Simulator Results

You just simulated about 19,200 years worth of weekends.

Not bad, huh? If you round, you’re spot on with the calculations. The math predicted almost exactly what the program would do. That, my friends, is pretty cool.

Creating a Calculator with C# Part 7: Tying up the Loose Ends

This is it. We’re done after this. That’s right – I will cast you off into the land of C#. Alone. It’s a sort of sad reality.

In this tutorial, we’re going to fix all those funky behaviors that happen in our calculator but not the Windows one with the help of two Boolean variables – resetFlag and allowDecPoint. You should declare both of them as class variables and set them to true right off the bat.

public partial class frmMain : Form
{
    // ...
    bool resetFlag = true;
    bool allowDecPoint = true;
    // ...

resetFlag will be used to figure out if the display TextBox needs to be reset when one of the numbers or the decimal point is hit. You can see that “resetting” behavior very frequently in the Windows calculator:

  • Whenever one of the operator buttons or the equals button is clicked
  • Whenever one of the memory buttons is clicked
  • Whenever one of the one-number operations (like square root) is conducted
  • Whenever the calculator displays zero (such as when it first starts up or after the user clicks CE or C)
When resetFlag is set to true, the user will not be able to backspace with the ← button.

The allowDecPoint variable should seem more obvious to you – numbers may only contain one decimal, so after one is put in the display TextBox, no more can be added. This prevents number parsing errors. Notice the glaring lack of error checking in our math. It is not because we don’t assume our users are morons, but because we are simply going to safeguard the code.

Now, let’s start adding places where resetFlag will be set to true. It should be set to true at the end (with the last line of code) of the following parts of our massive if statement:

  • else if (btn.Text == “*” || btn.Text == “/” || btn.Text == “+” || btn.Text == “-”)
  • else if (btn.Text == “=”)
  • else if (btn.Text == “√”)
  • else if (btn.Text == “%”)
  • else if (btn.Text == “1/x”)
  • else if (btn.Text == “MC”)
  • else if (btn.Text == “MR”)
  • else if (btn.Text == “MS”)
  • else if (btn.Text == “M+”)
  • else if (btn.Text == “M-”)
  • else if (btn.Text == “C”)
  • else if (btn.Text == “CE”)

Notice that the pieces of code listed above correspond to the behaviors I described earlier. Coding gets a lot easier when you plan out what you want to do, then write it. It isn’t a dark art. Moving on, we’ve set resetFlag to true in a whole bunch of places but not to false once. That’s a problem. The actual resetting gets done when a user clicks one of the number buttons or the decimal button, so the first part of the if statement seems like a logical place to stick some code. When we reset the display TextBox, we will clear its text, set resetFlag to false, and set allowDecPoint to true, since there is no decimal in the TextBox.

if ((char.IsDigit(btn.Text, 0) &amp;&amp; btn.Text.Length == 1) || btn.Text == ".")
{
    if (resetFlag)
    {
        txtDisplay.Clear();
        resetFlag = false;
        allowDecPoint = true;
    }
    // ...

Now, we need to implement one more tiny piece of the resetFlag modification. Remember when I mentioned that the user can’t backspace when resetFlag is set to true?

else if (btn.Text == "←")
{
    if (txtDisplay.TextLength &gt; 0 &amp;&amp; !resetFlag)
    {
        txtDisplay.Text = txtDisplay.Text.Remove(txtDisplay.TextLength - 1);
    }
}

We’ve added a “&& !resetFlag”. We went over what && is in the last lesson: it’s a logical AND, so for the code within this if statement to execute, txtDisplay’s text length must be greater than zero and !resetFlag must be true. We haven’t covered ! yet. ! is the NOT operator. It is used with Booleans and causes it to behave in the opposite manner from which it is set. That is, !true is false and !false is true. Therefore, in the code above, resetFlag must be false for the code to execute.

Let’s move on to the other variable. You won’t have to add as much code for this one – we only have to make sure allowDecPoint is true when we append a decimal and set allowDecPoint to false when we do. We don’t have to worry about allowDecPoint when we add any other numbers, so we just append the text. Modify the first part of your if statement to look like this:

if ((char.IsDigit(btn.Text, 0) &amp;&amp; btn.Text.Length == 1) || btn.Text == ".")
{
    if (resetFlag)
    {
        txtDisplay.Clear();
        resetFlag = false;
        allowDecPoint = true;
    }
    if (btn.Text == "." &amp;&amp; allowDecPoint)
    {
        txtDisplay.Text += btn.Text;
        allowDecPoint = false;
    }
    else if (btn.Text != ".")
    {
        txtDisplay.Text += btn.Text;
    }
}

The second if statement inside the larger if statement checks to see if allowDecPoint is true if the button text is “.”. If so, it allows the decimal to be appended. Otherwise, the != operator (not equal to) is used to see if the button’s text does not equal “.”. If it does not, it is a number so it gets added to the TextBox. Notice that if btn.Text is “.” and allowDecPoint is false, nothing happens, so it is not added to the TextBox.

Now, remember the reciprocal DivideByZeroException possibility I mentioned in the last lesson? We’re going to fix that now with another if statement. Rather than allowing the exception to be thrown, you should stop the problem in its tracks. Instead of using a try…catch statement, we’ll use an if statement to see if the value is zero before we divide. If so, we’ll just set the display value to zero:

else if (btn.Text == "1/x")
{
    decimal currVal = decimal.Parse(txtDisplay.Text);
    if (currVal != 0)
    {
        currVal = 1 / currVal;
        txtDisplay.Text = currVal.ToString();
    }
    else
    {
        txtDisplay.Text = "0";
    }
    resetFlag = true;
}

In this case, we use an else instead of an else if because it saves keystrokes – something is either zero or not, so there is no need to type out “else if (currVal == 0)”. If currVal != 0 and currVal == 0 are both false in the same if statement, something is seriously wrong.

Finally, we’ll make some changes to C and CE. Rather than clearing the TextBox, since we set resetFlag to true in both sections, we’ll set txtDisplay to zero like the Windows calculator does.

else if (btn.Text == "C")
{
    workingMemory = 0;
    opr = "";
    txtDisplay.Text = "0";
    resetFlag = true;
}
else if (btn.Text == "CE")
{
    txtDisplay.Text = "0";
    resetFlag = true;
}

To be consistent, open up the designer and set txtDisplay’s Text property to “0″ in the designer. Since resetFlag is true to begin with, it will just be erased when the user hits a button.

We have one last thing to do now: preventing the user from adding leading zeros to a number. Users should not be able to enter something like “00000016″. This isn’t binary! Accomplishing this actually took some trial-and-error, but it is actually trivial to emulate the behavior of the Windows calculator. Change your if(resetFlag) code to look like this:

if (resetFlag)
{
    txtDisplay.Clear();
    if (btn.Text != "0")
    {
        resetFlag = false;
    }
    allowDecPoint = true;
}

This way, the text will be reset again if the user hits zero.

You have been building up to this moment for seven lessons. You should feel very proud of yourself. You have gone from a beginner-level, “Hello World” tutorial to a console calculator to a calculator with a Windows GUI and 28 buttons that closely emulates the functionality of the Windows calculator when it is set in standard mode. Your calculator could be used as what we call a “little blue crutch” in school – a four-function calculator without graphing capability. With some of your new C# skill, you could write a program that graphs equations.

I know that the calculator is a common project for beginners. New developers all go through the “creative” stage, where they write more software than Microsoft. It’s a good thing – I’ve been there. My old computer had a hard drive with perhaps 50 Visual Studio projects, of which perhaps four were done. But still, I had lots of fun. Here are some projects that I enjoyed that you probably will, too:

  • A “network messenger” chat system that can either be connection-less (done with UDP instead of TCP) or use a client-server system (done with TCP, more advanced).
  • A video/media player. If you want, write some visualizations for it. Check out the Bass.NET library.
  • A YouTube downloader. I understand that this is way harder than it used to be. This project was particularly fun – I wrote a plugin system for the conversion formats (including my own FLV music extractor) and later ported it to Python on Ubuntu.
  • A rich text editor.
  • A web browser. Check out .NET’s WebBrowser control. Note that it’s IE-based, so you’ll come to hate it and want to check out WebKit.NET.
  • Pong.
  • A clock or alarm clock.
  • An email client – at least something to send emails. Receiving them is a lot harder (I stopped on mine when I got to MIME parsing).
  • Your own scripting or programming language. I wrote one called BeepScript then wrote a program to play Mario in computer beeps. Fun, fun, fun!
  • A Craigslist watcher.
  • An IDE for .NET similar to Visual Studio. Look into System.Reflection – you can compile .NET code very easily!
  • A .NET disassembler similar to ildasm.exe. Your C# code is actually compiled to a series of “opcodes” that aren’t machine code. The opcodes can be disassembled to CIL (Common Intermediate Language), which is basically .NET assembler. There are methods that allow you to disassemble .NET assemblies within the .NET framework.
  • An operating system. This isn’t very possible in C# (I say very because of COSMOS) but is lots of fun if you really want to learn what is going on with a computer.
  • A screenshot taker.
  • A drawing program or photo editor (or even photo cropper) similar to Microsoft Paint.
  • An RSS reader.

Here are some resources you might find helpful:

Whatever you choose to do, I wish you the best of luck with it. Thank you very much for reading this tutorial series. I hope it was helpful and I truly hope it sparked your interest in programming.

Click here to download my project (requires a VS product from 2010 or later).

A note on the licensing: You will notice that there is a file called license.txt in the root directory of the project. This project uses the MIT license. The MIT software license grants me the copyright (since I wrote it) and gives you unlimited rights to use the code in this project. I would have provided the source as a public domain dedication, but unfortunately, some nations do not have a “public domain”. The MIT license is about as close to the public domain as one can get with a license – you may sell this calculator if you want! I’m not saying that people would buy it.

If you do something interesting with it, I’d love to hear about it in a comment!

Creating a Calculator with C# Part 6: Making Your Calculator Function

In the last part of this tutorial series, you learned how to stick numbers into your TextBox. Hopefully you’re feeling fairly proud of yourself at this point. In this tutorial, we’ll implement the “calculator” part of the whole operation. To sum it up, we’ll make it function. Integral to the whole thing is the “if…elseif…else” statement we learned earlier (the math puns are now over). We’ll be using that to check the button text in our button click method. Based on the button text, the calculator will do something. Unfortunately, we haven’t attached all the Button.Click events yet. Let’s do that now. I won’t force you to type it all out if you don’t want to (I can understand why!).

public frmMain()
{
    InitializeComponent();
 
    btn0.Click += new EventHandler(ButtonClickHandler);
    btn1.Click += new EventHandler(ButtonClickHandler);
    btn2.Click += new EventHandler(ButtonClickHandler);
    btn3.Click += new EventHandler(ButtonClickHandler);
    btn4.Click += new EventHandler(ButtonClickHandler);
    btn5.Click += new EventHandler(ButtonClickHandler);
    btn6.Click += new EventHandler(ButtonClickHandler);
    btn7.Click += new EventHandler(ButtonClickHandler);
    btn8.Click += new EventHandler(ButtonClickHandler);
    btn9.Click += new EventHandler(ButtonClickHandler);
 
    // Below here are all the new ones
 
    btnBack.Click += new EventHandler(ButtonClickHandler);
    btnC.Click += new EventHandler(ButtonClickHandler);
    btnCE.Click += new EventHandler(ButtonClickHandler);
    btnDecimal.Click += new EventHandler(ButtonClickHandler);
    btnDivide.Click += new EventHandler(ButtonClickHandler);
    btnEquals.Click += new EventHandler(ButtonClickHandler);
    btnMC.Click += new EventHandler(ButtonClickHandler);
    btnMMinus.Click += new EventHandler(ButtonClickHandler);
    btnMPlus.Click += new EventHandler(ButtonClickHandler);
    btnMR.Click += new EventHandler(ButtonClickHandler);
    btnMS.Click += new EventHandler(ButtonClickHandler);
    btnMultiply.Click += new EventHandler(ButtonClickHandler);
    btnPercent.Click += new EventHandler(ButtonClickHandler);
    btnPlus.Click += new EventHandler(ButtonClickHandler);
    btnPlusMinus.Click += new EventHandler(ButtonClickHandler);
    btnRecriprocal.Click += new EventHandler(ButtonClickHandler);
    btnSquareRoot.Click += new EventHandler(ButtonClickHandler);
    btnSubtract.Click += new EventHandler(ButtonClickHandler);
 
}

Every button click now triggers our event. That’s what we want! Now, we can write an if statement to check for every other condition. Change the if statement in your ButtonClickHandler method to look like this:

if ((char.IsDigit(btn.Text, 0) &amp;&amp; btn.Text.Length == 1) || btn.Text == ".")
{
    txtDisplay.Text += btn.Text;
}
// Two-number operations
else if (btn.Text == "*" || btn.Text == "/" || btn.Text == "+" || btn.Text == "-")
{
}
else if (btn.Text == "=")
{
}
// One-number operations
else if (btn.Text == "±")
{
}
else if (btn.Text == "√")
{
}
else if (btn.Text == "%")
{
}
else if (btn.Text == "1/x")
{
}
else if (btn.Text == "←")
{
}
// Memory operations
else if (btn.Text == "MC")
{
}
else if (btn.Text == "MR")
{
}
else if (btn.Text == "MS")
{
}
else if (btn.Text == "M+")
{
}
else if (btn.Text == "M-")
{
}
else if (btn.Text == "C")
{
}
else if (btn.Text == "CE")
{
}

This if statement handles every possible button input. Notice the change to the original statement. The || (“logical OR”) operator is used. The logical OR operator allows code to execute as long as one condition is true. So, if the character is a digit (which we want to add to the screen) or if the character is a decimal (which we also want to add to the screen), we will add it because in either case, (char.IsDigit(btn.Text, 0) || btn.Text == “.”) will be true.

Look at it mathematically – Booleans are essentially just bits, with a value of either 0 (false) or 1 (true). Bool1 || Bool2 || Bool3 || … || BoolN will return true if at least one of the values between Bool1 and BoolN is true. So false || false || true || false is true.

This operator gets used again in the first else if statement.  Obviously, btn’s text can’t be both all four of the characters it is compared against, but the code in that statement will execute if it is one of those characters.

There is also another big change to the first statement – I found a bug in my original code as I tested! Adding the btn.Text.Length == 1 check ensures that “1/x” does not get appended to the TextBox when that button is pushed. The && (“logical AND”) operator is the exact opposite of the logical OR operator: if any one value is false, the logical AND will return false. This means that True || True || False || True returns false.

Now, we simply plug in code to wire the calculator up, right? Easier said than done (especially when we get into idiot-proofing in the next tutorial), but we can start with the one-number operations right now, since they are the simplest. I mentioned a while ago that .NET has a whole bunch of numeric data types to choose from. We are absolutely not going to use integers – no modern calculator only does integer math and we don’t have hardware limitations. What else can we use? We could use floating points (the .NET type System.Double), but since floating points store approximations, we don’t want to go down that road. Luckily, .NET has a memory-hogging, slow, lovable data type called Decimal. Decimal can store just about any value you ever want. Its maximum absolute value is about 7.92×10^28 and its minimum absolute value (besides zero) is about 1×10^-28. That’s more than good enough.

Not convinced yet? This is the full maximum value your calculator can hold: 79,228,162,514,264,337,593,543,950,335. If 79 octillion isn’t big enough for you, then you still have another 228 septillion to go through. If that still isn’t enough, then perhaps you should just find a better calculator!

Now then, we’ll start with the ± function. We’ll get the current value of the TextBox, convert it to a Decimal, negate it (if it is negative, it will become positive and vice versa), convert its value back to a string, and then set the TextBox’s value equal to it. How do we do that?

else if (btn.Text == "±")
{
    decimal currVal = decimal.Parse(txtDisplay.Text);
    currVal = -currVal;
    txtDisplay.Text = currVal.ToString();
    // Shorthand version:
    // txtDisplay.Text = (-decimal.Parse(txtDisplay.Text)).ToString();
}

This code is displayed in both the long version and the shorthand version that I would probably use and have to write a comment about in production code. It gets the value of the display TextBox (with a glaring lack of error checking), negates it, then sets the display text again. The shorthand version does the same thing with a few more parentheses and two fewer lines of code. Both do the exact same thing.

With the ± function done, we can move on down to the √ (square root) operation. Just like before, we’ll get a Decimal value, but this time we will square root it. C# does not have a power operator or a square root operator (the same as raising a number to a power of 1/2) so we will have to use a method in the System.Math class.

else if (btn.Text == "√")
{
    decimal currVal = decimal.Parse(txtDisplay.Text);
    currVal = (decimal)Math.Sqrt((double)currVal);
    txtDisplay.Text = currVal.ToString();
}

The most noteworthy part of this code is the second line. Math.Sqrt (the square root function) takes a double as an argument and returns another double. This is probably due to performance reasons but it comes at the expense of accuracy. We will simply have to convert from a Decimal to a Double and back again. We accomplish that with a cast – first on currVal inside the parentheses and then on the whole thing.

Next are the % (percent) and 1/x (reciprocal) buttons. Note that the reciprocal button will crash the program if you try to find the reciprocal of 0. This will be fixed in the next tutorial. For now, we do something similar to the last two methods:

else if (btn.Text == "%")
{
    decimal currVal = decimal.Parse(txtDisplay.Text);
    currVal = currVal / 100;
    txtDisplay.Text = currVal.ToString();
}
else if (btn.Text == "1/x")
{
    decimal currVal = decimal.Parse(txtDisplay.Text);
    currVal = 1 / currVal;
    txtDisplay.Text = currVal.ToString();
}

For the percent, we divide the value in the TextBox by 100. For the reciprocal, we divide 1 by the value in the TextBox. Feel free to try these out – provide some input and hit the button. If you find the reciprocal of a number that has a repeating decimal, the rounding will be a little off if you hit the reciprocal button twice. Try this with the number 7 or 9. We won’t worry about that for the time being.

Next is the back (←) button. This button needs to trim off the last character of the TextBox.

else if (btn.Text == "←")
{
    if (txtDisplay.TextLength &gt; 0)
    {
        txtDisplay.Text = txtDisplay.Text.Remove(txtDisplay.TextLength - 1);
    }
}

This code actually contains some error checking – if the text length of the TextBox is zero, then the line within the if statement will throw an exception. The check prevents the exception. If you are wondering how I find all these properties, I don’t usually have to remember the name or even look on MSDN. You should notice when you type something into the editor that a little box pops up sometimes:

Intellisense Image

This is one of the most helpful inventions of all time at work.

This box contains everything that has to do with whatever variable or class you’re working with. It also contains information about method arguments.

Anyway, back on subject – the String.Remove method as we’ve used it gets rid of everything at or after the specified character index in the string. Indices are zero-based (the first character is at index zero, the second is at one, and so on) while lengths are one-based (one-character strings have a length of one, two of two, and so on), so we have to subtract one from the string’s length to get the last character. We then remove it and set the TextBox text.

Now, we move on to the memory. We need to declare two new class variables. One should be called memory and the other should be called workingMemory (because I can’t think of anything better to call it). Memory will be used for the memory buttons (MR and the like) while workingMemory will store numbers before operations are conducted on them. Both should be Decimals. While you’re at it, declare a string called opr (short for operator, which we can’t use as a variable name because it is a C# keyword).

I say class variables because they need to be accessible to all the methods in the class. The curly brackets help categorize everything in your code, but they also define a hierarchy. Variables declared at one hierarchical level cannot be accessed at a higher one.  The more open curly brackets you are within, the lower your hierarchical level is. Class variables live in the class, not a method, and so are accessible to all the methods of the class.  All that explaining was for this:

public partial class frmMain : Form
{
    decimal memory = 0;
    decimal workingMemory = 0;
    string opr = "";
// ...
// The rest of the code goes here

Now that we’ve declared and initialized our variables, we can start working on the memory piece of the application. The easiest part (not that any of them are difficult) to implement is the MC function. MC clears the memory. Simply set memory equal to 0. For MR, we have to recall the memory value into the TextBox – set the Text to a string version of the memory variable.

MS stores the TextBox value in memory and removes the value from the TextBox, so we will just set memory equal to the value in the TextBox then clear it. Finally M+ and M- add and subtract (respectively) from the value stored in memory, so we act accordingly in the code. This part is actually quite simple.

else if (btn.Text == "MC")
{
    memory = 0;
}
else if (btn.Text == "MR")
{
    txtDisplay.Text = memory.ToString();
}
else if (btn.Text == "MS")
{
    memory = decimal.Parse(txtDisplay.Text);
    txtDisplay.Clear();
}
else if (btn.Text == "M+")
{
    memory = memory + decimal.Parse(txtDisplay.Text);
}
else if (btn.Text == "M-")
{
    memory = memory - decimal.Parse(txtDisplay.Text);
}

Before we move on to the “big four” operations, we have to take care of C and CE. C means clear – it clears the working memory (not the number the user chose to store in memory), the operation, and the TextBox. CE means clear entry and only clears the TextBox. We can write the code to take care of both of those:

else if (btn.Text == "C")
{
    workingMemory = 0;
    opr = "";
    txtDisplay.Clear();
}
else if (btn.Text == "CE")
{
    txtDisplay.Clear();
}

Setting opr equal to an empty string (“”) will come into play later with the equals button, and setting workingMemory to 0 will have an effect too. Both of these methods call txtDisplay.Clear() which is a fast way of getting rid of the text in a TextBox. Now, we move on to the operations.

The way we will be making these operations work is rather rudimentary. In the next tutorial, we’ll look at how we can better emulate the way the Windows calculator works since it is something most users are already familiar with and will reduce our program’s learning curve. For now, in our operation part of the if statement, we need to set what the operator is, set workingMemory, and clear the TextBox so the user can enter more values. Easy enough, right?

else if (btn.Text == "*" || btn.Text == "/" || btn.Text == "+" || btn.Text == "-")
{
    opr = btn.Text;
    workingMemory = decimal.Parse(txtDisplay.Text);
    txtDisplay.Clear();
}

Finally, in the equals button part, we need to get the second value from the TextBox and put a resulting value in the TextBox based on what the operation is. For this, I’ve decided to use a switch statement. The reason I used an if statement instead of a switch statement before is because you cannot use method calls in a switch like I did in the if – you can only compare values (so char.IsDigit(btn.Text, 0) would not be allowed, which would add a bunch of code). This time, there are only four possible values, so I chose a switch:

else if (btn.Text == "=")
{
    decimal secondValue = decimal.Parse(txtDisplay.Text);
    switch (opr)
    {
        case "+":
            {
                txtDisplay.Text = (workingMemory + secondValue).ToString();
                break;
            }
        case "-":
            {
                txtDisplay.Text = (workingMemory - secondValue).ToString();
                break;
            }
        case "*":
            {
                txtDisplay.Text = (workingMemory * secondValue).ToString();
                break;
            }
        case "/":
            {
                txtDisplay.Text = (workingMemory / secondValue).ToString();
                break;
            }
    }
}

Your calculator is now totally wired. It’s far from user-friendly and has some minor issues, but we’ll work on it! You can do one thing to reduce errors right now – go to the Forms designer, click on the TextBox, and set its ReadOnly property to true. This will prevent troublemakers like me from typing gibberish into your TextBox.

Great job on this tutorial. At this point, you have a working calculator. The only thing left to do is to make it work well.

Working Calculator Image

Woo-hoo!!

Bot Blast 2012 Full Event Report

Having not competed since Motorama (and not competed in a Mall for five or so years), I was very excited to fight robots at the Columbia Mall in Bloomsburg, PA. We woke up around 7:30, had a terrible breakfast (why would you serve one egg by itself on a plate with an orange?) at Cracker Barrel, and were at the venue by 9:00ish. I was pleased to see that Bot Blast has a wooden floor because it would not interfere with Lolcat’s radio reception. Wooden floors are also a bit quieter and more forgiving.

This event report contains some fight videos, but only for the interesting ones. I have only included one Lolcat vs Tracked Terror fight and did not include any Amatol fights.

John in the Arena Image

With the guys.

We got through safety inspections without much of a hitch. Coercion was a tiny bit overweight (as was Amatol) but apparently the scale was off by a bit so I didn’t have any issues. We sat around and waited for the event to start. Fights kicked off around noon, which is way earlier than they would at Motorama. We were all impressed.

The first fight of the day for us was with Coercion against Kyle’s fearsome vertical spinner, Ripto. I knew it would be a tough match for Coercion (especially in an eight-foot arena like the one at Bot Blast) but I never imagined it would be as tough as it was. We both spun up and Coercion went flying into the ceiling. The S7 blade (which I did not have hardened for some unthinkable reason) was bent about 30 degrees upward. I tried to push Ripto, hoping that the belt would come off the weapon, but it was no use. I quickly tapped out.

I do not have any images of the bent blade because I was so concerned about getting it fixed. I can tell you that it took some vice smooshing and beating with a hammer to get it back into shape. I did, however, get Coercion fixed.

The next first-round match was between Amatol and another wedge bot. After about thirty seconds of pushing, Amatol ended up stuck on the wall and was counted out. Amatol’s wedge wasn’t getting it done and I lost because of it. The next version will need a bent back. 0-2!

At this point, I was running seriously low on robo-mojo. It was Lolcat’s turn to fight a small undercutter called Baby Box. Undercutters have always scared me with Lolcat ever since Jeremy Campbell’s Rebound broke the eggbeater twice at Motorama 2011. I was hoping that it would not be able to cut my belt or worse, rip the eggbeater out of its supports. After accidentally hitting the blade a few times, I felt like my robot would hold up. I eventually removed the other robot’s weapon. Unfortunately, I did not remove either of Baby Box’s wheels (there seemed to be some foam padding helping there) and I was unable to cut Baby Box’s exposed battery connector. But still, I won the match on a judges’ decision.

With some of my mojo restored, I set my sights on my next antweight opponent, Mateo. I had to postpone my match because of connector issues (which would come back to haunt me), but when we finally got in the arena, the match was boring. We pushed each other around and Mateo wound up stuck on the arena, and after being left on the wall twice, I decided not to risk freeing it. I felt horrible but won by knockout.

With two wins under my belt, I started to calm down a little bit. I had been seriously worried at the beginning of the event, but I chalk it up to a combination of bad luck, poor foresight and great opponents. My next fight was another with Lolcat. This time, it was against Hedgehog, which was the fairyweight I thought had the best chance of breaking Lolcat coming into the event.

The fight began and we both spun up. Hedgehog tried to attack my wheels as I moved to attack its wheels, so our weapons ended up making contact. After seeing that my beater could stand up to Hedgehog’s large, direct-driven blade, I became a little more aggressive. My strategy worked – one hit sent Hedgehog a good foot or so into the air and the next sent us both flying. The second hit broke Hedgehog’s weapon motor in two and Lolcat won by tapout.

The damage to Lolcat from this fight was actually a lot worse than it appeared. Lolcat’s weapon shaft was a little bit tweaked, the pulley had a big gash taken out of it, the right weapon bearing’s dust covers were broken off, and alarmingly, the weapon belt was nearly sliced in two! I made a new belt but chose to keep the shaft as it was since it did not appear to impact weapon performance. A quick spin up test confirmed that, and Lolcat was ready to go once again.

My next opponent was a beetleweight vertical spinner called Lezlee. Considering my blade had just been re-straightened, I was happy to just be fighting. I noticed that Lezlee had thin aluminum armor, and since Coercion appeared to be on its last legs at the time, I decided to just go all-out. I spun up and chaos ensued. I chewed away at the front of Lezlee (somehow while avoiding the blade), and one hard hit jarred its LiPoly free. Jeremy is smart enough to know a one-pound piece of spinning steel could do bad things to an explosive battery, so he called the match. Coercion won by knockout.

The next fight was Amatol vs Kyle’s Cutter, an antweight spinner. I was confident heading into the fight because Amatol was built to fight spinners, not wedges, so I was looking forward to testing my robot’s strength. Unfortunately, I box rushed Kyle’s Cutter, hit the wall, and one of the battery connections in the speed controller came loose. Amatol was dead in the water and I tapped out less than three seconds into the match. I thought some very non-PG words after that fight.

With Amatol out after two stupid, preventable losses (AGAIN!), it was Coercion’s turn to continue carrying the Team Slammers banner. It was matched up against Play ‘n Krazy, which was fighting as a lifter at Bot Blast but is usually a vertical spinner. I was looking for revenge for my three-second match, and I got it in the form of a nine-second one. Coercion spun up and delivered a hard hit to the front of Play ‘n Krazy. The hit removed a wedge panel, a wheel, a wheel guard and a receiver and Play ‘n Krazy tapped out.

Lolcat was up next in the fairyweight winners’ bracket semifinal against The Tracked Terror. This was the first of three straight matches between these two robots. The Tracked Terror beat Lolcat at Motorama, so I was out for revenge. We traded blows for two minutes but Lolcat won on judges’ decision. More on these matches later.

The next fight for us was Coercion vs Counter Shock. Counter Shock was a very well-built beetleweight drumbot, but the drum wasn’t working so all I had to do to win was to keep the weapon running and not get stuck on the wall. I only accomplished the weapon part. I spun up and hit Counter Shock hard, but unfortunately, the hit also flipped Coercion over. It was too tall to hit Counter Shock, and got pushed up against the wall. Counter Shock gave Coercion one final shove, and the wheels could not get traction. Coercion was counted out, leaving Lolcat as our only robot still in the tournament.

Despite being out, Coercion still had one trick left up its sleeve – the beetleweight rumble. Although it ran out of battery at the end, it was crowned co-champion of the rumble along with mantisweight Dead Metal (since there was no mantis rumble). I think it had something to do with the flying around everywhere thing (see the video) combined with my exuberant cheering at the end of the match.

Lolcat was in up next against The Tracked Terror in the first fairyweight final. This match did not go as well for Lolcat as the semifinal did. I kept getting flipped over and according to Jeremy, lost on aggression. The good hits were also 3-2 in favor of Tracked Terror. I was worried – I was very close to finally getting a win with Lolcat, but it was going to come down to an all-or-nothing final. I charged my batteries and decided that no matter what, I would keep chasing Tracked Terror. Lolcat uses 50:1 gearmotors instead of the 30:1 ones used by Tracked Terror, so it was at a major speed disadvantage.

Nearly two years of work came down to one final match. I wanted to win really badly. I stayed aggressive. I followed the game plan. Luckily for me, it all worked out. Lolcat won on a judges’ decision and was crowned fairyweight champion. Congratulations to Chris on building an awesome robot! Lolcat could barely scratch it.

So, with the event over, what did I take away?

  • Lolcat is too slow and 30:1 HP Pololu gearmotors instead of 50:1 Sanyo gearmotors would do it a lot of good.
  • Coercion’s blade is too heavy and needs to be hardened. At Motorama, I plan on using an 11-12oz blade spinning at closer to 10,000 RPM. I will keep the MOI as high as I can while designing it.
  • Amatol needs… improvements. It is very strong but keeps failing in dumb ways. I will make some adjustments to keep it from getting stuck on the wall and hopefully the robot lords will smile upon me at Motorama.

Due to SATs, we won’t be able to make it to Franklin Institute this year. Any changes we make won’t be tested for a very long time!

Another big thanks goes out to Jeremy Campbell for putting on a great show. We will definitely be back next year!

Back from Bot Blast!

My dad and I are back from Bot Blast. I’ll write up a full event report tomorrow. For now, here are the results:

  • Lolcat: 4-1, 1st place
  • Amatol: 1-2, did not place
  • Coercion: 2-2, did not place, won rumble along with Dead Metal

I want to extend the first of many thank-yous to Jeremy Campbell, the EO, for putting on an awesome event. We had a lot of fun and it was worth the long drive.

To keep you occupied until tomorrow, here’s eventual beetleweight winner Ripto bending Coercion’s S7 blade. Maybe I should harden the next one!

Creating a Calculator with C# Part 5: Casting, Handling Events, Getting Input and Useful Methods

My thoughts and prayers go out to every individual who was hurt in the shootings last night in Colorado.

In the last installment of this tutorial, you learned how to use the Windows Forms editor. That’s a big step, but the Windows Forms editor isn’t much help if you don’t know how to use your creation. I saw Spiderman last night (because I didn’t want to stay out until two watching Batman on a day I had to drive for 4 hours), and using the Forms editor without being to write the corresponding code is kind of like inserting lizard DNA into your body when it actually turns you into a lizard – insane.

Now, open up your project and right-click on the form you made. Choose “View Code”. The code editor that you saw with the console application will pop up, but the code will look different. Where’s the main method, you ask? It’s there – but it’s in Program.cs. I suggest you don’t mess with it right now. Anyway, you have a code file that looks like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace Calculator
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
    }
}

This seems a little more complex than the console application, does it not? Just like before, we have using statements (although Windows applications have more by default). We have a namespace and a class and a method. There are two key differences. The first is the “: Form” thing, and the second is that the frmMain() method doesn’t have a return type.

The “: Form” thing means that our class inherits from the class System.Windows.Forms.Form. The Form class provides basic form functionality and lets us put controls on the screen. We can set the size of the form, change the color of the form, move the form, and do pretty much whatever we want with the form. Inheriting from the Form class allows us to get that functionality and add whatever we need onto it.

The latter difference also bears a lot of explaining. It is called a constructor. Constructors are methods that are called whenever a new instance of a class is created. What do I mean by that? Remember how I told you that you can use classes as variables? Each variable contains a different instance of a class, and a class instance is created with the “new” keyword. So a class could contain two variables, v1 and v2, and two variables could be declared with separate instances of the class. v1 and v2 could be 1 and 2 in the first and 5 and 6 in the second, like so:

// Call this from the Main method of a console application.
static void ClassExample()
{
    A a = new A();
    A b = new A();
    b.v1 = 5;
    b.v2 = 6;
 
    Console.WriteLine(a.v1 + " " + a.v2 + " " + b.v1 + " " + b.v2);
}
 
// Put this outside the Program class
public class A
{
    public int v1 = 1;
    public int v2 = 2;
}

The above code will output “1 2 5 6″. Declaring something within a class as static means it does not go with an instance of a class; changing it will affect all instances.

For now, all you need to know is that the constructor runs before the form opens. We’re going to take advantage of that by adding some code to the constructor:

public frmMain()
{
    InitializeComponent();
 
    btn0.Click += new EventHandler(ButtonClickHandler);
}

While you’re add it, add the ButtonClickHandler method to stop the error about ButtonClickHandler not existing in the current context:

private void ButtonClickHandler(object sender, EventArgs e)
{
    throw new NotImplementedException(); // Prevent head-scratching later on.
}

Now I have three more things to explain: the btn0.Click += part, the private keyword and the arguments that ButtonClickHandler requires.

  • btn0.Click is called an event. The event happens when btn0 (the zero button – I’m writing this a full day later and I can figure out what controls do because of my naming convention!) is clicked. += is an operator that appends something, so you are essentially adding the event handler method to the Click event. In other words, when the user clicks the button, that method will be automatically called.
  • The private keyword means a method may only be called by other methods in the same class. There is no sense in making an event handler public; it will only make it easier for outside code to interfere with our program.
  • ButtonClickHandler requires two arguments: sender and e. Sender is whatever raised the event – so when you click btn0, sender is btn0. The EventArgs (e) are the base EventArgs class and don’t do anything useful, but some EventArgs let you do cool things like keep a form from closing when a user presses the X button or getting the location of the mouse.

But John, you said C# is type-safe. The type of btn0 is Button, not object! That should be an error!

I like the way you’re thinking, but remember inheritance? Btn0 is a button. You’re correct about that, but if you go back far enough in the family tree, btn0 is an object because every single class in C# is an object. String is an object. EventHandler is an object. System.Linq.ParallelQuery is an object. So, you can use a cast to convert the object into what it actually is. We’ll get there in a bit. For now, add this event handler to the other nine number buttons.

public frmMain()
{
    InitializeComponent();
 
    btn0.Click += new EventHandler(ButtonClickHandler);
    btn1.Click += new EventHandler(ButtonClickHandler);
    btn2.Click += new EventHandler(ButtonClickHandler);
    btn3.Click += new EventHandler(ButtonClickHandler);
    btn4.Click += new EventHandler(ButtonClickHandler);
    btn5.Click += new EventHandler(ButtonClickHandler);
    btn6.Click += new EventHandler(ButtonClickHandler);
    btn7.Click += new EventHandler(ButtonClickHandler);
    btn8.Click += new EventHandler(ButtonClickHandler);
    btn9.Click += new EventHandler(ButtonClickHandler);
}

Now, whenever you click one of the number buttons, your program will crash because of an unhandled exception! Exciting stuff – you can try it out if you want but we really need more functionality than that. Go to your handler and add this (by the way, my TextBox is named txtDisplay):

private void ButtonClickHandler(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if (char.IsDigit(btn.Text, 0))
    {
        txtDisplay.Text += btn.Text;
    }
}

WHOA, WHOA, WHOA! I thought this was a basic course on C#! That looks like gibberish! I know it does, but it’s the best I can do to make that work. The way this calculator is going to work is to save ourselves a lot of extra coding, we’re going to have one event handler for all the buttons, and figure out which button we’re working with based on sender. To do so, we create a button variable, and use what is known as a cast to turn sender into a Button. You can’t do that arbitrarily; the classes must be compatible. That is, going back and forth from Button to object is fine, but going from Button to TextBox would cause your program to crash.

The next thing the code does is to look at the button’s text and decide if it is a number. The char.IsDigit method does just that. Since the number buttons only have one digit on them, using char (which represents a character in C#) is fine because one digit means there is only one character. If the character turns out to be a number, we add it to the display with the += operator, which appends it.

I know this was a short tutorial, but I have to get on the road to Bot Blast now. As always, thanks for reading!

Bot Blast 2012 Pre-port

I’ll be attending a robot competition in Bloomsburg, PA this Saturday (July 21st). If you live around there, it’s in the mall gazebo at the Columbia Mall. Fighting should start by 11:00 and we’ll be done by 7:00. 150g fairyweights, 1lb antweights, 3lb beetleweights and 6lb mantisweights will be fighting. It’s worth driving a couple hours to see. I understand that it’s a very fun event for builders and spectators alike. I’ve only fought in a mall once but it was one of my favorite events of all time.

I’ve been working hard over the past few days to get ready because just like every other robot builder, the 1-week mark seems like a good time to start prepping to me. Luckily, I didn’t have much to do. Here’s a picture of the three robots I’m taking:

Robots Before Bot Blast

I promise they won’t look this good on Saturday night.

Here’s the lo-down on changes I’ve made to my robots since they last competed (at Motorama in February) and how I think they’ll fare:

lolcat

Changes:

  • Complete redesign of sides. They are now taller and the front beater support has been swept back slightly so wedges will tend to hit beater first instead of support first. They are also made of polycarbonate now, so they are lighter and do not cause radio interference.
  • Upgraded from a custom 2S 160mAh LiPoly to a ready-made 2S 180mAh LiPoly that is capable of 40C burst current. The new battery seems to work much better and fits better as well. It can also be balanced.
  • New wheel guards provide more wheel padding so the plastic has time to absorb more energy. They are also swept back more and will hopefully be less flexible. The screws are farther from the edge on the new ones, too.
  • Because of the height, all components now fit inside the robot.
The current lolcat is running extremely well. If it does not suffer from any radio issues (receiver failures or interference) it will place in the top three.

Amatol

  • Replaced a drive motor that was taken out at Motorama for use as a spare.
  • Remarkably unchanged. Hopefully this robot will have better luck at Bot Blast!
There are a lot of antweight wedges going to Bot Blast, so winning will come down to driving and having a lower wedge. Amatol does both well, so it should pull off at least two wins and if it gets a lucky draw, could place in the top three.

Coercion

  • Weapon is now supported by ball bearings which reduce friction and allow for a tighter weapon belt.
  • Weapon belt has been tightened significantly to prevent slippage.
  • Weapon can now be fully tightened which should reduce flexing into the weapon pulley like what happened at Motorama.
  • 1Ah 3S LiPoly has been replaced by a 1.3Ah 2S LiPoly to meet the increased current demands of the motor with a tight belt driving a 1lb blade and to combat the increase in power consumption by lowering the voltage.
  • Grease has been removed from the robot to reduce belt slippage.
  • Polycarbonate wheel guards have been fashioned to use instead of the ABS ones that fared so poorly at Motorama.
  • I have purchased spare motors and wheels! The motors can also be used in Amatol.
  • Drive motors are now protected with foam to prevent the magnets from breaking during big hits.

The beetleweights at Bot Blast are excellent. Coercion hits very hard (it will go through quite a bit of aluminum and bend titanium) but is unproven in the arena, unlike the rest of our fleet and the rest of the beetleweights there. Assuming it holds together, it could do very well, but that can be said for any robot. Coercion is a tough call but placing in the top three is highly unlikely.

I am extremely excited for Bot Blast. I’ll post an event report, videos, and pictures when it’s done!

Creating a Calculator with C# Part 4: Designing the Windows Form

We now move on to the fun part: creating a GUI. GUI creation in C# requires absolutely no code. You can drag-and-drop what are known as controls on to your window, which is called a form. Controls are items on a form that serve some sort of function. I realize how broad that definition is, but controls can be anything from a TextBox (which you use to enter text) to a Button to a Label to a WebBrowser. C# provides you with all sorts of goodies to make cool programs with. In this tutorial, you will be designing your calculator window. Now, I know you have never designed a form before, so we should probably have a model to design our form from…

The Windows Calculator

Oh, hey. That’s convenient.

The Windows calculator is actually a very useful program. Most of the time, I use it in scientific mode because it is the most familiar to me (since I use a TI-30XIIS in school whenever I don’t need to graph and a TI-84+ when I do), but there are other modes as well. The programmer mode is actually kind of useful for testing logic operations before you try them in code (having a xor button can come in handy).

Windows Programming Calculator

So is being able to enter numbers in binary.

Our calculator will be based on the most basic calculator. It will have all of the same functions, but will look a little different. Why? The Windows calculator uses a theme that looks like Windows Ribbon, and we’ll be using the default theme. What’s Ribbon, you ask? Look at Microsoft Word 2007 or later and compare it to Word 2003.

I hate to break it to you, but you’ll need to create a new project in Visual C#. Fire it up, then go to File > New. This time, select Windows Forms Application as your project type and name your project Calculator. Hit OK. Go up to the View menu, and choose Toolbox (or press Control+Alt+X) and then go up again and choose Properties Window (or press F4). Press the pushpin icon to make both windows dock. Your window will change to look something like this (remember that I have Visual Studio so my window has a few additional features):

Windows Forms Designer

No errors! So far, so good!

I know it looks overwhelming, but you will find the forms designer to be fast, easy and intuitive. On the left side of the screen is the toolbox. It contains every control that you can use in your C# application. The most common ones are listed under Common Controls, but at the top (where it says All Windows Forms), you can find all the controls. On the right side is the property editor. It modifies a control’s properties. What are properties, you ask? Properties are attributes of a control – anything from a label’s text to a form’s border style. To modify a control, click on it and then search for the corresponding property in the editor. I’ll walk you through it more once we start adding controls.

In the top middle is the form preview. When you drag-and-drop (yes, drag-and-drop!) controls from the toolbox into the form, you can move them around. What the form looks like here will be what it looks like when your program runs. If you make a mistake when adding a control, you can either right-click it and choose delete or click on it and press the delete key.

Finally, the bottom middle has the error list. You may have seen it before if you made mistakes in the first three tutorials. If you can’t see it now, you can go to View > Error List. Make sure to click on the pushpin if you want it to stay showing. Otherwise, it lives in the bottom toolbar.

Let’s start designing our calculator form. Drag the box at the bottom right of the form out to make it a little bit bigger, then add a TextBox to the form from the common controls in the toolbox. You’ll notice that if you mouse over it, your cursor indicates that you can move it. Drag it to the top-left of the form. You’ll notice some blue spacer lines appear. They are suggesting how close your TextBox should be to the edge. Let me suggest something – listen to them. They know what they’re talking about. Finally, drag the right side of the TextBox over so that it stretches all the way across your form. Again, pay attention to the blue lines. When you’re done, it will look like this:

Form with Textbox

It already looks like a calculator.

Now, we’re going to edit the TextBox’s properties a little bit. Make sure it’s selected, then go to the properties editor. Find where it says (Name) and change textBox1 to txtDisplay. Then, go to Font and click in the box to the right of it. A button with an ellipsis will pop up. Click that button, and an editor will pop up. Change the font size to 24pt. Notice how the TextBox grows.

Now, why did we change textBox1 to txtDisplay? When we access the TextBox through code, we will want to know what it does. Imagine having a form with 16 TextBoxes, named textBox1 through textBox16. One of the TextBoxes has a first name in it. Which is it? Now imagine it’s named txtFirstName – it becomes self-explanatory. The txt prefix categorizes the control and makes it easier to find. You should always prefix your control names. Here are some prefixes I use:

  • frm for Form
  • txt (sometimes tb) for TextBox
  • btn for Button
  • lb for ListBox
  • rtb for RichTextBox
  • lbl for Label
  • pan for Panel
  • cb for ComboBox

Notice how the prefix is simply an easy-to-remember abbreviation. If you want, you can rename the form from Form1 to frmMain (I usually name my Windows Applications’ main form frmMain), but since this program will only have one form, you don’t need to if you don’t want to.

Next, drag two buttons on the form. Resize the first one so it looks like you will be able to have five columns of buttons and 6 rows. Then, place the second one below the first and stretch it to be the same width, then place it to the side of the first to make it the same height. The little blue helper lines (or maybe a pink line which indicates alignment) will appear again to let you know when you’re all set!

Adding Buttons

2 down, 26 to go.

Now, start adding buttons to make your window look like the Windows calculator. Remember that the button on the bottom-left is two buttons wide and the one on the bottom right is two buttons tall. Don’t worry about fonts, names or text yet. Just get the buttons on the form. If you need to, you can resize the buttons or the form to make everything fit. Making this part look good is up to you – I can’t drag-and-drop for you (actually, I can but I’m not going to). Here’s my finished product. I had to make my form wider and a tiny bit shorter.

Skeleton Form

My example only had 16 TextBoxes with non-descriptive names? We have 28 buttons here!

Hopefully you see the problem here – the buttons look like we have a calculator here, but we have no idea what any of the buttons do. Our users don’t either. I know we don’t like them, but we have to deal with them. Go through all the buttons and change the text to match the Windows calculator. I know your job is to code, not to scour the web for special characters, so here’s all that you’ll need: √±←☺. Okay, you won’t need the smiley face but I included it just in case (you might want to read ahead a bit now).

When you’re done changing button texts, you also need to change the button names. You need to come up with some sort of naming convention for your buttons. A naming convention is a standardized way of naming your controls so you don’t end up with one control named foo3, one named duck, and another named overlyDescriptiveNameForButtonOnLeftSideOfForm. You don’t have to follow the one I suggest, but please make it reasonable. Note that your names can only contain letters, numbers, dashes, and underscores and must start with a letter or underscore.

  • For all numbers: btnNumber (ie. the button for 3 is btn3)
  • Any functional or operation button: btnFunction
    • MC is btnMC, MR is btnMR, MS is btnMS, M+ is btnMPlus, M- is btnMMinus, CE is btnCE, C is btnC
    • ← is btnBack, ± is btnPlusMinus, √ is btnSquareRoot, % is btnPercent, + is btnAdd, – is btnSubtract, * is btnMultiply, / is btnDivide, 1/x is btnRecriprocal, = is btnEquals and . is btnDecimal

That covers it. Now you can get to work. I’ll wait for you to finish by showing you that mine is already done. Haha.

Completed Button Titles

We still haven’t written a single line of code.

Now, there are a few things left to do. The first is to make these buttons look better, because the font looks comically small right now. You can change the font on every button at once by clicking one, then holding shift or control and selecting all the others. Just like before, click on the box to the right of where it says “Font” in the property editor, then click the button that pops up. Change the font to whatever you want. Bold 14pt seems to be big enough for my huge calculator.

Next, we’re going to modify the form, so click on the border to deselect all the buttons and to select the form. Change the Text property from “Form1″ to something better. “My Calculator” wouldn’t be bad. Next, find the MaximizeBox property and set it to false by clicking where it says True next to it, hitting the button that pops up, and choosing false. Finally, change FormBorderStyle to FixedSingle. The last two actions will keep users from resizing your form at all.

Now, the moment of truth. Hit F5 or press the green play button to run your program and display your form.

Finished Product

It’s beautiful.

You can type in the TextBox and hit all the buttons. Of course, nothing happens yet because we haven’t written any code, but we still have a beautiful product.

A common question is how the heck the Forms Designer works, since the buttons just appear and you don’t have to write any code. If you go to View > Solution Explorer and click the arrow next to Form1.cs, you will see two more files pop up. The designer generates code, which gets put in Form1.Designer.cs. My designer file has 425 lines of code in it. The designer just saved you a ton of work – learn to use it well and you will be making gorgeous GUIs very quickly. Good work today!

Creating a Calculator with C# Part 3: Custom Methods, Throwing Exceptions, Conditional Logic, and a Console Calculator

By now, we’ve covered quite a bit of C#. Hopefully it’s all made sense to you and you’re starting to see how useful C# can be. If not, rest assured: the really cool stuff will start in the next lesson when we start using the Windows Forms Editor to display the windows you’re used to seeing. For now, open up the project we were working on in the last lesson. We’ll be making some big changes to it. In fact, by the time we’re done, we’ll have a basic four-function calculator. Of course, the calculator we end up with will look a lot like the one in Windows, so don’t think you’ll be finishing the series on something so basic.

If you’re just joining us, here’s the entire program from part 2:

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int number1;
                int number2;
 
                Console.WriteLine("Enter a number, then hit enter:");
                number1 = int.Parse(Console.ReadLine());
                Console.WriteLine("Enter another number, then hit enter:");
                number2 = int.Parse(Console.ReadLine());
 
                int sum = number1 + number2;
                Console.WriteLine("The sum is: " + sum.ToString());
 
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Main(args);
            }
        }
    }
}

We’ll start by adding four methods to the Program class. There are two obvious questions here: where do you put a method and how do you declare one? The first question is somewhat more difficult to answer. Notice the curly brackets ( { and } ) in the code. After the namespace keyword, there is an opening curly bracket ( { ), and down at the bottom, there is a closing curly bracket ( } ). The same happens one tab in below the class keyword. The same happens for Main. Anything between the curly brackets is considered to be “inside” or “part of” whatever the brackets are related to.

So, in this case, the new methods will go inside the Program class but not inside the Main method. Methods in C# can either be “void” or have a return value. Voids do not return any value; they simply perform a task. Functions that have a return value perform tasks and then return information for another method to use. We’ll be declaring four methods with a return type of int. They will also have to be static methods, which means they aren’t tied to a specific class instance. Don’t worry about this right now – just know that since Main is static, it’s way easier to make the other methods static as well. Each method will take two arguments: num1 and num2. The syntax for declaring methods is like this:

static ReturnDataType NameOfMethod (ArgumentDataType arg1, ArgumentDataType arg2, ... , ArgumentDataType argN)
{
    // Code of method
}

So what’s there? ReturnDataType is the DataType we’ll be returning. In our case, it will be int. NameOfMethod is just the method’s name. One will be Add, one will be Subtract, one will be Multiply, and one will be Divide. ArgumentDataType is the DataType of the argument. Look at Main. Args is associated with a DataType of string[]. Arg1, Arg2, and ArgN are simply the names of the arguments. Just like main, the example method has curly brackets. Let’s declare our four methods now.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Hello_World
{
    class Program
    {
        // Below Main method - don't delete the Main method!
 
        static int Add(int num1, int num2)
        {
        }
 
        static int Subtract(int num1, int num2)
        {
        }
 
        static int Multiply(int num1, int num2)
        {
        }
 
        static int Divide(int num1, int num2)
        {
        }
    }
}

Hopefully it’s painfully obvious what these four methods will do. But how do you return a value from a method? The return keyword. You can return a value in a similar way to how you would set a variable, except you don’t use an equals sign. When a return statement runs, code execution in your method will end, so make sure you’re ready to exit when you use one! I’ll write the multiply and divide methods; I’ll leave the add and subtract methods up to you. Remember that C# is case-sensitive!

static int Add(int num1, int num2)
{
 
}
 
static int Subtract(int num1, int num2)
{
 
}
 
static int Multiply(int num1, int num2)
{
    return num1 * num2;
}
 
static int Divide(int num1, int num2)
{
    return num1 / num2;
}

The one flaw with this code is that since we are using integers, num1 / num2 will be an integer, so 3/2 gets rounded down to 1. We’ll be fixing that in the next version of our calculator. For now, everything else will work fine. The next thing that needs to be done is to collect some user input in the Main method to figure out which method to use on the numbers. Below the number2 = int.Parse(Console.ReadLine()) statement, add this:

Console.WriteLine("Which operation do you want? (Choose +, -, * or /, then hit enter):");
switch(Console.ReadLine())
{
}

What’s that switch business? In C#, switch is a keyword used for conditional logic. It lets you check to see if a variable matches a value. In this case, we’ll be comparing what Console.ReadLine() returns to “+”, “-”, “*”, and “/”. If it doesn’t match any of those, C# allows you to create a default case.

switch (Console.ReadLine())
{
    case "+":
        {
            int sum = Add(number1, number2);
            Console.WriteLine("The sum is: " + sum.ToString());
            break;
        }
    case "-":
        {
            int difference = Subtract(number1, number2);
            Console.WriteLine("The difference is: " + difference.ToString());
            break;
        }
    case "*":
        {
            int product = Multiply(number1, number2);
            Console.WriteLine("The product is: " + product.ToString());
            break;
        }
    case "/":
        {
            int quotient = Divide(number1, number2);
            Console.WriteLine("The quotient is: " + quotient.ToString());
            break;
        }
    default:
        {
            Console.WriteLine("You didn't use a valid operator.");
            break;
        }
}

This requires some explaining. The case “string” statements define a case that C# should check the string against. If it matches, the code inside the brackets will be run. If it doesn’t, it will be skipped. The break statements tell C# that the code regarding the case is over. Finally, the default statement provides a default case in the event that the string doesn’t match anything else. It should always go last and should always be present – remember to always assume your user is clueless and will try to break your program. Want to know more? Here is more than you will ever want to. Now, at this point, you can remove all the sum stuff from the last lesson. When you’re done, your Main method will look like this:

static void Main(string[] args)
{
    try
    {
        int number1;
        int number2;
 
        Console.WriteLine("Enter a number, then hit enter:");
        number1 = int.Parse(Console.ReadLine());
        Console.WriteLine("Enter another number, then hit enter:");
        number2 = int.Parse(Console.ReadLine());
        Console.WriteLine("Which operation do you want? (Choose +, -, * or /, then hit enter):");
        switch (Console.ReadLine())
        {
            case "+":
                {
                    int sum = Add(number1, number2);
                    Console.WriteLine("The sum is: " + sum.ToString());
                    break;
                }
            case "-":
                {
                    int difference = Subtract(number1, number2);
                    Console.WriteLine("The difference is: " + difference.ToString());
                    break;
                }
            case "*":
                {
                    int product = Multiply(number1, number2);
                    Console.WriteLine("The product is: " + product.ToString());
                    break;
                }
            case "/":
                {
                    int quotient = Divide(number1, number2);
                    Console.WriteLine("The quotient is: " + quotient.ToString());
                    break;
                }
            default:
                {
                    Console.WriteLine("You did not enter a valid operator.");
                    break;
                }
        }
 
        Console.ReadLine();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        Main(args);
    }
}

This is good enough to run. Try out your calculator. Since I’m pretty good at playing clueless user, I found an inconsistency pretty quickly. Normally, you can only run the calculator once (which is annoying – we’re going to set up an infinite loop in a little bit to make our calculator more useful), but if you try to divide by zero, an exception gets thrown, which doesn’t look very good:

Divide by 0 Error Image

On the bright side, your program didn’t crash!

To provide a nicer-looking error, we’re going to throw our own exception. But how do we know when to do that? Introducing the if statement – a more useful version of the switch statement. Don’t get me wrong. The switch statement has its place (it runs faster than an if statement), but when it comes to really complicated logic or where there are only a few options, the if statement is just plain better.

In the Divide method (the only place where we’ll have issues) we’re going to use an if statement to make the exception message look like any other message.

static int Divide(int num1, int num2)
{
    if (num2 == 0)
    {
        throw new Exception("The quotient is: Infinity (Cannot divide by 0)");
    }
    else
    {
        return num1 / num2;
    }
}

There three parts to an if statement. The first is “if”. It is the first condition to be checked; if whatever is between the parentheses is true, then the code will run. The second (not used here) is else if. Else if statements are just like if statements except they are not checked first. They are checked in order from top to bottom. If none of the other conditions are true, the else statement executes.

The == operator in C# compares two things to determine if they are equal. Do not use = to determine equality! I’ll say that again. Do not use = to determine equality! Using = to determine equality will assign your variable and will always return true or false, which isn’t what you want.

The throw new Exception(“”) statement throws an exception that will be caught by our try…catch block. Normally, tossing exceptions around like this is a bad idea, but for the sake of this tutorial, we can get away with it.

There’s only one thing left: moving Main(args) out of the catch statement so that it is only inside the Main method at the end. This will create an infinite loop that will let users use your calculator as long as they want. They will just have to use the X button to exit. It’s far more convenient. That’s it!

Finished Calculator Image

I’m not very good at using this thing, but it does math.

Here’s the finished source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Hello_World
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int number1;
                int number2;
 
                Console.WriteLine("Enter a number, then hit enter:");
                number1 = int.Parse(Console.ReadLine());
                Console.WriteLine("Enter another number, then hit enter:");
                number2 = int.Parse(Console.ReadLine());
                Console.WriteLine("Which operation do you want? (Choose +, -, * or /, then hit enter):");
                switch (Console.ReadLine())
                {
                    case "+":
                        {
                            int sum = Add(number1, number2);
                            Console.WriteLine("The sum is: " + sum.ToString());
                            break;
                        }
                    case "-":
                        {
                            int difference = Subtract(number1, number2);
                            Console.WriteLine("The difference is: " + difference.ToString());
                            break;
                        }
                    case "*":
                        {
                            int product = Multiply(number1, number2);
                            Console.WriteLine("The product is: " + product.ToString());
                            break;
                        }
                    case "/":
                        {
                            int quotient = Divide(number1, number2);
                            Console.WriteLine("The quotient is: " + quotient.ToString());
                            break;
                        }
                    default:
                        {
                            Console.WriteLine("You did not enter a valid operator.");
                            break;
                        }
                }
 
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);  
            }
            Main(args);
        }
 
        static int Add(int num1, int num2)
        {
            return num1 + num2;
        }
 
        static int Subtract(int num1, int num2)
        {
            return num1 - num2;
        }
 
        static int Multiply(int num1, int num2)
        {
            return num1 * num2;
        }
 
        static int Divide(int num1, int num2)
        {
            if (num2 == 0)
            {
                throw new Exception("The quotient is: Infinity (Cannot divide by 0)");
            }
            else
            {
                return num1 / num2;
            }
        }
    }
}

For homework, use comments to label what everything here is doing, just so we’re clear. By the way, this program is a full 91 lines of code! Our programs are getting more complicated!

Keep up the good work!