Archive for January 2012

WPF Localization at run-time

I needed a better WPF Localization solution and I came up with one and posted it over on my WPF blog.

I would love some feed back, so if you are interested, check it out.

How to change language at run-time in WPF with loadable Resource Dictionaries and DynamicResource Binding (Example 1)

C# Dictionary

In C# there is an object called Dictionary<TKey, TValue> that can be used to store data.  The Dictionary<TKey, TValue> is essentially a collection of KeyValuePair<TKey, TValue> objects.

C# Dictionary Example 1 – A word dictionary

In this example, we create a simple dictionary with a few words and there definitions and show you how they are accessed.

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

namespace DictionaryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<String, String> words = new Dictionary<string, string>();
            words.Add("Hello", "An expression or gesture of greeting.");
            words.Add("Goodbye", "A concluding remark or gesture at parting.");
            words.Add("Computer", "A programmable usually electronic device that can store, retrieve, and process data.");
            words.Add("Friend", "One attached to another by affection or esteem");

            Console.WriteLine("Word - Definition");
            Console.WriteLine("===================================================");
            foreach (KeyValuePair<string, string> pair in words)
            {
                Console.WriteLine(string.Format("{0} - {1}", pair.Key, pair.Value));
            }
        }
    }
}

Accessing values in a C# Dictionary

You can access the value using the key. In the case of our word dictionary, the word is the key and the definition is the value.

While you could access the value as follows, there is a problem with the below method.

    private string GetDefinition(String inWord, Dictionary<String, String> inDictionary)
    {
        return inDictionary[inWord];
    }

Do you know what the problem is?  Right, it doesn’t handle a missing value.  If the value doesn’t exist, this will throw a KeyNotFoundException.

Handling a missing value in a C# Dictionary

There are two ways to prevent the KeyNotFoundException.

Method 1 – Use TryGetValue()

TryGetValue() return a bool It takes in the Key and also an out reference. It populates the out reference. Here is an example.

    private string GetDefinition(String inWord, Dictionary<String, String> inDictionary)
    {
        string retVal;
        // String is set to null if the value is not found
        return inDictionary.TryGetValue(inWord, out retVal) ? retVal : ;
    }

I am not a big fan of how the TryGetValue() function was implemented to return a bool However, I understand why it was implemented to return a bool. One might wonder why it returns bool. You may be thinking that TryGetValue() could return a value if found, null otherwise, right? Wrong! Reason 1 – Don’t forget that the value might actually be null. Reason 2 – While this Dictionary used a nullable type, string, another implementation might implement using a type that is not nullable, such as int.

Method 2 – Using ContainsKey()

Alternately you could check if the value exists first using ContainsKey(). Here is an example.

    private string GetDefinition(String inWord, Dictionary<String, String> inDictionary)
    {
        return inDictionary.ContainsKey(inWord) ? inDictionary[inWord] : string.Empty;
    }

I prefer this because to me, it is more readable than the TryGetValue() function, but feel free to make your own opinion.

Looping through a C# Dictionary

Now imagine you wanted to get all the words and their definitions that start with a certain letter. In this case you are creating a Dictionary that is a subset of the full Dictionary. You could do this with a foreach loop. Notice that the object in the foreach loop is a KeyValuePair.

        private Dictionary<String,String> GetWordsAndDefinitionsWhereWordsStartWith(Dictionary<String, String> inDictionary, char inChar)
        {
            Dictionary<String, String> wordsAndDefinitionsWhereWordsStartWithC = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> pair in inDictionary)
            {
                if (pair.Value.StartsWith(inChar.ToString(), StringComparison.CurrentCultureIgnoreCase))
                    wordsAndDefinitionsWhereWordsStartWithC.Add(pair.Key, pair.Value);
            }
            return wordsAndDefinitionsWhereWordsStartWithC;
        }

You could alternately use LINQ against the C# Dictionary to get the method body to be a single line.

    private Dictionary<String,String> GetWordsAndDefinitionsWhereWordsStartWith(Dictionary<String, String> inDictionary, char inChar)
    {
        return inDictionary.Where(pair => pair.Value.StartsWith(inChar.ToString(), StringComparison.CurrentCultureIgnoreCase)).ToDictionary(pair => pair.Key, pair => pair.Value);
    }

You could just get the words and not the definitions in a List<String> as well.

    private List<String> GetWordstartingWith(Dictionary<String, String> inDictionary, char inChar)
    {
        List<String> wordsStartingWith = new List<String>();
        foreach (KeyValuePair<string, string> pair in inDictionary)
        {
            if (pair.Value.StartsWith(inChar.ToString(), StringComparison.CurrentCultureIgnoreCase))
                wordsStartingWith.Add(pair.Key);
        }
        return wordsStartingWith;
    }

Again, you could use LINQ against the C# Dictionary to make this function one line.

    private List<String> GetWordstartingWith(Dictionary<String, String> inDictionary, char inChar)
    {
        return (from pair in inDictionary where pair.Value.StartsWith(inChar.ToString(), StringComparison.CurrentCultureIgnoreCase) select pair.Key).ToList();
    }

References

How to add a corner banner to your web page?

Today I noticed that a few sites, including WordPress.com have a corner banner on their pages to help alert others to a specific cause (in this case they are against SOPA & PIPA).

And so everyone can add a corner banner to their sites, I am going to post how to do it.

Step 1 – Create the image

There are dozens of ways to create the images and if you can create it yourself, just do so.

Note: While I for this cause WordPress would care if you used their image, I thought it best to make my own if for no other reason than to use my color style.

  1. Using your favorite image editor create a new image.
    Note: I am going to use the free Paint.NET program.
  2. Change the canvase size to be a square. Use a size between 150×150 to 200×200. I went with 175×175.
  3. Make the background transparent.
  4. Draw a line from corner 0,0 to corner 175,175.
    Note: In some applications, holding down shift while drawing your line will guarantee the line is a perfect 45 degree diagonal.
  5. Draw a second line from  60,0 to about 175,115.
    Note: Mine came out to 175,114, which is close enough.
  6. Fill the  area inside the lines as you desire.
    Note: I used a nice soft gradient.
  7.  In a new layer (also transparent), add text in a normal horizontal way.
  8. Rotate only the new layer 45 degrees. (-45.00 degree.)
  9. Show both layers.
  10. Move the text to the appropriate place in the image.
  11. Save as a png or jpg file.
  12. Upload the image to your site.

Here is my image. Feel free to download it and use it.

Stop Censorship

Step 2 – Change your web site code to display the image

  1. Add the following style to your css file.
    #right-corner {
    	position: fixed; /* Make sure you can align it exactly */
    	cursor: pointer; /* Change the cursor on mouse over */
    	top: 0px; /* Change to 100px to put it under a 100px banner */
    	right: 0px; /* Change to 100px to put it left of a 100px right-side bar */
    	z-index: 99999; /* make sure it is the top element always */
    }
    

    Note: If you do not have a css file, then go to step two and add this as well in step 2.

    <style>
    #right-corner {
    	position: fixed; /* Make sure you can align it exactly */
    	cursor: pointer; /* Change the cursor on mouse over */
    	top: 0px; /* Change to 100px to put it under a 100px banner */
    	right: 0px; /* Change to 100px to put it left of a 100px right-side bar */
    	z-index: 99999; /* make sure it is the top element always */
    }
    </style>
    
  2. Open whatever html or script file that create the top part of your web site.
    Note: Often it is a top.htm, header.htm, or something similar.
  3. Find your <body> tag and add a link to http://americancensorship.org anywhere inside the <body> tag.
  4. For the tag, set the “id” to the css id called right-corner.
  5. Put your image inside the link.The code should look as follows:
    <a id="right-corner" href="http://americancensorship.org/" target="_blank">
    	<img src="/wp-content/uploads/2012/01/Stop-Censorship.png" alt="Stop Censorship">
    </a>
    
  6. Save your changes.
  7. Refresh your page.

You now have a corner banner image on your page.


While I want to add a corner banner to my site and state that I am against SOPA and PIPA as well, here is my disclaimer:

I haven’t fully read the SOPA & PIPA document, so I am against it based on hearsay…but it is reliable hearsay. Also there may be statement in the document that I am for. Instead of telling you what I am against in the SOPA & PIPA document, it is easier just to write my thoughts.

  1. The U.S. Government should not censor the internet for the public in any way.
  2. The government should in no way tamper with or hinder the freedom of speech on the internet
  3. Certain organizations, such as parents at home, schools, or a business (except ISPs) may censor/filter the internet for their specific internet connection. (And hence anyone only using their internet access is also censored).
  4. The Government may censor the internet in locations they naturally control, such as in Government Buildings, military facilities, or government-paid-for schools.
  5. An ISP may provide an optional censorship/filtering service so long as it is not applied by default or when not specifically requested. If the ISPs whole business plan is based on the idea of a safe internet for families, such as MStar, then defaulting to enabling certain censorship/filtering service is allowed.
  6. Internet Registrars may enforce rules that make filtering easier, like having all porn sites end in .xxx or all gambling sites end in .gmb so they can easily be filtered, especially in homes, schools, and some work places.  But enforcement should be done by agreement of internet registrars and not really by the U.S. Government.
  7. The government should pursue theft of intellectual property the same on the internet as is does with theft of intellectual property off the internet with one stipulation: Only the most minimal part of a site should altered. For example, if a site posts a copyrighted movie, only the movie itself should be removed, every other part of the site should remain, including a broken link to the movie.

If the bill could be written with those few sentences, it would pass easily and I don’t think anyone would care.

How to install MySQL on FreeBSD

Note: Tested on FreeBSD 9

Step 1 – Install FreeBSD

  1. First install FreeBSD. Instructions for installing FreeBSD is contained in this article.
    How I install FreeBSD 9?
    (Legacy) How I install FreeBSD?
  2. Second update FreeBSD and install the ports tree. Instructions for this are in this article.
    What are the first commands I run after installing FreeBSD?

Step 2 – Installing MySQL

Install MySQL from Ports

  1. Change to the directory of the mysql55-server port.
    # cd /usr/ports/databases/mysql55-server
  2. Now install mysql55-server with ‘make install’.
    # make install

    MySQL 5.5 Server (and MySQL 5.5 client) will download, compile, and install automagically for you.

    Note: You may be wondering about the WITH_CHARSET option that used to exist. This is not necessary during compile and install and we will set the character set in a later step. Don’t start the MySQL service until we make these changes.

Installing MySQL from Packages

  1. Install easily as a binary package with this simple command.
    pkg_add -r mysql55-server

Step 3 – Configure MySQL

Configuration of MySQL is done in the my.cnf file.

Example 1 – Configuring mysql to use UTF8

For this example, we will change our server to use UTF8.

  1. Change to the /usr/local/etc/ directory. This is the default location for the my.cnf file.
    cd /usr/local/etc/
  2. Add the following to the my.cnf file.
    # # # > /usr/local/etc/my.cnf echo '[mysqld]' >> /usr/local/etc/my.cnf echo character-set-server=utf8 >> /usr/local/etc/my.cnf echo collation-server=utf8_general_ci

Note: FreeBSD has multiple example my.cnf files here: /usr/local/share/

  • my-huge.cnf
  • my-innodb-heavy-4G.cnf
  • my-large.cnf
  • my-medium.cnf
  • my-small.cnf

Step 4 – Configure MySQL to start on boot

  1. Add the following lines to the /etc/rc.conf file.
    #
    #
    echo # MySQL 5.5 Server >> /etc/rc.conf
    echo 'mysql_enable="YES"' >> /etc/rc.conf
  2. Now start your server.
    # /usr/local/etc/rc.d/mysql-server start

Step 5 – Secure your MySQL installation

MySQL documentation covers this and I’ll not repeat it here. Instead, go here:
2.2 Securing the Initial MySQL Accounts

Integration with Apache and PHP

If you want to integrate Apache and PHP see these articles.

How to install FreeBSD 9?

FreeBSD 9 comes with a new installer and installing it is quite fast.

Part 1 – Download the media

Step 1 – Download the DVD ISO

  1. Go to http://www.freebsd.org/where.html and click to the ISO link for FreeBSD 9 for you architecture. (x86, amd64, etc…)
  2. Click to download the FreeBSD-9.0-RELEASE-amd64-dvd1.iso.

Step 2 – Burn the ISO to a DVD

I am not going to give you steps for burning an ISO, as you could be on Windows, Linux, OS X, and you could be using any of the DVD burning tools out there.

I’ll give you this hint though…Do not burn the ISO file onto the disk as a file.

Note: Skip this step if you are installing to  a virtual machine.

Part 2 – Install FreeBSD

Step 1 – Boot off the DVD

  1. Put the DVD in your drive. (Or if using a virtual machine, point the virtual machine’s DVD drive to the ISO file.)
  2. Boot your system.
    Note: If you system doesn’t boot off the DVD check the BIOS settings or try pressing F12 to select the boot device

  3. The next screen will automatically boot but delays 9 seconds.
    Press enter to continue without waiting.


    Your now booting to the installer.

Step 2 – Install FreeBSD

  1. Click Install on the first screen.

  2. If you need a special keyboard layout, click yes, otherwise, click no. I clicked no.
  3. Enter the host name for this new installation.
  4. Select the optional system components and press enter.

  5. Partitioning can be done for you with Guided or you can do it yourself with Manual.Note: With todays hard drives, there is little to no benefit from having  multiple partitions as there was in the past. Just use Guided and the root partition will fill the drive.Note: Doesn’t look like we have ZFS options yet.

  6. Look over the guided partition settings.
  7. Click Commit to perform the installation.

    It runs the checksum verification to make sure media is valid.


    It then commits the install.

    It is actually not that long of a wait before you are pretty much done.

    The installation has committed. You will now be asked post-installation configuration questions.

Step 3 – Configure Post-installation settings

  1. Enter a password for the root account when prompted. Enter it again to verify it.
  2. Select your network card.
  3. Unless you know for sure you are going to use IPv6 only, say Yes to enabling IPv4.
  4. Unless you have been given a specific IP address to use, say Yes to enabling DHCP.
  5. Lately I like to enable IPv6 because all my operating systems now support it. But you probably don’t need it unless you know you need it.
  6. If you enabled IPv6, you probably want this option, unless you have a specific IPv6 address you need to use.

    Your dynamic network settings are determined.
  7. Your DNS setting may be detected for you, but if not, you can enter your DNS settings manually. I only entered a single DNS entry for IPv4.
  8. Unless you have a server that needs its clocked synchronized to UTC, select No when prompted.
  9. Select your time Region.
  10. Select your Country.
    Note: United States is number 49.
  11. Select your Time Zone.
  12. You may get a prompt to very whether the Time Zone you selected is correct. Select Yes if it is correct.
  13. Choose what to install.
    Note: If you are on a laptop you consider selecting powerd.
  14. If you want to contribute to FreeBSD and help them resolve bugs (especially yours) select yes. Otherwise, select No.
  15. Select Yes when prompted to Add user accounts.
  16. Enter a user name and follow the prompts.


    Note: Don’t forget to invite the user to the wheel group if they are going su to root.
  17. Enter Yes when all the settings are correct.
  18. Select Yes if you want to add more users and repeat these steps. Once you are done adding users, select No.
  19. Press Enter to Exit.
  20. I don’t have any special settings to make, so I select No here.
  21. Go ahead an press Enter to reboot.

    Important! Do not boot of the DVD again!

    Your system will now boot and create an SSH key on its own and give you a login prompt.


    FreeBSD is now installed.

Part 3 – Configure Your FreeBSD Install as Desired

What do you want to do next?

Why a developer’s next computer should be an Apple

It is not because OS X is better

Let me start by saying that I do not fall into the “my os is better than yours” mantra. I like to talk about the right tool for the job.

  • For a home user, Windows 7 and OS X still beat Linux (yes, even Ubuntu).
  • For a geeky home user, Ubuntu or any other OS might be more fun.
  • If you want to give away your old computer but not give away your Operating System license, put Ubuntu or PC-BSD on it.
  • Similarly if you get a free computer without an OS and you don’t want to buy one, put Ubuntu or PC-BSD on it.
  • For most businesses, Windows 7 is the better solution for a lot of reasons, many of which are IT related and not even user related.
  • For an artist, OS X is the right choice. Sure Windows has caught up in graphic tools, but not in peer knowledge.
  • For a Web Server, I would never run windows or MAC, I would recommend BSD or Linux.
  • For a NAS server, I would use FreeNAS.
  • For an enterprise to sell a secure appliance I would recommend a BSD derivative.

Those are just a generalizations based on the idea of using the right tool for the job. In every case others have different opinions and there are always exceptions. The appropriate thought is that you should use the right tool for the job.
So if you are a developer, what is the right tool for the job? Here is my new generalization.

  • For a Developer, I now recommend Apple hardware.

Notice I said Apple Hardware, but I didn’t say that I recommend OS X. Run whatever OS you need.

It is not because Apple Hardware is better

Also, this has nothing to do with saying that Apple hardware is better. Dell, HP, Lenovo, Sony, and others all make some great hardware for running whatever OS you can run.

Many argue that Alienware makes the best hardware, not any of the above vendors.  It is not about the best hardware.  So if it was a hardware issue, I would be recommending Alienware. But it is not.

Let me repeat.

  • For a Developer, I now recommend Macintosh hardware.

Notice, I qualified this by saying For a developer. I am not telling everybody to get Apple hardware.

Answer #1: It is simply a licensing issue

Legally you cannot run OS X on any hardware other than Apple hardware (an no Hacintosh is not legal) . Since iOS development realistically can only happen on OS X, you cannot legally run iOS on hardware designed for windows either.

Answer #2 – The cross-platform world

You need every Operating System today.

Lets talk about where development has taken us.  We have gone from not really cross-platform (Windows only and sometimes support Macintosh too), to having to be able to code on Windows, Windows Phone 7, OS X, iOS, Android, and possibly Linux and Unix as well.

Lets list these in a table and you will see why buying an Apple Laptop frees you to develop on all those platforms.

Operating System Apple Hardware Windows Hardware
Windows Run OS and Develop for it Run OS and Develop for it
BSD/Linux Run OS and Develop for it Run OS and Develop for it
Android Emulate OS and Develop for it Emulate OS and Develop for it
OS X Run OS and Develop for it Not supported*
iOS Emulate OS and Develop for it Not supported*

* While it can be done it is illegal and breaks license agreements.

Only Apple hardware allows you to install on all the popular Operating Systems that exist today.

So Apple has put themselves in an interesting position where cross-platform development on all popular operating systems can only occur on Apple hardware. It is this position that has me making this statement.

  • For a Developer, I now recommend Macintosh hardware.

As for the operating system that I recommend, you probably have guessed from this post my recommendation: If you are a developer, run them all.