Category Archives: C#

Whoops.

I know I haven’t posted for far too long. It’s really embarrassing, especially since I now aspire to be an admissions blogger at MIT.

Wait, what?

Yeah. I committed to MIT. I’m going to be a Beaver (or maybe an Engineer or an IHTFPer or whatever), and I couldn’t be happier! So now that the college admissions process is done until I (hopefully don’t have to) apply to grad school, what am I up to? Moreover, what have I been up to for the past month and a half? Why haven’t I been blogging?

I could post myriad excuses, and depending on how the rest of this blog post goes, I very well might. However, for the time being, I think it would be more appropriate if I directed your attention to Hawgrade!

Hi, Hawgrade!

Hi, Hawgrade! What the heck are you, anyway?

You can actually see the live version of this website at www.hawgrade.com. Now, to answer the caption’s snarky question, Hawgrade is grading for the Twenty First Century, developed with the help of one of the social studies teachers at my school, Dave Hawley. Mr. Hawley also goes by Hawley, hence the name Hawgrade. The website will eventually join forces with an iPad app, and the two will offer the following functionality:

  • Easy, paperless submitting of student papers.
  • Grading that stores data remotely. Teachers can keep their students’ papers anywhere!
  • Corrections for the most common student mistakes built in. This makes grading most papers as simple as highlighting passages and pressing a few buttons.
  • Recording voice comments to end the time consuming process of actually writing comments on students’ work.
  • Returning students’ corrected papers over email.

Most of that functionality has been implemented by now. It’s a wonderful culmination to my high school career, although it is unfortunate that I (a second semester senior) actually have to work on something! It’s also an enormous project. Maybe I’ll post some of my secret, proprietary code samples on this blog.

Regardless, I’ll definitely start posting more!

Drawing the Mandelbrot Fractal in C#

I suppose you could say I had a deprived coding childhood; I already wrote about how I never calculated pi and now I am about to tell you that until this afternoon, I had never drawn the Mandelbrot set. I don’t know why I never took the time to do so, but as with the pi calculator, when I decided to plot the Mandelbrot set, I found a very interesting coding challenge waiting for me.

The first step in the process was to fix the notoriously slow Bitmap.SetPixel() method. I haven’t decompiled System.Drawing to look at .NET’s implementation but I assume it involves some sort of Marshal.Copy()ing of unmanaged bitmap data to a managed byte array, modifications to pixels in the managed byte array, and recopying the array to unmanaged memory. That’s well and good for setting three pixels. We’re going to render Mandelbrot sets of an arbitrary size; 2800×1600 is about 4.5 million pixels. Bitmap.SetPixel() would make this process way, way longer than necessary.

I created a class with a readable, writable bitmap as well as a method to set any of its pixels using unsafe code.

public class FastBitmap
{
    public FastBitmap(int width, int height)
    {
        this.Bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
    }
 
    public unsafe void SetPixel(int x, int y, Color color)
    {
        BitmapData data = this.Bitmap.LockBits(new Rectangle(0, 0, this.Bitmap.Width, this.Bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
        IntPtr scan0 = data.Scan0;
 
        byte* imagePointer = (byte*)scan0.ToPointer(); // Pointer to first pixel of image
        int offset = (y * data.Stride) + (3 * x); // 3x because we have 24bits/px = 3bytes/px
        byte* px = (imagePointer + offset); // pointer to the pixel we want
        px[0] = color.B; // Red component
        px[1] = color.G; // Green component
        px[2] = color.R; // Blue component
 
        this.Bitmap.UnlockBits(data); // Set the data again
    }
 
    public Bitmap Bitmap
    {
        get;
        set;
    }
}

This class isn’t very useful outside of this program; it would need some modifications to use pixel formats other than 24bpp RGB. However, it gets the job done! The SetPixel method is what makes this class useful. It locks the provided Bitmap’s pixels, then gets a pointer to where the first color byte of the first pixel is in memory (Scan0.ToPointer()). It then figures out what the offset is to the pixel we want to modify. Finally, it creates a pointer to the pixel we want. It sets the blue, green and red to the specified color’s blue, green and red, then finally unlocks the bitmap data. When the data gets unlocked, it is saved in memory.

The SetPixel method presented here does not provide tremendous performance. It does, however, let you work with a bitmap fast enough that you won’t get bored. Most Mandelbrot rendering time is in calculations, anyway.

Now that we have an image class, we can get down to the math. The Mandelbrot fractal is based on the following formula:

Where C is the starting point on the complex plane and the starting value is zero.

Where C is the starting point on the complex plane and the starting value is zero.

The formula is given a starting value, C, that lies somewhere in the complex plane. If the formula (using C) does not tend to infinity, then C is part of the Mandelbrot set. If C tends to infinity, it is part of the Mandelbrot set. As a quick programmatic note, if the absolute value of Z sub N (the value of the formula after N iterations) ever becomes greater than two, the formula will tend to infinity.

Knowing that, we can start coming up with some pseudo-code:

for x on the screen:
  for y on the screen:
    scale (x, y) to the complex plane to figure out where we are
    c = where we are on the screen
    z = 0 + 0i
    b = a bitmap
    for i = 0 to however many iterations:
      z = z^2 + c
      if |z| > 2:
        plot (x, y) on b as some color that indicates how much "infinite tendency" there is at C
        break

If you read the Wikipedia article about rendering the Mandelbrot set, you will notice that it uses two real numbers to accomplish the same thing as one complex one. C# has a complex number class, which we will use in our code. However, before we talk about the actual rendering, we need a color palette. The members of the Mandelbrot set will be rendered black (or actually, based on the flow of the pseudo-code, not rendered at all), while the rest of the set will be rendered some color based on how many iterations it takes for the absolute value of Z to eclipse two. The more iterations it takes, the whiter the pixel. The fewer iterations, the bluer the pixel. It all comes together in the following (very simple) method:

public static List<Color> GenerateColorPalette()
{
    List<Color> retVal = new List<Color>();
    for (int i = 0; i <= 255; i++)
    {
        retVal.Add(Color.FromArgb(255, i, i, 255));
    }
    return retVal;
}

Okay, we can finally translate the pseudo-code into a real Mandelbrot-rendering method:

public static Bitmap DrawMandelbrot(int width, int height, double rMin, double rMax, double iMin, double iMax)
{
    List<Color> Palette = GenerateColorPalette();
    FastBitmap img = new FastBitmap(width, height); // Bitmap to contain the set
 
    double rScale = (Math.Abs(rMin) + Math.Abs(rMax)) / width; // Amount to move each pixel in the real numbers
    double iScale = (Math.Abs(iMin) + Math.Abs(iMax)) / height; // Amount to move each pixel in the imaginary numbers
 
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            Complex c = new Complex(x * rScale + rMin, y * iScale + iMin); // Scaled complex number
            Complex z = c;
            for (int i = 0; i < Palette.Count; i++) // 255 iterations with the method we already wrote
            {
                if (z.Magnitude >= 2.0)
                {
                    img.SetPixel(x, y, Palette[i]); // Set the pixel if the magnitude is greater than two
                    break; // We're done with this loop
                }
                else
                {
                    z = c + Complex.Pow(z, 2); // Z = Zlast^2 + C
                }
            }
        }
    }
 
    return img.Bitmap;
}

Some notable points about this method:

  1. The rScale and iScale variables represent the change in real or imaginary value in the complex plane of each pixel on the screen.
  2. Some good parameters to pass to this method are rMin = -2.5, rMax = 1.0, iMin = -1.0 and iMax (no copyright infringement intended!) = 1.0.
  3. This method could be significantly improved on multi-core machines by dividing up the x-values to render and running a thread on each core. However, any rendering would have to be done after all the threads finished to avoid any cross-thread bit-locking issues. Luckily, the part that takes a while is the iterating, not the rendering.

That’s all it takes to draw a pretty good-looking Mandelbrot fractal. Here’s a fairly large one that you can give to your math teacher. I promise it will make him or her proud. I’m totally giving one to my math team coach as a New Year’s present.

Very blue...

Very blue…

It serves!

Writing a Working Web Server in Under 100 Lines of Code

UPDATE 12/30/12: You must run the compiled executable as an administrator on systems with UAC. Otherwise, the program will crash and exit.

I was reading some coding blogs last night and I happened across a guy who had written a minuscule web server in C# over his lunch break. I knew right away that I had to have one, too. A server like this one serves little practical purpose; it does not support any sort of server-side scripting (though adding a BASIC interpreter to it would be extremely cool). It does, however, serve a wide variety of documents (and will detect their MIME type prior to serving them.

The first thing I did was write a Log method to make console output look fancy:

static void Log(string message)
{
    Console.WriteLine("[{0}]: {1}", DateTime.Now, message);
}

That was quick. Next was to create an actual server method, which would continuously loop and be started asynchronously by the Main() method.

static void RunServer(int port)
{
    HttpListener listener = new HttpListener();
    listener.Prefixes.Add(string.Format("http://+:{0}/", port)); // Where to listen
    listener.Start(); // Fire up the server
    while (true)
    {
        HttpListenerContext context = listener.GetContext(); // Get a connection
        Log("Requested: " + context.Request.Url);
 
        if (context.Request.RawUrl.EndsWith("/")) // Just asking for index; redirect
        {
            context.Response.StatusCode = 301;
            context.Response.StatusDescription = "301 Moved Permanently";
            context.Response.RedirectLocation = context.Request.RawUrl + "index.html"; // Just send browser to index.html
            context.Response.Close();
            Log("Redirected client to /index.html.");
        }
        else
        {
            byte[] retVal;
            try
            {
                retVal = File.ReadAllBytes("www" + context.Request.RawUrl); // Give the client the requested page
            }
            catch
            {
                context.Response.StatusCode = 404; // File not found; tell the client.
                context.Response.StatusDescription = "404 Not Found";
                Log("404: " + context.Request.RawUrl);
                context.Response.Close();
                continue;
            }
            string mime = GetMimeType(context.Request.RawUrl);
            context.Response.Headers.Add(HttpResponseHeader.ContentType, mime); // Give response a MIME type
 
            Stream respStream = context.Response.OutputStream; // Response stream we'll write to
            respStream.Write(retVal, 0, retVal.Length);
 
            context.Response.StatusCode = 200;
            context.Response.StatusDescription = "200 OK"; // Let client know stuff is okay
 
            respStream.Close();
            context.Response.Close();
            Log("Served: " + context.Request.RawUrl + " as " + mime + ".");
        }
    }
}

There’s quite a bit going on here; I’ll try to explain it all. The beginning of this method configures an HttpListener to wait for connections and starts it. It then starts an infinite loop (the user can stop the server by closing the console window) of continuously waiting for and serving requests (listener.GetContext() blocks until something makes a request). A client can ask for three things in this simple server (since we’re not running server-side scripts):

  1. A page that exists (e.g. /index.html)
  2. A page that doesn’t exist (e.g. __++++_____-sdasfash1234.abcdf)
  3. A directory root that may or may not exist (e.g. /mysite/)

The first thing we check for is the directory root case. We check the URL to see if it ends in a slash. If it does, we redirect the client to whatever the path is, plus “index.html.” We could simply serve the “index.html” off the bat, but we’re (poorly) code golfing right now! That would take more code and accomplish essentially the same thing!

If the RawUrl does not end in a slash, we’re serving a page! Anyway, the server stores all its files in a “www” folder that lives in the same directory as the executable. Fetching “www” plus the raw path with File.ReadAllBytes gets the data of the file we are looking for. The try statement is used in the event we can’t find the file. If an exception does get raised, the server returns a “404 File Not Found” error to the client. If this server were fancy, it would also serve a 404 error page.

If the server can find the file, it determines the MIME type through a simplistic process I will detail in a moment, sets the MIME type in the header, writes the data to the client stream, gives the client a “200 OK” (I am not sure if the order matters for all this, or if all the data simply gets flushed when the HttpResponse gets closed, but this code worked fine in Chrome and IE 9), and closes the connection.

The last thing is to determine the MIME type of the file. Rather than using WIN32 interop calls, I decided to write a simplistic method of my own based on the file extension being served.

static string GetMimeType(string fileName)
{
    // Fast way of determining if the lowercase file name ends with something
    Func<string, bool> fendw = new Func<string, bool>(inp => fileName.ToLower().EndsWith(inp));
 
    // Use our function to figure out the mime type
    if (fendw(".htm") || fendw(".html")) return "text/html";
    else if (fendw(".ico")) return "image/vnd.microsoft.icon";
    else if (fendw(".png")) return "image/png";
    else if (fendw(".jpg") || fendw(".jpeg")) return "image/jpeg";
    else if (fendw(".gif")) return "image/gif";
    else if (fendw(".js")) return "text/javascript";
    else if (fendw(".css")) return "text/css";
    else return "application/octet-stream";
}

This method wouldn’t be very interesting were it not for the Lambda Expression (remember those things I love?). The Lambda Expression takes as a string as an argument and returns a Boolean of whether the lowercase version of the provided file name ends with the specified text. In other words, it checks to see if the file has whatever extension you pass to it and ignores case. The “fendw” name, although cryptic, is short for “file ends with;” it prevented me from having to type fileName.ToLower().EndsWith(…) over and over again!

That’s it. The web server works — we just need to add a Main() method:

static void Main(string[] args)
{
    Console.WriteLine("On what port should the server run?:");
    int port = int.Parse(Console.ReadLine());
 
    Task server = new Task(() => RunServer(port)); // Start the server async
    server.Start();
    Log("Server started on port " + port.ToString() + ". Close this window to stop it.");
 
    while (!server.IsCompleted) ; // Wait infinitely
}

The first part of this method gets the port the user wants to run the server on. I used 2013, since it’s almost New Year’s! Next, it creates an asynchronous task (using a Lambda Expression again!) to run the server on, then fires it up and blocks indefinitely. The use of the Lambda expression is unnecessary here (since the thread Main() runs on will just loop forever), but if you wanted to listen on more ports, you could create more tasks to run new instances of the server on. It makes the code more extensible, right?

It serves!

It serves!

Serving a real web page from a website I built for a charity organization last year!

Serving a real web page from a website I built for a charity organization last year!

If you desired, you could actually open a port in your router and let your friends connect to your cool new server. I should probably warn you that doing so would be a terribly risky idea, even if you only have the port open for a short while. You wouldn’t run through wolf-infested woods with a steak or swim at the Great Barrier Reef with a gaping leg wound for ten minutes, so why would you do the same on the Internet? In other words: this code is provided “AS-IS” with no express or implied warranty, especially since I do not really know how secure this server is. My guess is that it isn’t. Still, it’s hard to go wrong with a 100-line server!

Calculating Pi

One programming task that I had never taken on (up until this morning, anyway), was a pi calculator. Finding pi is not an overwhelmingly daunting task; one can get an extremely precise approximation from the System.Math.PI constant. However, that’s no fun. The real fun is in rolling your own pi calculator. As it turns out, this was no beginner project. It was math-heavy, theory-heavy and CPU-heavy. Oh, and it was a blast!

The trouble was that at first, I had no idea where to begin. In C#, there is no “arbitrary precision” decimal type; the decimal class can hold 28 or so significant figures (remember the calculator tutorial?). No self-respecting pi calculator would ever stop at 28 significant figures. 28,000 would be a bit better! The first challenge in coding the pi calculator would be coming up with a way to store an unlimited number of significant figures. I’d read about some pi calculator authors implementing “BigFraction” or “BigRational” classes based off of the fairly new BigInteger (arbitrarily-sized .NET integer) class, so I thought I’d take a crack at writing one of those. I also decided that before I wrote a single line of code, I needed to choose a pi calculation formula.

The requirements for a formula are simple: that it converges relatively quickly and requires relatively few calculations per iteration. Unfortunately, the use of a “BigRational” class adds another requirement: no fractional powers of numbers that have irrational fractional powers. That’s a real drag, because it means we can’t use the Chudnovsky Algorithm, which is the Holy Grail of fast pi calculation algorithms:

The trouble is with the 3k + 3/2 part; 640320 is not a perfect square (it is almost 800.2^2, but not quite).

The trouble is with the 3k + 3/2 part; 640320 is not a perfect square (it is almost 800.2^2, but not quite).

With the really good algorithm out of the way, I started trying to find another good algorithm. My first thought took me back to my trig identity days a few years ago (okay, the past three years of high school):

So then if you take the deriv... actually, no.

So then if you take the derivat… actually, no.

This is actually a sound, correct thought. In fact it has a name: the Gregory-Leibniz formula. This will eventually converge to pi. However, after following a link off the handy, dandy Wikipedia page I used to decide which algorithm I would use in my program, I learned that it takes five billion iterations of arctan(1) (which I will get to in a moment) to produce ten correct digits of pi. YIKES! It was a good thought.

Anyway, I eventually decided on the original Machin formula, from 1706:

Although it was created in 1706, Wikipedia says it is still one of the fastest-converging pi-calculation algorithms!

Despite its age, it converges quickly and is relatively easy to compute.

Awesome. We have a formula. Now we need to figure out how an arctangent can be computed. It is actually rather simple, especially with programmatic help:

See. Not that bad.

See. Not that bad.

Alright! We have the formula for computing pi and we have the formula for computing arctangent, so now we’re done. Not so fast. Remember when I mentioned the BigRational class? As it turns out, writing a BigRational class is the bulk of this project. I won’t bore you with too many tiny details of the way I implemented it; I will tell you that it was designed for simplicity over speed. It definitely needs some refining, but it works.

The basic concept behind the BigRational class is simple: it is a fraction. It has a numerator and a denominator. The numerator and denominator are arbitrarily-precise, so the entire ratio is arbitrarily-precise. The class has a bunch of methods to help the numerator and denominator do their fraction-y duty:

As it turns out, a lot of help.

As it turns out, a lot of help.

Most of the methods listed in the class diagram are pretty self-explanatory; I won’t go into detail here (but you can download the source code to the project at the bottom of the page). All the operators help the BigRationals play well together, and the * operator has an overload that allows “scalar” multiplication. That is, it allows multiplication by a BigInteger.

The two methods that I will delve into are the Reduce method and the ToDecimalString method. The Reduce method reduces a BigRational into its simplest form. It implements Euclid’s Algorithm, which is a means of reducing a fraction. It works in steps:

  1. The larger of the numerator and the denominator is set as the “big number.” The smaller is set as the “small number.”
  2. The program finds the remainder when the big number is divided by the small number.
  3. If the remainder is not zero, the small number becomes the big number and the remainder from step two becomes the small number.
  4. If the remainder is zero, both the numerator and denominator may be divided by the small number. At this point, the small number is the greatest common factor of the numerator and denominator.
  5. Steps 2, 3 and 4 are repeated until step four terminates with the small number equal to one. At this point, the fraction is in simplest form.

In code, the above steps look like this:

public void Reduce()
{
    // Set up big and small number
    BigInteger bigNumber, smallNumber = 0;
    if (Numerator > Denominator)
    {
        bigNumber = Numerator;
        smallNumber = Denominator;
    }
    else
    {
        bigNumber = Denominator;
        smallNumber = Numerator;
    }
 
    // Now divide a bunch of times
    while (smallNumber != 1)
    {
        // Find the remainder
        BigInteger rem = (bigNumber % smallNumber);
        if (rem != 0)
        {
            bigNumber = smallNumber; // Set up the numbers for the next iteration
            smallNumber = rem;
        }
        else
        {
            // We can divide both the numerator and denominator by the previous remainder
            Numerator /= smallNumber;
            Denominator /= smallNumber;
 
            // Re-assign bigNumber and smallNumber
            if (Numerator > Denominator)
            {
                bigNumber = Numerator;
                smallNumber = Denominator;
            }
            else
            {
                bigNumber = Denominator;
                smallNumber = Numerator;
            }
        }
    }
 
    // One last thing -- if the numerator is positive and the denominator is negative, the numerator needs to become negative and the denominator needs to become positive.
    // If they're both negative, they should both be positive
    if (Denominator < 0 && Numerator > 0 || Numerator < 0 && Denominator < 0)
    {
        Numerator = -Numerator;
        Denominator = -Denominator;
    }
}

The only change between the pseudo-code and actual implementation was the addition of the small if-statement at the bottom. I noticed that the denominator would sometimes be negative instead of the numerator being negative. That would probably throw off some calculations, so I made sure that only the numerator of the BigRational could ever be negative.

The ToDecimalString method converts a BigRational into its decimal equivalent — a handy helper when it comes to calculating pi (since it’s no fun unless it starts with 3.14159…). I considered two different implementation styles:

  1. Multiplying the entire fraction by 10^however many digits I wanted.
  2. Creating my own long division algorithm that would return a string of digits of a specified length.

Contrary to what seems sane, I chose the second method. I suppose it was partially because I had always wanted to write an actual long division algorithm, but by any means, it took some head-scratching at first. Long division isn’t something I have to do very much, so I started by doing out a few long division problems. As it turns out, there is a nice pattern. The non-decimal part of the number may be calculated in one fell swoop by using integer division. It may then be committed to a string. After that, a decimal point should be committed to the string. Then, a “new numerator” should be created. Its value is the remainder from the previous iteration multiplied by ten. The next decimal digit is equal to the “new numerator” minus the remainder when it is divided by the denominator of the fraction, all divided by the denominator of the fraction. This process can be repeated until the desired number of digits is reached.

Okay, it makes more sense in code. Wow.

public string ToDecimalString(BigInteger decimalDigits)
{
    StringBuilder rv = new StringBuilder();
    this.Reduce(); // Go as fast as possible
    BigInteger remainder = Numerator % Denominator;
 
    // Get the non-decimal part
    rv.Append(((Numerator - remainder) / Denominator).ToString() + ".");
    remainder = Numerator % Denominator;
 
    BigInteger newNum = remainder * 10;
 
    // Now get the decimal part
    for (BigInteger i = 0; i < decimalDigits; i++)
    {
        rv.Append(((newNum - (newNum % Denominator)) / Denominator).ToString()); // This literally just does long division
        newNum = (newNum % Denominator) * 10;
    }
 
    return rv.ToString();
}

The only real advantage this method presents is the lack of any string parsing. It is all basic use of a StringBuilder. Plus, it seems to work very well!

With the BigRational class done, the next step was the actual pi calculation. The first step was to implement an arctangent method, in accordance with the formula I mentioned earlier.

public static BigRational ArcTangent(BigRational input, BigInteger iterations)
{
    BigRational retVal = input;
    for (BigInteger i = 1; i < iterations; i++)
    {
        // arctan(x) = x - x^3/3 + x^5/5 ...
        // = summation(n->infinity) (-1)^(n) * x^(2n+1)/(2n+1)
        BigRational powRat = input.Pow((2 * i) + 1);
        retVal += new BigRational(powRat.Numerator * (BigInteger)Math.Pow(-1d, (double)(i)), ((2 * i) + 1) * powRat.Denominator);
        if (i % 100 == 0)
        {
            Console.WriteLine("ArcTangent {0}: {1}/{2} iterations complete.", input, i, iterations); // Status update.
        }
    }
 
    return retVal;
}

Wait. There’s a parameter called “iterations.” How do we figure out how many iterations are necessary? This page provided the answer. As it turns out…

I find it's a good idea to add twenty or so digits to the end to make sure everything is correct.

I find it’s a good idea to add twenty or so digits to the end to make sure everything is correct.

In other words…

public static BigInteger GetConversionIterations(BigInteger digits, BigRational q)
{
    return (BigInteger)((double)digits / (2 * Math.Log10((double)q.GetReciprocal())));
}

That was quick. That also finished laying the foundation for actually calculating pi. Phew. That was a lot of keystrokes.

public static BigRational GetPi(BigInteger numDigits)
{
    // pi = 16 arctan(1/5) − 4 arctan(1/239)
    BigRational oneFifth = new BigRational(1,5);
    BigRational oneTwoThirtyNine = new BigRational(1, 239);
    BigRational arcTanOneFifth = PiCalc.ArcTangent(oneFifth, PiCalc.GetConversionIterations(numDigits + 1, oneFifth)); // Start computing
    BigRational arcTanOneTwoThirtyNine = PiCalc.ArcTangent(oneTwoThirtyNine, PiCalc.GetConversionIterations(numDigits + 1, oneTwoThirtyNine));
 
    return (arcTanOneFifth * 16) - (arcTanOneTwoThirtyNine * 4);
}

This code block implements Machin’s formula as discussed above. An improved version of this program could take advantage of multi-core computing by calculating one arctangent on one thread and the other arctangent on another. More formulas should also be tested to determine which is the fastest; this program really slows down as the iteration count gets higher because the fractions get really, really, really huge. Of course, this program was never going to break any records anyway because it was written in C#. JIT-compiled, super high-level languages aren’t exactly speed demons. Then again, my Phenom II x4 (overclocked to 3.7 gHz) is also beginning to show its age. I’d be curious to see how performance compares on one of the latest-generation i7s.

Although it is sluggish, it does seem to compute pi properly. Here are the first 10,001 digits:

Although it looks like a lot of pi, it's not a lot of pi.

Although it looks like a lot of pi, it’s not a lot of pi.

So that’s it. It’s done. It works. Now it just needs to run for a few days so I can brag to my friends! The funny thing about calculating pi is how although we believe pi is completely irrational and will never end, we’ve calculated enough digits that it might as well end. If my calculations are correct, it only takes about 80 digits of pi to calculate the volume of the observable universe to the nearest cubic meter. Thus, ten thousand would calculate it to the nearest 1/10^9920 cubic meter, whatever that would be. That’s some mind-blowing precision. Imagine what a million digits would do.

Download this Project (MIT License)

I LOVE Lambda Expressions

Lambda Expressions essentially add anonymous methods (methods that are attached to a piece of code, have no name and cannot really be explicitly called) to C#. I have not used them very much in my time as a developer, partly because they are newish and partly because I have never really had a need to use them. Yesterday, I decided to do some research into them and I really liked what I saw. Using Lambda Expressions in C# code adds a real JavaScript feel. It’s like the inline, more organized beauty of JavaScript without all sorts of annoying asynchronousness (though asynchronous delegates are possible in C#).

C# and the .NET Framework have always had very slick event handling. I have heard horror stories about listeners and hundreds of lines of code in Java, but since I am not a Java developer, I cannot relay a firsthand account of just how scary it gets. I can tell you that C# event handling started out great and became even better.

For the purposes of this blog post, I made a Windows application with three buttons (aptly named button1, button2 and button3).

Lambda Expressions at Work

Hey look, a sneak preview! Yippee!

In early versions of the language, if you wanted to do something when one of the buttons got clicked, you had to attach an event handler method like this:

button1.Click += new EventHandler(button1_Click);
 
void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("You clicked button1!");
}

Granted, this is awesome, but for quick snippets to run in event handlers, it’s not a very efficient use of space. Additionally, it’s hard to keep track of your code flow because you have to scroll down from where the method is attached to see what the event handler does. I am not advocating for cluttering your methods with tons of anonymous method code. I am saying that sometimes, you just want to see what is happening in your program without looking all over the place.

That’s where a delegate method comes in:

button2.Click += delegate(object sender, EventArgs e)
{
    MessageBox.Show("You clicked button2!")
};

Whoa! That’s way better! But wait, there’s more! Enter the Lambda Expression! To use Lambda Expressions, you need to use the Lambda operator. Since λ and Λ aren’t standard keyboard characters, C# uses => (not to be confused with >=) as the lambda operator. On the left side of your expression are the parameters. They do not need to be strongly-typed (scary, I know); you only have to provide a name for each and the type is inferred. On the right side of the expression is what you want to do with the code. Ready, set…

button3.Click += (sender, e) => MessageBox.Show("You clicked button3!");

WOW! That saved a lot of code! Unfortunately, it was kind of a silly example. Let’s try a slightly more complicated, relevant one. Let’s say you wanted to return the first name in a list that started with “B”. Ordinarily, you’d use a foreach loop:

List names = new List();
names.AddRange(new string[] { "John", "Bob", "Steve", "Mike", "Bill", "Emily", "Jenny", "Morgan" });
 
foreach (string name in names)
{
    if (name.StartsWith("B"))
    {
        MessageBox.Show(name);
        break;
    }
}

That’s seven lines of code for the loop. With a Lambda Expression, you can cut that done to one:

List names = new List();
names.AddRange(new string[] { "John", "Bob", "Steve", "Mike", "Bill", "Emily", "Jenny", "Morgan" });
 
MessageBox.Show(names.First(name => name.StartsWith("B")));

Uhhh… okay. What the heck. Maybe that example is worth dissecting a little bit!

Just as before, we create a list of strings and add a bunch of names to it. Then, instead of manually looping through the list, we use a LINQ extension method. The LINQ extension will return a string (because names is a list of strings) and takes a Lambda Expression as an argument. The Lambda expression takes an argument of its own, which will be a string. It will return true if name.StartsWith(“B”) is true (note that you do not use the “return” keyword with it), and names.First will return whatever string causes the Lambda Expression to return true. Basically you end up with the first name that starts with a capital letter B, which in this case is “Bob.” Try it!

Bob Message Box

Success.

Of course, Lambda expressions have an associated type: System.Func. System.Func is a generic type; the List<string>.First method we’ve been using actually takes a parameter of the type System.Func<string, bool> where string is the parameter and bool is the return value of the Lambda Expression with which it is associated. Thus, you can actually declare Lambda expressions as variables!

Func fd = st => st.StartsWith("B"); // Declare Lambda Expression
 
MessageBox.Show(names.First(fd)); // Pass the Lambda Expression variable as an argument.
 
MessageBox.Show(fd("Steve").ToString()); // Use the Lambda Expression just like any other method (displays "False" here).

I have barely scratched the surface of Lambda Expressions in this post. You can use them asynchronously and do countless, really cool things with them with the help of LINQ. As I am hoping to get a Macbook for Christmas so I can learn Objective-C, I won’t get to use Lambda Expressions very much but I already know I am going to miss them.

If you want to learn more about Lambda Expressions, go to the MSDN page about them here or this really good StackOverflow post.

Happy expressing!

Quotebook, a Grotesquely Over-complicated Version of a Program I Wrote for a Quiz

Last week in my video game development class (which is an introductory-level course on Python 3 with some focus on games), we had a quiz. We had to talk about some things we’d learned, describe the intricate differences between Python’s if, elif and else statements, then write a program. The program intrigued me: the goal was to “simulate a fortune cookie” and display one of five different, pre-determined strings at random.

My first reaction was relief that I was going to be able to write the program with little issue. My second reaction was how incredibly far I could take that idea. An entire social network materialized in my head; a place where people could go to share and discuss quotes or fortunes. Then I realized that I was crazy, but I did decide to make some changes to the program we’d written in my spare time:

  1. Create an online component that would allow anyone to submit quotes to the “fortune cookie”. The “cookie” has become a system that I call Quotebook, for lack of a better name.
  2. Create a Python client for some kind of bare-bones Quotebook API that would accomplish the same task as the quiz program, except after retrieving the quote from Quotebook.

I knew the Python part would be the easy part, so I fired up Visual Studio and got cracking. I used most of the default template but changed the top text and removed the menu. I kept the HeadLoginView and all the other assorted login-related items so I could use the Membership class to attribute submitted quotes to a user. I also added a database to the project and created a table called quotes. Quotes has four columns:

  1. id (int)
  2. byUser (nvarchar)
  3. timestamp (timestamp)
  4. quoteText (nvarchar)

On the homepage, I added a big TextBox and a submit button. Then, I wired it up to write to the database:

protected void btnSubmitQuote_Click(object sender, EventArgs e)
{
    if (HttpContext.Current.User.Identity.IsAuthenticated) // Make sure user is authed before writing bad things to DB
    {
        // Connect to the DB
        SqlConnection sconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["messageDB"].ConnectionString);
        sconn.Open();
 
        // Create the command to insert the values into the database
        // PARAMETERS are used to STERILIZE all inputs.
        SqlCommand scomm = new SqlCommand("INSERT INTO quotes (byUser, quoteText) VALUES (@byuser, @quotetext)", sconn);
        scomm.Parameters.Add(new SqlParameter("@byuser", System.Data.SqlDbType.NVarChar));
        scomm.Parameters.Add(new SqlParameter("@quotetext", System.Data.SqlDbType.NVarChar));
        scomm.Parameters["@byuser"].Value = Membership.GetUser().UserName;
        scomm.Parameters["@quotetext"].Value = tbQuote.Text;
 
        // Commit to DB
        scomm.ExecuteNonQuery();
 
        // Close and refresh page.
        sconn.Close();
        Response.Redirect("Default.aspx");
    }
    else
    {
        lblError.Text = "
 
You must login or register before adding a quote!"; // Alert user
    }
}

There are a lot of points to cover here. First, the user state gets checked so quotes don’t get attributed to some kind of phantom (and so no exceptions get thrown!). I added a red, textless label to the area next to the submit button so that if the user isn’t logged in, he will get an error message. If he is logged in, the quote gets written to the database. I had to provide my own connection string in the web.config file. The connection string gets used to connect to the database, and a command gets created on that connection.

The command has two parameters: the text of the quote and the user’s name. Those are set through SQL parameters. Although I have no plans to SQL injection attack my own database, it is good practice to use parameters whenever user input is to be committed to a database. After the parameters get set, the data gets written and the connection gets closed.

With the input side of the Quotebook I/O taken care of, I set out to write the output. I wanted two different kinds of output: a mess of all the quotes in reverse chronological order on the homepage and the “bare-bones API” I mentioned earlier. Before I wrote either, I created an easy way to get data out of the database that I call the QuoteEnumerator class. I created a struct called Quote, which contains the quote text and the name of the quote submitter. QuoteEnumerator has a static method that returns a list of all the Quotes stored in the database. I implemented the two like this:

/// <summary>
/// Reads the DB and creates lists of quotes.
/// </summary>
public class QuoteEnumerator
{
    /// <summary>
    /// Obtains a list of quotes from the ASP.NET database.
    /// </summary>
    /// <returns></returns>
    public static List<Quote> GetQuotes()
    {
        List<Quote> retval = new List<Quote>();
 
        // Connect to DB and set up the query
        SqlConnection sconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["messageDB"].ConnectionString);
        sconn.Open();
        SqlCommand scomm = new SqlCommand("SELECT * FROM quotes", sconn);
 
        // Read the database
        SqlDataReader sdr = scomm.ExecuteReader();
        if (sdr.HasRows)
        {
            while (sdr.Read())
            {
                // Iterate through the results
                Quote q = new Quote();
                q.QuoteSubmitter = sdr["byUser"].ToString();
                q.QuoteText = sdr["quoteText"].ToString();
 
                retval.Add(q);
            }
        }
 
        return retval;
    }
}
 
/// <summary>
/// Contains a quote once it is extracted from the DB.
/// </summary>
public struct Quote
{
    public string QuoteText { get; set; }
    public string QuoteSubmitter { get; set; }
}

The QuoteEnumerator.GetQuotes() method is a relatively simplistic database reading method. It utilizes a SqlDataReader to iterate through all the rows. For each row, it retrieves the quote text and quote submitter, then adds them to a list containing all the other quotes. It returns that list. Using GetQuotes made implementing the homepage side of the output easy.

// Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
    foreach (Quote q in QuoteEnumerator.GetQuotes())
    {
        // Append the quote to the page in a pretty-looking (?) way
        lblError.Text += string.Format("<div style='display:block; padding:2px; margin:0 auto; border:1px solid black; width:80%; text-align:center;'>{0}<br/><br/><span style='font-size:smaller'>Submitted by {1}</span></div><br>", q.QuoteText.Replace("\n", "<br/>"), q.QuoteSubmitter);
    }
}

The result is, uh, kinda stunning…

Quotebook Image

That comment was sure telling the truth!


I only had two obstacles left: implementing the API and implementing the Python script that would utilize it. The API came first. I created a page called getmessage.aspx and deleted all of the code from the ASPX page except the top line indicating that it was, indeed, ASPX. In the code behind, I came up with this little gem to write a random quote as a string to the page (and to give credit to the submitter):

protected void Page_Load(object sender, EventArgs e)
{
    // Grab a random quote
    List<Quote> allQuotes = QuoteEnumerator.GetQuotes();
    Quote chosen = allQuotes[new Random().Next(0, allQuotes.Count)];
 
    // Write the quote as the response text
    Response.Write(chosen.QuoteText + "\n\nSubmitted by " + chosen.QuoteSubmitter);
}

Lastly, I created a Python script to read from the API. It uses urllib, and given my limited Python knowledge, it is more than good enough! (Keep in mind that this is Python 3; my last Python post was written in Python 2)

# randomMessage.py
# Random message downloader python script
print("Fortune Cookie")
DLURL = "http://localhost:6642/getmessage.aspx" # Replace with yours
 
import urllib.request
while input("Enter Q to quit or press ENTER to continue: ").lower() != "q":
    # Open the API page
    response = urllib.request.urlopen(DLURL)
    data = response.read().decode("utf-8") # Download and decode to a string
 
    print("\n" + data, end="\n\n")

With that, I entered some quotes and fired my creation up!

Quotebook Python Script Running

The awesome thing about Python is how incredibly easy it is to build relatively useful programs like this one.


Sure, it’s seven or eight times more code than the school version, but it’s extensible.

Do you have any improvements for this? Additional features? Let me know!

Brute Security

DISCLAIMER: I do not endorse the use of any “cracking” methods I discuss in this article for anything but educational purposes, nor do I claim to be any sort of “security expert”. Everything here is provided “as-is” with no warranty whatsoever.

With the legal jargon taken care of, let’s discuss passwords and why you have them (note the plurality – I sure hope you don’t simply have one password!). Passwords protect your information.Without them, everyone would have access to everything with only a username. Would you feel comfortable with that? I didn’t think so.

So, if the point of a password is to protect your security, then it follows that a password should be as secure as possible. What makes a secure password? I turned to Google for some advice. Here’s the jist of what I learned:

  • Length is super-important
  • Mixing uppercase letters, lowercase letters, numbers and symbols makes the best password possible

What’s groundbreaking about that? Absolutely nothing – tips for crafting great passwords have been around for as long as I have been able to read them. The problem is that great passwords are often difficult to remember. For example, AsJ*()gM,4 is ten characters long and has at least one character from each category I just mentioned. XKCD came up with a solution to the problem, though I don’t agree with simply using lowercase letters (and Google rates the example “correcthorsebatterystaple” password as “Good” rather than “Strong”). Why only strong for such a long password? Here are two common for breaking passwords:

  • Dictionary attacks are attacks using common “passwords”, usually derived from the dictionary or other common phrases. Dictionary attacks are the easiest, fastest way to break insecure passwords. Is your password “password”, “password1″, “123456″, “qwerty”, or anything else on this list of tragically bad passwords? It will be broken with a dictionary attack.
  • Brute force attacks are exactly what they sound like – they try every password combination possible. They are useful when dictionary attacks fail, because “zebra” will be cracked by a dictionary attack, but “ze6ra!” probably won’t be. They also aren’t very much work to implement but take much, much longer than a dictionary attack. How much longer? I wanted to find out.

I wrote a very, very slow brute forcer implementation in C#. I am not going to publish the source code on the blog, but I’ll give you an idea of how it works:

  •  The brute forcer is passed a string containing every character it should try, which could be something like “abcdefghijklmnopqrstuvwxyz”. It is also passed the MD5 hash of the string it is trying to break.
  • The brute forcer uses a for loop starting at zero up to the length of the trial string raised to the power of the maximum length to look for.
  • It computes the MD5 of the generated string and compares it with the one it is trying to break. If they match, it is done.
  • There are some big slowdowns – the .NET framework (which I did my best to counteract by using the “unsafe” keyword) and that I am only using one core. Sure, I have a 3.7gHz i7, but I am only using one of eight possible cores. These passwords would break much faster if I used all of them or if I had a supercomputer.

The way this brute forcer works has taught me two things just how correct that password advice is. It’s all in the math.

Longer passwords make taking passwords way longer. Let’s examine a two character password comprised of uppercase and lowercase letters. There are 52 possible first letters and 52 possible second letters, so the total number of password permutations is 52 * 52, or 52 ^ 2. It follows that the number of permutations is 52 ^ N, where N is the length of the password. Therefore, assuming every cracking iteration takes the same amount of time (around 50 microseconds on my password cracker near the beginning, which isn’t very fast), every letter you add makes cracking take 52 times as long. If you add three characters, there will be about 140,000 times as many combinations.

Special characters make password cracking take far longer as well. Think about it – if your password is comprised solely of lowercase letters, there are 26 ^ N permutations. Add the uppercase letters, and there are 52 ^ N. With the numbers 0 – 9, there are 62 ^ N. Add ~`!@#$%^&*()_-+= and there 78 ^ N.

According to my expert Windows calculator usage (in scientific mode, which the C# calculator tutorial didn’t cover), a five-character lowercase password has 11,881,376 permutations, while a five-character password that could use every symbol I have mentioned has 2,887,174,368 permutations. That’s right – the jump is from 11.8 million to 2.9 billion. In fact, you would have to use about a seven-character (well, about 6.7-character) lowercase password to match the strength of the five-character anything-possible password.

Not convinced about the huge difference? Here are some action shots with some different password lengths (all matching against the “anything-possible” string of 78 characters):

Three-Character Password

Three-character password.

Four-Character Password

Four-character password.

Five-Character Password

Five-character password. To be fair, my computer was asleep for much of that time.

So, in going from a three character password we went from less than one million iterations to success to 2.4 billion iterations to success. Imagine how long this would take with, say, an eight-character or ten-character password.

As always, there is one big concept I want you to take away from my articles. In this case, it is that adding just one symbol to your current password (even if it as simple as putting it in parentheses or putting an asterisk in front) will strengthen it immensely. Stay secure!

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!!

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!