Singleton pattern in .net and c#

I was talking to my brother earlier (also a developer, although specializing in game development) and he mentioned that he’s always had an issue implementing the singleton pattern under c#/.net, also citing that he finds it a bit tricky generally when using OO languages.

Well, here’s one way to do it. As he’s a game developer, let’s assume that we’re using the pattern to accomodate the current state of a video game.

    

class GameState
    {
        //The Single Instance
        private static GameState _singleton = new GameState();     

        //The constructor
        private GameState()
        {
            _score = 0;
        }

        //A "player score" property and member
        private int _score;
        public static int Score
        {
            get
            {
                return _singleton._score;
            }
            set
            {
                _singleton._score = value;
            }
        }
    }

Possible improvements to this would be to have a static “initializeGameState()” method and create the singleton instance in there instead. Either way, using the above method allows you to write code like this;

           
GameState.Score = GameState.Score+100;

I don’t find much use for the singleton pattern in my line of work (the web) but hopefully this’ll be of use to someone!

EDIT: Many good improvements have been suggested in the comments which can help to make this even lazier (in my example, the initialization of the singleton would happen the first time someone used any of the static methods in the code, rather than when the user perhaps intended to start)

Simple C# Screen Scraping Proxy with JQuery

Was asked today how to do a screen scrape an external site using JQuery. The short version is, you can’t do it with JQuery alone. There exist certain security measures that prevent ajax requests going out to other domains/points of origin.

You can achieve the effect in a number of ways. The most old school of these is using an iframe, but in most cases this just won’t cut it as you’ll need to be able to manipulate the returned HTML.

A better way is to code up a simple server side proxy that does the scrape, and then do your ajax postback to there instead. Here’s an example in C#…

            
using (WebClient client = new WebClient())
{
   string url = "http://www.google.com/"; 
   Byte[] requestedHTML = client.DownloadData(url);
   UTF8Encoding objUTF8 = new UTF8Encoding();       
   
   //This line just writes the string straight back to the response, but you 
   //could just as easily stick it in a string variable and manipulate it to 
   //your hearts content!                         
   Response.Write(objUTF8.GetString(requestedHTML)); 

}

Let’s say you saved that as the code behind of an otherwise blank page called “Ajax/scape.aspx”. You’d then just need to use the jquery “.load” command

$("myDiv").load("Ajax/scrape.aspx");

and you’re there! Note that the “load” command will cache by default, so if you need something more complex look up the “.ajax” command.

Project Euler Problem 4

Have decided to try and get a few of these done every week just to keep the ol’ brain alive. Here’s my working for Project Euler problem 4 in C#.

class Program
 {
 static void Main(string[] args)
 {
 int biggest = 0;

 for (int i = 100; i < 999; i++)            
   for (int j = 100; j < 999; j++)
   {
      int product = i * j;
      if (IsPalindromic(product))                      
        if (product > biggest)
          biggest = product;
   }
 
   Console.WriteLine("Done!, biggest was " + biggest);
   Console.ReadKey();

   }
 }

Where “IsPalindromic” is as follows…

        public static bool IsPalindromic(int number)
        {
            string s = number.ToString();
            int frontCounter = 0;
            int backCounter = s.Length-1;

            while (frontCounter < backCounter)
            {
                if (s[frontCounter] == s[backCounter])
                {
                    frontCounter++; backCounter--;
                    continue;
                }

                return false;
            }
            return true;
        }

brute force… but for something this trivial I don’t care 😛

Ancient Egyptian Multiplication in C#

Clocks have gone back in the UK and I can’t sleep so decided to do a little light programming to try and send me off. I’ve basically coded up an ancient Egyptian multiplication algorithm in C# using a .net Dictionary object. If you want to read up on the algorithm itself, here’s the wikipedia article.

This algorithm is also known as Egyptian multiplication, Ethiopian multiplication, Russian multiplication, or Peasant Multiplication. I did also find an implementation of this over on Rosetta Code – the one they have there is much more streamlined than what I ended up doing (they even did a linq version that I’m very jelous of!) but this one’s more readable than the recursive version they give over there so thought it was at least worth posting.

Okay then here we go: Ancient Egyptian Multiplication in C#!

using System.Collections.Generic;
using System.Linq;

        public static int AncientEgyptianMultiplication(int multiplicand1, int multiplicand2)
        {
            Dictionary<int, int> pairs = new Dictionary<int, int>();            
            pairs.Add(multiplicand1, multiplicand2);
            return performMultiplicaiton(pairs);
        }

        private static int performMultiplicaiton(Dictionary<int, int> pairs)
        {
            if ((int)pairs.Last().Key == 1)
                return pairs.Last().Value;
            else
            {
                var latestPair = pairs.Last();
                pairs.Add(latestPair.Key / 2, latestPair.Value * 2);

                if (latestPair.Key % 2 != 0)
                    return (int)latestPair.Value + performMultiplicaiton(pairs);
                else
                    return performMultiplicaiton(pairs);
            }
        }

Parsing Dates in C#

In this example: How to parse a string date into a DateTime object. If the parse doesn’t work, we want to just use todays date.

The verbose way

                DateTime date;
                try
                {
                    date = DateTime.Parse("01-03-1991");
                }
                catch
                {
                    date = DateTime.Now;
                }

Less verbose way (using tryparse)

                DateTime date;
                if (!(DateTime.TryParse("01-03-1991", out date)))
                {
                    //hits this if the string doesn't parse into a date
                    date = DateTime.Now;
                }

What not to do…

A common mistake is to do this;

                DateTime date = DateTime.Now;
                DateTime.TryParse("01-03-1991", out date);

Assuming that the “tryparse” will do nothing to the output variable if it’s not a valid parse. This is not correct – if the string does not parse into a valid date, then the output variable will be initialized to its default value (in the case of a DateTime, this would be 01/01/0000).