NUnit Project and Item Templates for Visual Studio

Here is an NUnit Project Template for Visual Studio.

  1. Download this template: NUnit Project
  2. Place this zip file into the %USERPROFILE%\Documents\Visual Studio 2010\Templates\ProjectTemplates\Visual C#.
  3. Create a new Visual Studio Project and choose NUnit Project from the list of C# projects.

Here is an NUnit Item Template for Visual Studio.

  1. Download this template: NUnit Test
  2. Place this zip file into the %USERPROFILE%\Documents\Visual Studio 2010\Templates\ItemTemplates\Visual C#.
  3. Add a new item to an NUnit Project and choose NUnit Test from the list of C# items.

My Coding Guidelines

Everyone has their own style guide and mine has just grown naturally. I didn’t used to do all of these so many of my early posts don’t follow these formats exactly, but I now very much prefer these coding styles.

Also, it annoys me to no end when someone calls there style good and another style bad. I will do no such thing. I will mark the styles as “My style” and “Not my style”. Just because it is “No my style” doesn’t mean it isn’t a good style for you.

Some basic guidelines

  • Follow the rules of grammar whenever possible.
  • Make code as self-documenting as possible.
  • Make code easy to copy and paste.

Indentation

Use four spaces tabs when tabbing. Remember this, scrolling up and down is easier than scrolling side to side.

Do not tab brackets but tab code inside brackets.

My Style

for (i = 0; i < 10; i++)
{
    DoSomething();
}

Not my style

for (i = 0; i < 10; i++)
    {
        DoSomething();
    }

Whitespace

Add spaces after commas in method parameters but don’t space around the parenthesis.
My style

public void DoSomething(string inString, bool inValue)
{
   string a = "a";
   string b = "b";
   SomeWork(a, b);
}

Not my style

public void DoSomething ( string inString, bool inValue )
{
   string a = "a";
   string b = "b";
   SomeWork( a, b );
}

No space when declaring an array.

My Style

string[] myArray = new string[] {"String1", "String2"};

Not my style

string [] myArray = new string [] {"String1", "String2"};

Curly Brackets

Always put the curly brackets on the next line. Why? Think of the brackets as left-most column. The opening bracket should be directly above the closing bracket, in the left-most column. Or think of the brackets as a section you want to isolate from everything else. The brackets (start section) should never share a line. You should be able to easily highlight all the lines in the bracketed section and not include any code outside the brackets.

My Style

for (i = 0; i < 10; i++)
{
    if (SomeBoolCheck())
    {
        DoSomething();
    }
}

Not my style

for (i = 0; i < 10; i++) {
    if (SomeBoolCheck()) {
        DoSomething();
    }
}

Again, in every instance where you use a curly bracket, put it on the next line.

if

Almost always use brackets even if it is only one line.

My Style

if (SomeBoolCheck())
{
    DoSomething();
}

Not my style

if (SomeBoolCheck())
    DoSomething();

The only time I use a one line if statement is when it really is only one line. And when I do this, I always have an empty line afterwards.

My Style

public void DoSomething(object inParam)
{
    if (inParam == null) return;

    DoSomething();
}

Not my style

public void DoSomething(object inParam)
{
    if (inParam == null)
        return;
    DoSomething();
}

Variable names

Member variables or fields

All public variables are in camel case with the first letter uppercase. I feel that having the first letter lowercase is distracting in most instances.

My style

public string FirstName;
public string LastName;

All private member variables start with an underscore and are in camel case with the first letter uppercase.

My style

private string _FirstName;
private string _LastName;

Not my style

private string _firstName;
private string _lastName;

Properties

I don’t really differentiate public or private properties, as I rarely have private properties and in the rare instances where I do, I don’t change the syntax in any way. Also, I always have a space between properties.

My style

public string FirstName {get; set;}

public string LastName {get; set;}

Always use an autoproperty unless you have at least one line of code to add to the get or set.

A Property that must have a manual backing field should have the backing field right under the property. Why, because if you think about it, it is part of the property and if you copy it (or just copy the contents on the lines with and within the brackets), the backing property should come along with the copy and paste.

My Style

public string FirstName
{
    get { return _FirstName; }
    set
    {
        _FirstName = value;
        NotifyPropertyChanged("FirstName");
    }
} private string _FirstName;

Not my style

private string _FirstName;

// .... more code

public string FirstName
{
    get { return _FirstName; }
    set
    {
        _FirstName = value;
        NotifyPropertyChanged("FirstName");
    }
}

Note: In my example, I am using a property for a ViewModel in the MVVM format. I would really prefer the following syntax. Someday, I will figure out how to do this without including 3rd party software.

[NotifyPropertyChanged]
public string FirstName {get; set;}

[NotifyPropertyChanged]
public string LastName {get; set;}

Methods

Naming

Methods should be named very clearly based on what they do. Length is not a problem due to intellisense. For example, imaging you want to have a function that eats a cookie. You would name it as follows. Also, I don’t do anything different for public verses private (or protected or internal) methods. They are all camel case with the first letter uppercase.

public void EatACookie()
{
    // ... code to eat a cookie
}

Parameters

All parameters in functions are in lowercamel case. Remember, having the first letter of a name be lowercase is distracting to me. However, I get by this by and mark the variable with the preposition “in”. In rare cases where I use a ref or an out for a parameter, I use those prepositions where “in” would be.

This also adds an additional benefit of marking the parameter variables differently than internal variables.

My style

public void EatACookie(Cookie inCookie)
{
    // ... code to eat a cookie
}

Not my style

public void EatACookie(Cookie cookie)
{
    // ... code to eat a cookie
}

Variables declared in a method

I basically just go all lowercase using the same name as the object when possible, or the most self documenting variable name as possible.

public void EatACookie(Cookie inCookie)
{
    Mouth mouth = new Mouth()
    mouth.Teeth.Chew(inCookie, 27);
    mouth.Swallow();
}

However, if the word needs camel case, I often add a short tag in front similar to method parameters only I usually use “loc” or “tmp” to mark them as local or temporary variables. Again, I use the same name as the object when possible, or the most self documenting variable name as possible.

My style

public void EatACookie(Cookie inCookie)
{
    CookieMonster tmpCookieMonster = new CookieMonster ()
    tmpCookieMonster.EatCookie(inCookie);
}

Final remarks

I am sure I have more styles I use, and I will add them as I go.


Using FreeBSD inside a controlled network – A required HTTP Proxy and No FTP

Inside a controlled network, it is a little harder to use FreeBSD. The simple things become hard, such as running “portsnap fetch extract” or running “make install” on a port.

In a certain network, I am experiencing certain security settings that I must make FreeBSD work around:

  1. An HTTP proxy is required to access external sites
  2. No FTP access.

Working with a required HTTP proxy on FreeBSD

You cannot bypass the proxy. Most ports are blocked with HTTP/HTTPS forced through the proxy. Even worse, DNS only responds for internal addresses  and the proxy handles the external sites, so your local box never actually resolves names to IP addresses and the browser only works because the proxy makes it work.

Setting a global proxy on FreeBSD

You can configure FreeBSD to use a proxy. You can set a global proxy, sort of. It looks like you can set a global proxy per shell. However, not all apps respect that proxy.

csh/tcsh

To add a global proxy to any csh or tcsh shell, add the following line to this file: /etc/csh.cshrc

setenv HTTP_PROXY http://ProxyNameOrIp:8080

sh

To add a global proxy to any sh shell, add the following lines to this file: /etc/profile

HTTP_PROXY=http://ProxyNameOrIp:8080
export HTTP_PROXY

Now that you have made these settings, your proxy should be working and any tool that uses HTTP/HTTPS, such as fetch, portsnap, make fetch, etc., should now properly use the proxy to access the internet.

fetch and tools that use it (ports, portsnap, etc…)

Any HTTP source should now work. Both ports and portsnap and other such FreeBSD tools use fetch so as soon as the environment variable is set, fetch and any tool that uses it will work.

Tools that don’t use fetch (Subversion, etc…)

Other tools, such as subversion, may not support the HTTP_PROXY environment variable and must be manually configured. For Subversion, I couldn’t find a global setting, instead it was a user setting. The file in your home directory. It usually exists by default but contains only comments. The following is the minimal lines you need.

[global]
http-proxy-host = ProxyNameOrIP
http-proxy-port = 8080

Working with no FTP access on FreeBSD

This problem is easy to get around. Always use HTTP or HTTPS. FreeBSD has usually made it that simple as all the common tools that use FTP seem to have HTTP options as well.

Ports

Most ports have an HTTP site as a backup download location. The best case, you run make install and it just finds an HTTP site and downloads the port for you. In the worst case, you may have to manually edit the Makefile and add an http source.

Portsnap uses http by default.


Decoupling settings from /etc/rc.conf in FreeBSD

The rc.conf file can have a lot of settings that quite important. In fact, I would say it has so many settings that it often gets very bloated. Have you ever made a huge mistake and wiped out the rc.conf when it is huge and full of many settings. Or have you ever had a system crash that wiped out the rc.conf? I have! A large rc.conf can be difficult to recover without a backup. On a production server, I will have such a backup but in my lab and on my PC-BSD desktop, I don’t.

My personal experiences of erasing the rc.conf are silly but they happened. Feel free to laugh but I have been using FreeBSD since 2001 (11 years as of the writing of this post) and each of these happened in lab environments or on my personal laptop where I was less careful and none of them ever happened on a production server.

  1. I accidentally ran a command that wiped it because I used > which overwrites the file, instead of >>, which appends to the file.
    $ sudo echo ‘someapp_enable=”yes”‘ > /etc/rc.conf
  2. PC-BSD wireless settings are written to the /etc/rc.conf file and once while managing my wireless settings, the system crashed, rebooted, and my /etc/rc.conf was empty.
  3. I once was going to delete the hosts file and add a new one and I am so used to typing /etc/rc.conf that I typed that instead of /etc/hosts. Oops!
    $ rm -f /etc/rc.conf
  4. While writing a script to update a setting in /etc/rc.conf, my script wiped it. Maybe the reason was similar to #1, maybe it was different, I don’t remember.

How to store settings in separate files on FreeBSD

If you do a quick read of the man 5 rc.conf, it will tell you that you can put setting in rc.conf, rc.conf.local, or in any filename residing in a folder called /etc/rc.conf.d and all these files can store settings.

Moving all your settings to rc.conf.local just moves the problem I described above, it doesn’t actually fix it, so I am not going to use that solution. However, using a separate file per setting in the /etc/rc.conf.d directory is quite a great idea.

Step 1 – Create the /etc/rc.conf.d directory

  1. Create a /etc/rc.conf.d directory:
    # sudo mkdir /etc/rc.conf.d

Step 2 – Create a file to hold a setting

Example 1 – Hostname

  1. Create a file in /etc/rc.conf.d and name it hostname.
  2. Add the hostname=”SystemName.domain.tld” setting to the file.

Note: You can do both steps at the same time with one command:

# sudo echo ‘hostname=”SystemName.domain.tld”‘ > /etc/rc.conf.d/hostname

Example 2 – SSH

  1. Create a file in /etc/rc.conf.d and name it ssh.
  2. Add the sshd_enable=”YES” setting to the file.

Note: You can do both steps at the same time with one command:

# sudo echo ‘sshd_enable=”YES””‘ > /etc/rc.conf.d/ssh

Example 3 – Default Gateway

Yes, on FreeBSD the default route setting is called defaultrouter, not gateway or defaultroute as one would expect.

  1. Create a file in /etc/rc.conf.d and name it defaultrouter, or if you want to name it gateway or defaultroute.
  2. Add the defaultrouter=”192.168.0.1″ setting to the file.

Note: You can do both steps at the same time with one command:

# sudo echo ‘defaultrouter=”192.168.0.1″‘ > /etc/rc.conf.d/defaultroute

Conclusion

If you use the /etc/rc.conf.d file, then if you ever accidentally overwrite a file, it is not that hard to deal with because every setting is decoupled in its own file. You only lose one setting.

From now on, in my posts, I will tell likely suggest adding settings using a separate file in /etc/rc.conf.d.


MSVCR100.dll Download or MSVCP100.dll Download

In a previous post, Avoiding the MSVCR100.dll, MSVCP100D.dll, or MSVCR100D.dll is missing error, I explain what the MSVCR100.dll is and how to solve problems with it.

Many have asked for an MSVCR100.dll download. Turns out that Visual Studio has a redistributable folder that contains these dlls. So I zipped it up and I am redistributing it.

Here it is:

Download MSVCR100.dll and MSVCP100.dll


Monitoring the uptime of your blog

So my blog was down and I didn’t know. The mysql server and CPanel were down, actually.

I decided I should set up a monitoring service so I set out to find one.

I found this article:

http://mashable.com/2010/04/09/free-uptime-monitoring/

This was the first one on the list and it will monitor up to 50 sites for free  every 5 minutes and try to send you email or texts if your site is down.

http://www.uptimerobot.com

Google pulled this site up and while it only monitors one site for free and only at 30 or 60 minute intervals, it seems to have some statistics for you.

http://www.siteuptime.com/

 


Developer Training Tracking Checklist

This is to cover development related training, (so no Human Resources (HR) training is listed here).

Why training does not occur

The industry is full of companies that do not invest in training for their developers. There are many reasons training does occur and for every company these reasons may be slightly different.  Here are some that seem prevalent.

  1. There is an assumption that developers do not need training.
  2. They assume developers train themselves.
  3. They cannot afford training.
  4. They haven’t even thought about it.

Of course, many software development companies provide excellent training, so this article may not apply to them.

Why you should train your developers

Training is extremely important and this article exists so that if you are in a software company that is failing to train your developers, your development department can take steps to improve this.

To make correct decisions

Many software development companies fail in many areas. Training will not guarantee success in these failed areas, but it will increase your odds of success significantly. Often developers are treated as experts and analysts for tools and processes to perform their jobs. Developers often get to choose their source control tool, 3rd party libraries, the branching strategy, and more. Unfortunately, most developers are not trained System Analysts so they do not actually have an expertise in how to locate multiple products that feel a need, research which is best, and choose the one that is best for the company. Instead, the choice is often made because it is the first tool or process the developer found or already knew about that works for their very narrow need at the moment.

If your developers are well-versed in a topic and know the options and the pros and cons of each option, they are more likely to make correct choices for your company.  Ask yourself and your team about your current tools and processes. Is your development department just using these tools and processes because they are the most common, or because a skilled analyst determined that process fit your business?

When you hire a new employee, or when you implement a training program among existing employees, it is difficult to know where a developer stands in regards to training. If you want to find out where a developer is at, and help them move to the next level, you need a tracking system.

To grow as a developer

You may find that developer grow at a fast rate their first few years. But then, this growth may stop. A developer’s skills may stagnate. They know enough to do their job so they don’t continue to learn.  This is a problem because new technology always comes out and new tools are released to aid in their job.

To maximize productivity

A trained developer should produce code faster and with higher quality.

Software Development is always improving and something that may take a day today, might take 30 seconds and one line of code a year from now due to either a new tool or a new library.

To improve quality

There are a lot of bugs per lines of code and training, especially on quality topics such as design patterns and unit testing, can really improve the quality of a product.

How to track a developer’s training

I designed a simple tracking system. I made a list of topics (which are by no means complete) and subtopics. I gave each sub topic three levels to show continued growth.

The following is a spreadsheet version of the simple Developer Tracking System I created.

As a Google Doc: Developer Training Tracking Checklist
As Excel: Developer Training Tracking Checklist
As Excel (inverted) Developer Training Tracking Checklist – Inverted

Basically, the items that you should train on are as follows:

Training Topic Sub Topic Level
Development Tools IDE Level 1
Level 2
Level 3
IDE Plugins Level 1
Level 2
Level 3
Other Tools Level 1
Level 2
Level 3
Your company’s product Product 1 Level 1
Level 2
Level 3
Product 2 Level 1
Level 2
Level 3
Source Management Tool (TFS, GIT, SVN) Level 1
Level 2
Level 3
Branching Strategy Level 1
Level 2
Level 3
Development Language (C++, .NET, Java, PHP, etc…) Style Guides Level 1
Level 2
Level 3
Best Practices Level 1
Level 2
Level 3
Design Patterns Level 1
Level 2
Level 3
Advanced Language Level 1
Level 2
Level 3
Language Libriaries Log4Net Level 1
Level 2
Level 3
Unity Level 1
Level 2
Level 3
Unit Test Test Framework (Nunit) Level 1
Level 2
Level 3
Unit Test Best Practices Level 1
Level 2
Level 3
Libs (SystemWrapper) Level 1
Level 2
Level 3
Localization Localization Procedure Level 1
Level 2
Level 3
Build Building Locally System Level 1
Level 2
Level 3
Nightly Build System Level 1
Level 2
Level 3
Continuous Integration Level 1
Level 2
Level 3

Here is the key:

Key or Legend

Training Topic = A broad general development topic. Example: Source Management
Sub Topic = A more specific development topic. Examples: Source Control Tool, Chosen Branching Strategy
Level 1 = Often over the shoulder training of a new hire. A basic overview that is enough to get them working. For example, what are the basics for using TFS. 1-4 hours. All level 1 trainings should be provided within the first three months or at first use. Level 1 can be marked off without training if the employee demonstrates they are already at a higher level.
Level 2 = Usually in a formal training or an online training. A more in-depth overview of the sub topic. 8+ hours. All level 2 trainings should be complete by the end of year 1. Level 2 can be marked off without training if the employee demonstrates they are already at a higher level.
Level 3 = Expert level training. This could come from combining a few trainings, such as one or more Text Books, Online Research. 24+ hours. Level 3 trainings take time. The should begin after the first year of employment (unless a job requires it occurs earlier) and one or two should be completed each quarter. If an employee thinks they are already at a level 3, they should create a portfolio of information describing why they are at level 3 and present to a peer group of four or more individuals. If at least three of the four agree, then Level 3 is passed.

Training Types

FT = Formal Training. Hopefully in a classroom by a technical trainer.
OR = Online Research. Employee reads blogs and articles about the subject and indicate the articles and blogs read.
OT = Online Training. A formal training delivered online.
TB = Text Book. A book about the subject. Indicate which book. Also, the book should be read by multiple developers who should meet every other week to discuss the topics in the book.
ST = Shoulder Training. A person trains from over the shoulder. You may want to track who provided the training.

Hopefully if you are a VP of Engineering or CTO of a development company, you can take this and implement this in your environment.


Hello, Caradigm! Goodbye, LANDesk!

Friday was my last day as an employee at LANDesk. After more than seven years, it was emotionally painful to leave. I have lots of friends and co-workers who I trust and respect that I’ll likely see once a year if ever again.

While on one side change can be sad, on the other it can be extremely exciting!

I have accepted a new position as a Lead Software Developer and start one week from today. My new company will be called Caradigm. GE Healthcare and Microsoft are coming together to form this company and each will own 50% of it. Click the image below to read more about it.

 

This is going to be a fun time working for a new IT healthcare solution.


Unit Test Best Practices and Guidelines

The following are Unit Test best practices and guidelines:

  1. Test one object or class per unit test class.
    Yes, you should refactor your code if you cannot test one class only.
  2. Name your test class after the class it tests.
    If you have a class named SomeClassY, then your test class should be named SomeClassY_Tests.
  3. Perform one test per test function.
    The test class can have as many functions as you need. Perform one test per function. That doesn’t mean one Assert call. Multiple assertions might be needed to perform one test.  Think of it this way. When a test fails, you should know exactly what failed and why just because of which test function failed.
  4. A unit test should run on the Build and Continuous Integration (CI) systems.
    Unit tests are there to help you succeed and prevent you from failing. If they run rarely, they rarely help. They should run every time you check in code and every time your build kicks off. You should be automatically notified if any code you wrote breaks an existing Unit Test.
  5. A unit test should never alter the system in any way.
    Don’t touch files, databases, registry, network, etc… A test that does so is a functional test not a Unit Test. If an object cannot be tested without touching the system, refactor the object to use an Interface (and if needed a wrapper) for interacting with the system so such can be faked, or mocked with a tool such as RhinoMocks or MOQ. This is important because if a Unit Test is running on the Build or CI system, you could actually introduce a change to the system that hides a bug and allows the bug to exist in a released product.
  6. Make the test function names self documenting.
    This means if you want to test passing in a bool to FunctionX you might call your test functions something like this:
    FunctionX_True_Test()
    FunctionX_False_Test()
    Think of it this way. When a test fails, you should know exactly what failed and why just because of the function name.
  7. Never assume 100% code coverage means 100% tested.
    For example, 100% coverage of a function that takes a string as a parameter might be 100% tested with one test. However, you may need to test passing in at least five string instances to avoid all types of bugs: expected string, unexpected string, null, empty, white space, and double-byte strings. Similarly a function that takes a bool parameter should be tested with both true and false passed in.
  8. Test in the simplest way possible.
    Don’t elaborate, don’t add extra code. Just make a valid test as small as possible. Warning! That doesn’t mean you can forget the best practices and guidelines above. For example, if the simplest way is to test everything in one function do NOT do it. Follow the best practices and guidelines.
  9. Get training and keep learning about Unit Testing.
    You won’t do it correctly without training and continued learning. It doesn’t matter if you do your own research and train yourself by reading online articles, blog posts, or books. Just get yourself trained and keep learning. There are many test frameworks, mocking frameworks, wrappers (such as System Wrapper), and encapsulation issues, and without training you may end up with Unit Tests that are not maintainable. You will find many opinions about best practices, some matter, some don’t, but you should know each side of the opinions and why those opinions exist whether you agree with them or not (this list included).

I hope this list helps you.

If you have a best practice not on this list, or you want to comment on one of the items, or even disagree, please comment.

Return to C# Unit Test Tutorial


Why Interface-based design leads to good Unit Tests?

Interface-based design leads to good Unit Tests because you can more easily have a separation of concerns, limit the test to one object, and eliminate dependencies by not having to have “real” dependencies available to test a portion of your code.

I am going to explain this by example.

First, let me remind you of some rules for writing good Unit Tests:

  1. You don’t touch the system so Unit Tests can run on a stable build device without corrupting the build system.
  2. You don’t have external dependencies so the build system can run in an isolated environment.
  3. The tests should run quickly.
  4. Each test should test one thing only.

Imagine you have code that tests authenticating to a UNC path.  You have these two classes:

  • BusinessObject
  • NetworkShare

BusinessObject contains an instance of NetworkShare.  The code is not really significant as this is theoretical. We’ll get to code in the next few articles.

You need to write Unit Tests for BusinessObject.cs.

Why is this a problem? Because it requires a system with a UNC share to run the class and so testing is difficult.

Now, imagine that BusinessObject.cs didn’t actually have an instance of NetworkShare, but instead an Interface was created called IAuthenticateRemotely. And Your code now includes these files.

  • BusinessObject
  • IAuthenticateRemotely
  • NetworkShare : IAuthenticateRemotely

Now BusinessObject has an instance of IAuthenticateRemotely instead of an instance of NetworkShare.  Now you can write Unit Tests for the BusinessObject class by simply creating any fake class in your Unit Test code that implements IAuthenticateRemotely. Your test class would simply be a fake. Lets say the IAuthenticateRemotely had a bool Authenticate() function. You would create a fake class for your test and implement this function as follows.

public bool Authenticate()
{
    return true;
}

Notice that the function doesn’t actually do anything. That is because a Unit Test for the BusinessObject class only needs to test the BusinessObject class.

Please feel free to make any comments as necessary.

Return to C# Unit Test Tutorial


Table Layouts still win over CSS layouts in 2012

The longer I am blogging and the more often I mess with my html layout (which is done in CSS) the more I come to realize that while CSS is a solution for HTML layouts but it is not a good solution and it has in my opinion completely failed to address the layout problem.

Look at any development language, GTK, QT, wxWidgets, Windows Forms, Windows Presentation Foundation, and a dozen others and they all have simple and easy to use layout systems. It is common to have Grid layouts, wrapping layouts, and more.

What does CSS2 and HTML4 have specifically for layout?

Nothing specific to layout. A div is not specific to layout. I was using what the author called Holy Grail 3 column liquid-layout. However, after two days, I still can’t change the width of my right side bar without breaking the layout in some way, which is mostly because the layers and layers of div elements is a mess in this layout.

What does CSS3 and HTML5 have specifically for layout?
They have new elements: article, aside, audio, bdo, canvas, command, datalist, details, embed, figcaption, figure, footer, header, hgroup, keygen, mark, meter, nav, output, progress, rp, rt, ruby, section, source, summary, time, video, wbr

However, while you can use HTML5 and CSS3, just be aware your website will only look good in newer browser. Please don’t try to view your site on Windows XP with IE7 or IE8.

I want the developers of Firefox, Opera, Internet Explorer, Safari, Chrome, HTML5 and CSS3 to know that when it comes to layout, YOU HAVE FAILED!!!!

If there is one reason that I wish Silverlight could become the de facto internet standard is for the simple reason that the layout features in XAML are so far superior than those of even the new HTML5 and CSS3 that there isn’t even a comparison.

So what is the solution to an easy HTML layout?

It just doesn’t get easier than the good old table layout, but you can at least style your layout with CSS.  CSS is good at styling even if it fails at layouts.

Look how easy it is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>3 Column Table Layout</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">

html, body {
  height: 100%;
}

body {
    margin:0
}

table.layout {
  height:100%;
  width: 100%;
  border-collapse:collapse;
}

tr.header {
  height:150px;
  background:black
}

tr.menu {
  height:50px;
  background:DarkGrey;
}

tr.body {
  height:100%;
}

tr.footer {
  height:150px;
  background:DarkGrey;
  height:150px;
}

td.leftcol {
  padding: 15px;
  width: 170px;
  min-width: 170px;
  background-color:Navy;
}

td.midcol {
  background-color:Grey;
  min-width: 625px; /* Make 425px for min res of 800x600 */
}

td.rightcol {
  padding: 15px;
  width: 205px;
  min-width: 205px;
  background-color:Navy;
}
</style>
</head>
<body>
<table class="layout">
<tr class="header">
<td colspan="3"></td>
</tr>
<tr class="menu">
<td colspan="3"></td>
</tr>
<tr class="body">
<td class="leftcol"></td>
<td class="midcol"></td>
<td class="rightcol"></td>
</tr>
<tr class="footer">
<td colspan="3">
  <p style="text-align: center;">
    <a href="http://validator.w3.org/check?uri=referer">
	  <img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Strict" height="31" width="88" />
    </a>
  </p>
</td>
</tr>
</table>
</body>
</html>
  1. t took less than 30 minutes to make this layout.
  2. It still uses CSS to style the layout.
  3. Changes are easy (any column can be re-sized in seconds).
  4. Left and right columns are always the same height.
  5. The background colors always extend vertically as far as needed.
  6. It is of course, W3C compliant.

Sorry CSS, until you have a real layout solution I think you lose to a good old-fashioned table.

But what about dynamically changing the layout?

Well, lets face, it. Dynamic changes are done in code anyway, and any good developer can code up that solution. Besides, most web sites are using some sort of Content Management System, like WordPress, Drupal, SilverStripe, or others. Each of these allow for Themes or Styles and so you can easily code up a way to switch styles with code such as php, asp.net, ruby, or any programming language.


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.