Archive for June 2012

A simple Log singleton in C#

Here is a simple Log singleton in C#.

Updated: 7/25/2016

using System;
using System.IO;

namespace Rhyous.Logging
{
    public class Log
    {

        #region Singleton

        private static readonly Lazy<Log> Lazy = new Lazy<Log>(() => new Log());

        public static Log Instance { get { return Lazy.Value; } }

        internal Log()
        {
            LogFileName = "Example";
            LogFileExtension = ".log";
        }

        #endregion

        public StreamWriter Writer { get; set; }

        public string LogPath
        {
            get { return _LogPath ?? (_LogPath = AppDomain.CurrentDomain.BaseDirectory); }
            set { _LogPath = value; }
        } private string _LogPath;

        public string LogFileName { get; set; }

        public string LogFileExtension { get; set; }

        public string LogFile { get { return LogFileName + LogFileExtension; } }

        public string LogFullPath { get { return Path.Combine(LogPath, LogFile); } }

        public bool LogExists { get { return File.Exists(LogFullPath); } }

        public void WriteLineToLog(string inLogMessage)
        {
            WriteToLog(inLogMessage + Environment.NewLine);
        }

        public void WriteToLog(string inLogMessage)
        {
            if (!Directory.Exists(LogPath))
            {
                Directory.CreateDirectory(LogPath);
            }
            if (Writer == null)
            {
                Writer = new StreamWriter(LogFullPath, true);
            }

            Writer.Write(inLogMessage);
            Writer.Flush();
        }

        public static void WriteLine(string inLogMessage)
        {
            Instance.WriteLineToLog(inLogMessage);
        }

        public static void Write(string inLogMessage)
        {
            Instance.WriteToLog(inLogMessage);
        }
    }
}

Note: This is not tested with multiple threads as this is a simple example.

How to effectively salt a password stored as a hash in a database

A salt is an additional sequence of data (bits or characters, however you want to think about it) that is appended to a password before hashing the password and storing the hash in a database.

There are three types of salts that can be added to a password. Assume the password is passwd! and the salt is 12345, here are the three types described in a table.

Salt Type Salted Password SHA256 hash
unsalted passwd! 12f225551a043b6e136b2cf03546b06efb289d29ab42cebfd78ee101d8555304
Prefix 12345passwd! b38c49760d484119f227fab640cb1415d58f765c0727dc9ad7e0a5a66003d041
Infix pass12345wd! a9fa7c693b691c8ceded848877afdb1259f28f194863ebb33c07c4bbfa1ff04c
Postfix passwd!12345 1315abea2576c3b6270712df587359d614ae1a1698d69dd2175459e411f678f5

Of course you can use multiple of these in any combination as well. You can surround the password by using both a prefix and a postfix. You can use all three. You can have multiple infixes, so a password of 12 characters such as MyPassword1! could become MyP12345assw12345ord1!.

Reasons for salting

Salting was created because hashing is imperfect. Hashing has multiple problems. However, I am only going to describe two problems and how salting improves the security in each situation.

Problem 1 – Rainbow tables

A database of hashes for all character sequences up to a certain number of characters can be generated over time. This database is called a rainbow table.

Scenario

Let say you registered at site ABCStore.tld. Some time later, ABCStore.tld reports that their database was compromised.  Your password was not stored in the database, but the hash of your password was. Lets say your password was passwd! and you use it on every site on the internet.

With a rainbow table, your password will be discovered in moments and that password will work on other sites perfectly.

How a Rainbow table works

It works by generating a table of passwords and their matching hashes. As each character is added to a password, the total possible password options increases, making the next number of passwords hard to generate. For an English keyboard, there are 26 upper case letters, A-Z, 26 lower case letters, a-z. There are ten numbers, 0-9. There are 33 special characters, 34 if you include tab.  There are other characters available, but the majority of people who speak English, those are the only characters used in a password. That is 95 possible options for a password (96 if you include a tab).

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 0
  ~ ` ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' " , < . > / ?

So for every character in length the password is, the possible values grow exponentially.

Password Length Possible combinations
6 96^6 782,757,789,696
7 96^7 75,144,747,810,816
8 96^8 7,213,895,789,838,336
9 96^9 692,533,995,824,480,256
10 96^10 66,483,263,599,150,104,576
11 96^11 6,382,393,305,518,410,039,296
12 96^12 612,709,757,329,767,363,772,416

However, it is actually easier than this. Most passwords are dictionary words, so a Rainbow table can be created with dictionary words first. Now a large portion of passwords are covered.

Then because most passwords are lowercase characters only, a hacker can have their rainbow table created by first creating only the options using all lowercase letters. Notices the numbers are significantly smaller.

Password Length Possible combinations
6 26^6 308,915,776
7 26^7 8,031,810,176
8 26^8 208,827,064,576
9 26^9 5,429,503,678,976
10 26^10 141,167,095,653,376
11 26^11 36,703,444,86,987,776
12 26^12 95,428,956,661,682,176

Also it is common to only put numbers on the end of a password, so they can then do all lowercase passwords with one number at the end, then two numbers at the end. It is also to common to replace letters with number, E = 3, l or i = 1, S = 5, etc. It is also common to only capitalize the first letter, so that can be done too. So as you can see, by doing far less than generating all passwords, a rainbow table can be created that matches almost all passwords used.

Password Creation Hint: When creating your own password, avoid these trends and use long passwords. If it is allowed, use a sentence with punctuation as a password if you can such as this:

I love my wife, Michelle!

Sentence passwords are easy to remember, easy to type, and are freaking hard to populate into a rainbow table. The above sentence is 25 characters. Each space, the comma, and the ! are special characters, that is 6 special characters. There are two capital letters, one not just at the front.

So once such a rainbow table is created, if your password is easy, your password is just a select statement away from a hacker who compromises a database.

Select * from RainbowTable where hash=?

The hacker now knows your actual password  and can use that on other websites, like your bank account. You scared now? You should be!

How a salt improves security against a Rainbow table

Remember our scenario. How is that scenario less of a security concern because salting was used? The answer is fairly simple. Because salting changes the string being hashed, the hash is different. So a look-up in a Rainbow table will be less likely to return a result. The probability is high that even if a simple password was used, the rainbow table will not return a result. If a result is returned, the likelihood that the returned string is a collision not your password was increased.

Note: If the salt is known, or can be figured out, obtaining your password is still possible, but it is harder and will take longer.  If you change your passwords often enough, you only need the building of the Rainbow table to take longer than the time you use your password.

Problem 2 – Collisions

Another problem with hashing is that there is a possibility, however remote, that two completely different strings return the same hash.

Scenario

You register using the same username and password at both ABCStore.tld and XYZStore.tld. Two sites don’t use a salt, but they both hash your password with the same hashing algorithm. ABCStore.tld reports that their database was compromised.  Your password was not returned, but a collisions was returned.

Even though it is not your password, the collision string can be used to authenticate at XYZStore.tld also.

How a collision occurs

Because a hash is limited in the amount of characters it generates, but there are an infinite amount of character sequences, it stands to reason that infinite is greater than anything finite, once all hashes are used, the next hash created from a unique sequence will be a duplicate.

(Read this: What’s the shortest pair of strings that causes an MD5 collision?)

Lets make the numbers ridiculously small so you can understand easier. Imagine a hash that changes everything to a single digit number, 0-9. Once all ten hashes are used, the eleventh hash created is guaranteed to be a duplicate.

With SHA-256, the rules still applies, only there are a plenty of unique hashes, so collisions are extremely hard to calculate, even for multiple computers over a long period of time (at least today in June, 2012).

How salting improves security against collisions

If we look at our scenario where a hacker was able to determine a collision for the password used, not the password itself, they may not even have the salt string.

Well, if salting were used by both ABCStore.tld and XYZStore.tld, and both used different salts, then the collision that worked for ABCStore.tld doesn’t work from XYZStore.tld because they used different salts, and therefore the passwords aren’t the same. So that means that the hackers have to calculate your actual password, which is harder to calculate.

Even better, the hacker wouldn’t even be able to log into to ABCStore.tld because the login system will append the salt to the entered password, so having a collision doesn’t help, because after entering the password, the collision gets the different salt appended to it and it is no longer the same and is not a collision on another system.

Less-effective salt implementation

Salting works. However, it is often implemented in a way that is less-effective. Remember, “less-effective” is still somewhat effective. Let’s look at some less-effective uses of salting.

Using a single salt for all passwords

Look at the following table of passwords. Can you easily tell which is the salt and which is the password?

123456789passwd!
123456789myPass12
123456789littleJohn
123456789jennifer
123456789secret100

The salt is 12345679. Now because the salt is known, a hacker can now create a rainbow table using the salt.

This is “less effective” because it is still somewhat effective. This method is just not as effective as it could be.

According to scenario 1, it is effective because the standard rainbow table will not return a result. The hacker is now forced to create a new rainbow table. However, it is less effective because the hacker only has to create one more Rainbow table, and they can probably get all passwords with a partial rainbow table.

According to scenario 2, finding a collision will not allow authentication to another site with a different salt or a site without a salt. However, because the hacker knows the salt, they can find a collision from which they can remove the salt, and that leaves them with a collision string that works on ABCStore.com.

Using a static hash resource in the code

If a static hash is in the code, it is possible that this value can obtained from a binary or by compromising the code itself. Storing the hash in the code is effective as if the database is compromised, the hash was not in it.

It is somewhat effective in that the hacker now has to figure out the hash on their own. It is less-effective in that the code could be what was compromised.

Publishing the salt in the database

Since a single salt is “less effective” the author of an authentication system may decide to use a separate salt for each user. However, now he has so many salts, he needs to track them somewhere. The salt becomes a column, usually next to the password column, and usually the column is clearly titled: “Salt”.

According to scenario 1, this is still “effective” in that now a hacker must generate a Rainbow table for each user. Why is it still less effective? Because the salt is known, and only one password per Rainbow table is needed, a complete rainbow table is not needed. As soon as a string is found matching the hash, that Rainbow table can be abandoned. A dictionary designed to try high probability passwords first can significantly limit the time needed to find the average person’s passwords, which are usually simple and common dictionary words or names. Most passwords can be determined in a short amount of time. The time is of course based on resources. Of course, with cloud services, resources are cheap and powerful.

Using an existing user value as a salt

Instead of using a column called “Salt’, an existing known column, such as the username, first name, or last name is used. Of course, you wouldn’t use the actual value in the known column, it is probably too short. You would use a hash of the first name or a cryptographically random character sequence added to the value in the known column.

This is effective in that the hacker has to figure out which column is used as the salt. It is less effective because the hacker only has to do this on the first user and once the column is determined, for the rest of the users it is the same as publishing the salt in the database.

More effective implementations

One of the main failures of salting is the common idea that the salt is not secret. A secret or calculated salt increases security.

Salts should be unique per user and they should be hard and as close to impossible to figure out.  Here are some ways that a hacker may never figure out the salt, and never be able to create a Rainbow table using it. Something that provides the security as close to that of a one-time pad as possible.

Use a variably located calculated salt

There is not one salt, there are one or more salts. The salts don’t exist in the code, nor do the exist in the database. However, it is a combination of both. And the salt is not always a prefix, infix, or postfix, or any combination of the three, however, the number of salts and the location(s) are determined by one or more calculations.

There are seven possible salt combinations, however, because the infix could have multiple locations as well, the salt locations could be many more.

  1. prefix
  2. infix
  3. postfix
  4. surround (prefix and postfix)
  5. prefix and infix
  6. infix and postfix
  7. all (prefix, infix, and postfix)

When there is an infix, it could be multiple infixes every n* characters where n could even be calculated so a 16 character password could have 1-15 infixes.

The number of salts and their locations and where they go could be determined with a calculation as simple as this:

SaltLocations = Firstname % 7

Of course a more complex method could be used as well. Again, the number of infixes could be calculated. Each salt location should then have a separate salt and each salt should be created using a separate calculation. Also, make sure both the code and the database are used for the calculations. Even a simple algorithm makes life harder on the hacker. Go ahead and create a column called salt in the database, however, only store a random character sequence there.

Salt (database part) = First letter of first name + random character sequence + first letter of last name

This can be made even more complex by altering this using a function.

Salt (code part) = function(First two letters of first name + random character sequence + first two letters of last name)

Even if the function in code is a simple shift one bit function, the hacker will not know the function and will have difficulty figuring it out. Even if they figure out one salt, will they be able to figure out the number of salts, what each salt is, and where each salt is used.

This is more effective because the hacker will have to compromise both the database and code to figure out each salt and often the database and the code are stored on separate servers.

Use a variably located calculated salt including information outside the database and the code

No matter how many algorithms you use or how complex they are, if the hacker has the code and the database, they usually have the salt. What if you could change that? So what if having the code and the database is not enough.

External File

What if the code was obtained and the database was obtained but on inspection of the code, a file on the system, located nowhere near the code, held a value that was part of the hash. Now that file has to be accessed too. This file could be anywhere. On the same server, or on a separate server. It could be accessible by different credentials.

Salt = function(First two letters of first name + random character sequence + first two letters of last name + GetInfoFromFile())

Web Service

What if the calculations were performed on a separate server entirely using a web service and lets assume the web service is secure.

hash = Remote_function(password, First two letters of first name + random character sequence + first two letters of last name + GetInfoFromWebService())

The web service could also determines where to place the hash, in any of the seven ways mentioned, so compromising the local code no longer benefits the hacker.

However, adding a third server is costly and more complex and adds additional need for security. For example, if you don’t add security and the hacker gets the database and code, they could simply call the same web service. Adding security such as ‘source IP address of the calling server’ would be effective.

Now the database, the code, and the third-party server all have to be compromised by the hacker for them to determine your salt and then your password or a collision of your password.

Hashing your hash a calculated amount of times

Ok, so if you do everything above, you can still make life even harder for a hacker by hashing  your hash a number of times.

long RoundCount = CalculateRoundCount();
hash = hash(saltprefix + password)
for (long i = 0; i < RoundCount; i++)
hash = hash(hash)

Since we calculate the RoundCount so that every user in the database was hashed a different amount of times, it is difficult for the attacker to know how many hashes were run and so they have to try them all.

Kerckhoffs’s principle

Kerckhoffs’s principle states that a cryptosystem should still be secure even if everything about the system, except the key, is public knowledge.

This principle is abused by some security engineers in multiple ways:

  1. they assume that only one key can or should exist.
  2. they apply Kerckhoffs’s principle, which is for a single cryptographic action, to an entire multi-part software system.
  3. they claim that a security measure is useless if that security measure relies on another part of the system being secret.

So is a calculated hash security by obscurity? Yes an no. This is security by multiple secrets. Security by multiple secrets is not necessarily the same as security by obscurity. Security by obscurity provides the idea that the code could be riddled with vulnerabilities but because the code isn’t known, it doesn’t matter, it is secure by being unknown. If you don’t know the hash, can you create valid rainbow table? No, you have to create the entire table and move to brute force. So it is security by making the hash a secret. Does it improve the hashing algorithm as a single cryptographic action? No. Does it require the attacker to build a bigger database of hashes? Yes. Does it make it more likely the hash they match with is a collision and not the user’s actually password? Yes.

Look, if the whole system were known, that would include the key or secret. Kerckhoffs’s principle explicit states that everything but the key or secret is known. His statement is true. It is best if that is the case. But that doesn’t mean security can’t be better for any given situation where that is not the case.

The best way to check if you are making your system more secure, is very similar to how you define features for a product: in stories. Barneck’s Security Story Principle (Barneck is me 😉 states this: Any security increase is valid if the security increase is for a hacker story that is valid.

So let’s look at some stories. Is security increased by making the salt secret?

Story Security Measure Taken Security is increased for story
A hacker gets access to only the database data. The salt is secret in the code. Yes
A hacker gets access to the database and the code. The salt is secret in the code. No
A hacker gets access to the only the database data. The salt is secret and not in the database or code. Yes
A hacker gets access to the database and the code. The salt is secret and not in the database or code. Yes

If the salt is a secret, and the algorithm that calculates the salt uses a secret so the salt can’t be recalculated, then the system is more secure than it would be if the Salt were known. Even if the system is open source, if the open source software was written so the algorithm that creates the hash uses a secret that is generated by the user and is different for every install and not static in the source, then the attacker must first discover the secret to the salt before they can begin to use a rainbow table to find a collision.

There is a belief that cryptography should involve as few secrets as possible. However, one single secret is also a problem. What if that one secret is discovered. Shouldn’t the redundancy principle apply to secrets? Isn’t there a backup secret so discovering one secret is never enough? We inherently know that multiple keys and doors work better than one key and door. This is why we create games that have mazes where we have to find one key before we can find another.

Think of it as an arms race. Making the salt secret might not make your hashing algorithm any stronger. But does it have to? Isn’t it enough to make it harder for the hacker to make a rainbow table? Since a hacker is using a rainbow table, isn’t it valid to respond by attacking their ability to make a rainbow table? Yes it is. Time is a very important dimension in security and any measure taken that significantly increases the time required to hack a system is valid.

Now, as an exercise for you, what if the following calculations were done using separate secrets stored in separate places?

  • Hash
  • Hash location(s) – prefix, postfix, infix, or multiple
  • Number of hash rounds

How does having separate secrets improve your system’s security? What administration concerns does it create?

Conclusion

Salting is effective. Even when a salt is implemented in a less effective manner, it is still better than having no salt at all.

Typically the salt is considered “not secret” but I argue that a hacker who compromises a database, the code, or both, should still have difficulty determining the salt or how the the salt is added to a password as that information allows for an easier creation of a rainbow table.

Implementing salting in these more effective ways can increase complexity, making it unlikely a hacker could reverse engineer a password using the hash or find and use a collision.

AOP – Implementing a lazy loading property in C# with PostSharp

When developing in C#, you may have an object that contain properties that need to be initialized before they can be used. Think of a List<String> property. If you forget to initialize it, you are going to a NullReferenceException error. The List can be initialized as part of the constructor to solve this exception. However, maybe the List isn’t always used and you only want to load it if it needs to be used. So many people create a property that initializes iteself on first use. While this is not a bad idea, in C# it results in one line of code becoming at least six lines of code because you have to break out the auto property.

Here is the one line version verses the six line version (I can make it five lines if I put the private variable on the same line as the last bracket, which is a syntax I like with full properties).

List AddressLines { get; set; }
public List AddressLines
{
    get { return _AddressLines; }
    set { _AddressLines = value; }
}
private List<String> _AddressLines;

Wouldn’t it be nice if we could do this by only added single line of code, in this case an attribute? It can be that easy. Creating an instance on first use, or lazy loading, is a cross-cutting concern and can be extracted to an aspect using PostSharp. This article is going to show you how to do this.

It is assumed you have the following already installed and licensed:

  1. Visual Studio
  2. PostSharp

Step 1 – Create your Visual Studio Project

So to show you how this works, let’s get started.

  1. Create a sample Console Application project in Visual Studio.
  2. Add a reference to PostSharp.

Step 2 – Create an example class with properties

Ok, so let’s go ahead and create an example class called Address.

  1. Right-click on your project and choose Add | Class.
  2. Give the class file a name.
    I named this class Address.cs.
  3. Click OK.
  4. Add properties needed to store and address.
    Here my Address class working.
using System;
using System.Collections.Generic;

namespace ExampleAspects
{
    public class Address
    {
        public List AddressLines
        {
            get { return _AddressLines; }
            set { _AddressLines = value; }
        } private List<String> _AddressLines;

        public String City { get; set; }

        public String State { get; set; }

        public String Country { get; set; }

        public String ZipCode { get; set; }
    }
}

So our goal is to use Aspect-oriented programming to extract the lazy load something like this:

[LazyLoadAspect]
public List AddressLines { get; set; }

For me this is much clearer and more readable than the full property. Let’s make this happen in the next step.

Step 3 – Create the LazyLoadAspect

Ok, so let’s go ahead and create an example class called Address.

  1. Right-click on your project and choose Add | Class.
  2. Give the class file a name.
    I named this aspect class LazyLoadAspect.cs. Another good name might be InstantiateOnFirstUse or something.
  3. Make the class inherit from LocationInterceptionAspect.
  4. Override the OnGetValue method.
  5. Write code to get the value, check if it is null, and if null instantiate and set the value.
  6. Add a Type property that takes a type and implement that type if it is set, just in case you want to initialize using a child class. Otherwise how would you implement an interface.
using System;
using PostSharp.Aspects;

namespace Rhyous.ServiceManager.Aspects
{
    [Serializable]
    public class LazyLoadAspect : LocationInterceptionAspect
    {
        public Type Type { get; set; }

        public override void OnGetValue(LocationInterceptionArgs args)
        {
            args.ProceedGetValue();
            if (args.Value == null)
            {
                args.Value = Activator.CreateInstance(Type ?? args.Location.PropertyInfo.PropertyType);
                args.ProceedSetValue();
            }
        }
    }
}

Note: You may have a factory for creating your objects and you could replace the Activator.CreateInstance method with your factory method.

As discussed, replace the full property with this:

[LazyLoadAspect]
public List AddressLines { get; set; }

Step 4 – Prove your LazyLoadAspect works

Give it a try by creating an instance of Address in the Main method of Program.cs.

using System;
using Common.Aspects;
using PostSharp.Aspects;

namespace AspectExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            Address address = new Address();
            // NullReferenceException would occur here without the LazyLoadAspect
            address.AddressLines.Add("To: John Doe");
            address.AddressLines.Add("100 N 100 E");
            address.AddressLines.Add("Building 12 Floor 5 Suite 530");
            address.City = "SomeCity";
            address.State = "Utah";
            address.Country = "USA";
        }
    }
}

Well, you are done.

Please take time to look at how the code actually ended up using ILSpy or .NET Reflector.

Return to Aspected Oriented Programming – Examples

AOP – Implementing try catch in C# with PostSharp

I’ll be honest, I always cringe whenever I have to use try/catch. I do everything I can to avoid it. Besides being a resource hog, try/catch statements clutter code making it harder to read. So naturally I was excited when learning about Aspect-oriented programming (AOP) and PostSharp (the AOP library for C#) that try/catch statements are cross-cutting concerns and can be implemented as aspects.

It is assumed you have the following already installed and licensed:

  1. Visual Studio
  2. PostSharp

Step 1 – Create your Visual Studio Project

So to show you how this works, lets get started.

  1. Create a sample Console Application project in Visual Studio.
  2. Add a reference to PostSharp.
  3. Populate the Program.cs with an example exception as shown.
using System;
using Common.Aspects;

namespace AspectExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            ThrowSampleExecption();
        }

        private static void ThrowSampleExecption()
        {
            throw new ApplicationException("Sample Exception");
        }
    }
}

Ok, now we have an example exception, lets show how we can catch this exception, log it, and continue.

Step 2 – Creating an exception aspect

  1. Right-click on your project and choose Add | Class.
  2. Give the class a name.
    I named my class ExceptionAspect.
  3. Click OK.
  4. Make the class inherit from OnExceptionAspect.
    Note: If you haven’t added a reference to PostSharp, you’ll need to do that now.
  5. Add a string property called Message.
  6. Add a Type property called ExceptionType.
  7. Add a FlowBehavior property called Behavior.
    The default value is FlowBehavior.Default.
  8. Override the OnException method.
  9. In the OnException method, create a message and log it.
    For this example, I will just log to the Visual Studio  Output window.
  10. In the OnException method, set the FlowBehavior to the Behavior property.
  11. Override the GetExceptionType method and configure it to return the ExceptionType property.
using System;
using System.Diagnostics;
using PostSharp.Aspects;

namespace Common.Aspects
{
    [Serializable]
    public class ExceptionAspect : OnExceptionAspect
    {
        public String Message { get; set; }

        public Type ExceptionType { get; set; }

        public FlowBehavior Behavior { get; set; }

        public override void OnException(MethodExecutionArgs args)
        {
            string msg = DateTime.Now + ": " + Message + Environment.NewLine;
            msg += string.Format("{0}: Error running {1}. {2}{3}{4}", DateTime.Now, args.Method.Name, args.Exception.Message, Environment.NewLine, args.Exception.StackTrace);
            Debug.WriteLine(msg);
            args.FlowBehavior = FlowBehavior.Continue;
        }

        public override Type GetExceptionType(System.Reflection.MethodBase targetMethod)
        {
            return ExceptionType;
        }
    }
}

Your ExceptionAspect class is complete and ready to use.

Step 3 – Apply the ExceptionAspect

  1. Add ExceptionAspect as an attribute to the ThrowSampleException method.
  2. Set the ExceptionType property to type of exception being thrown, which is an ApplicationException in this example.
  3. Set the Message property to hold a message.
  4. Set the Behavior property to FlowBehavior.Continue.
using System;
using Common.Aspects;
using PostSharp.Aspects;

namespace AspectExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            ThrowSampleExecption();
        }

        [ExceptionAspect(ExceptionType = typeof(ApplicationException), Message = "An example exception.", Behavior = FlowBehavior.Continue)]
        private static void ThrowSampleExecption()
        {
            throw new ApplicationException("Sample Exception");
        }
    }
}

This is now complete. You have now implemented try/catch as an aspect.
You should take the time to look at your code with .NET Reflector or ILSpy to see what is really being done.
So here is the resulting code for the method accord to ILSpy.

  • Notice that our one line of code in the original method is in the try block.
  • Notice that in the catch block, the OnException method is called.
  • Notice that the catch block also has a switch statement based on the FlowBehavior to determine whether to continue or rethrow, etc.
// AspectExamples.Program
private static void ThrowSampleExecption()
{
	try
	{
		throw new ApplicationException("Sample Exception");
	}
	catch (ApplicationException exception)
	{
		MethodExecutionArgs methodExecutionArgs = new MethodExecutionArgs(null, null);
		MethodExecutionArgs arg_1F_0 = methodExecutionArgs;
		MethodBase m = Program.<>z__Aspects.m2;
		arg_1F_0.Method = m;
		methodExecutionArgs.Exception = exception;
		Program.<>z__Aspects.a0.OnException(methodExecutionArgs);
		switch (methodExecutionArgs.FlowBehavior)
		{
		case FlowBehavior.Default:
		case FlowBehavior.RethrowException:
			IL_55:
			throw;
		case FlowBehavior.Continue:
			methodExecutionArgs.Exception = null;
			return;
		case FlowBehavior.Return:
			methodExecutionArgs.Exception = null;
			return;
		case FlowBehavior.ThrowException:
			throw methodExecutionArgs.Exception;
		}
		goto IL_55;
	}
}

You now can implement pretty much any try/catch block as an Aspect using the ExceptionAspect.

Reusability

One of the main benefits of Aspects is that they take cross-cutting concerns and make them modular. That means that like class files, they are now reusable. Now it is easy to use, link to, or copy and paste your ExceptionAspect class into any other project.

Return to Aspected Oriented Programming – Examples

Why I used the ‘goto’ statement in C# today

Today I did something I have only ever done once before. I used the goto statement in C#.

In batch files I used goto all the time. For those who don’t know, LANDesk Management Suite supports batch file distribution packages and I became an expert at scripting with batch files. Of course, as a batch file scripting expert, I am very good at using the goto statement, but honestly using it in C# is generally frowned upon. I am sure there are other poeple like me that have used a language where goto is popular and can recognize uses for it when they crop up.

Anyway, I needed to start, stop, or restart a windows service and I need to perform the actions asynchronously in the background. Everytime I tried to create three methods, a Start, Stop, and Restart, the code grew in size and there was lots of duplication. So I kept going back to a single method that takes an action of start, stop, restart.

Since I wanted to run the action in the background, I created a ServiceWorker that inherits from BackgroundWorker and has an Action property (for Stop, Start, Restart) and here is the method I used.

private void StartOrStopService(object sender, DoWorkEventArgs doWorkEventArgs)
{
    ServiceWorker worker = sender as ServiceWorker;
    if (worker != null)
    {
    restart:
        switch (worker.Action)
        {
            case "Start":
                Log.WriteLine("Attempting to start service: " + worker.ServiceController.DisplayName);
                worker.ServiceController.Start();
                worker.ServiceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(30000));
                break;
            case "Restart":
            case "Stop":
                worker.ServiceController.Stop();
                worker.ServiceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(30000));
                if (worker.Action == "Restart")
                {
                    worker.Action = "Start";
                    goto restart;
                }
                break;
            default:
                return;
        }
    }
}

I of course have other options, but if I break this method out into more methods, it is actually more code. For example, if I make Start and Stop methods,

private void StartOrStopService(object sender, DoWorkEventArgs doWorkEventArgs)
{
    ServiceWorker worker = sender as ServiceWorker;
    if (worker != null)
    {
        switch (worker.Action)
        {
            case "Start":
                StartService(worker);
                break;
            case "Stop":
                StopService(worker);
                break;
            case "Restart":
                StopService(worker);
                StartService(worker);
                break;
            default:
                return;
        }
    }
}

private void StartService(ServiceWorker worker)
{
    Log.WriteLine("Attempting to start service: " + worker.ServiceController.DisplayName);
    worker.ServiceController.Start();
    worker.ServiceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(30000));
}

private void StopService(ServiceWorker worker)
{
    Log.WriteLine("Attempting to stop service: " + worker.ServiceController.DisplayName);
    worker.ServiceController.Stop();
    worker.ServiceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(30000));
}

What’s your opinion?

Do you like 1 method with 28 lines including a goto statement?

Do you like 3 methods totaling 36 lines without the goto statement?

Leave a comment and let me know.

We need a standard for database password security disclosure

We need a standard that adds a requirement to inform the user of how their data, especially their password, is stored in a database.

Most data is commonly stored in plain text. The only data that is usually not in plain text is the password, which is often stored using a cryptographic hash. However, plenty of systems store the password in plain text as well.

Imagine filling out a registration form with a username and password and some peronal data and clicking submit. What if the submit process had a confirmation screen that told how your information is stored in the database. For example, a site might say that the password is stored in plain text with a little “what does this mean” link and you are asked “Are these security needs sufficient?”.

If such a pop-up were required a number of things might happen:

  1. The individual registering may choose not to use a site with such blatant disregard for security.
  2. The individual registering may choose to use the site anyway but…
    1. Use a password that they isn’t used for more secure sites.
    2. Not enter all the information (for example, if a site is not trusted I often put just my initials for first and last name.
    3. Use all false information

Almost no site provides the security information of how data is stored. Because of this, we need a personal data storage standard. Think of your personal data as related to healthcare where standards such as HIPAA already exists and already have security requirements. However, we need a standard that is more general. This is not and RFC or IEEE standard. It is more of an ISOC standard. I would say a government standard would work, however, the internet is fairly global and so it would a multi-government standard.

Digital Information Security Act (DISA)

We need a Digital Information Security Act (DISA). DISA would have rules and regulations and companies over time would start to comply. Just as we have well-known cryptographic algorithms, we would soon have well-known secure data storage methods.

(For a laugh: I first thought to call it the Personal Information Security Standard, but that acronym wasn’t very good.)

I was not surprised that British Columbia has a Personal Information Protection Act already but it hardly addresses the security of digital storage of personal data. However, it is more about how personal information is used, not about how it is securely stored in a database. I saw many privacy acts that have been implemented by various governments. However, most are in desperate need of an update adding rules from the digital perspective.

I want to focus on a rule about passwords that DISA should have.

Problems

Your personal data is your own. There are number of security issues if you lose your personal data. Your personal data includes any data that is connected to you. We are going to talk about two types of data here.

1. Your real identity

Your personal information is not really changeable. Your name is your name. Sure you could have a name legally changed, but aside from that, your name is static.  Your address and phone number are usually static but changeable over time.

2. Your online identity

This usually means your user name(s) and password(s), which are completely different from your real identity. Your online identity is dynamic and you can have many of them and use different ones on different sites. You can usually change them at any time.

Security Issues

Example Issue 1 – Identity theft

With enough of your personal information a person can pretend to be you. Steeling your identity to use it fo fraud, slander, theft, and much more.  Sensitive personal data, such as driver’s license, SSN, and identifiers should remain protected and secure.

There are many security issues, let me give a couple of examples, but there are many more.

Example Issue 2 – Security of your passwords

Since your username is not exactly secure and is easy to get, your password must be secure. Most people use passwords for multiple sites. Many sites now support authentication using a connection to another site such as OpenId, Yahoo, Google, Facebook, twitter, etc. If you password to one site is found, it is very likely that your password can be used on multiple sites.

Could you imagine someone obtained a password and you also use that password for you bank account. Yes, they could empty your account and the money could be gone and untraceable before you know it.

How your password is stored in a database is extremely important. If the password is in clear text or stored using an easily cracked hash, then your security risk is high.

First, the technology administrators such as the database administrators and others would already know and have access to your password. We usually trust “admins” and usually our data is not used in an incorrect manner, but that is not always the case, and you are vulnerable.

Second, if the database was stolen then your password is now in the hands of someone who does intend to use it maliciously.

Example Issue 3 – The real identity to online identity map

Your real data is easy to get. Knowing your first and last name is almost a non-existent security concern. Such information is in the phone books (or online phone books such as DexOnline) and in your year books and spread around records all over the world. Very few people care to secure their first and last names.

Your username is not really secure either. Usually sites provide any member the rights to see the user names of other members.

However, the connection between a real identity and online identity is a security concern.  Should “just anybody” know that bob123 is Bob Robertson? No they shouldn’t. Why? Because if someone wants to target Bob Robertson, they should not easily know that they bob123 is their target.

Lets look at a real identity to online identity map.

Real Identity Sites Online Identity Encrypted
Bob Robertson twitter.com user: bob123 pw: passwd123 yes
facebook.com user: bob123 pw: passwd123 yes
google.com user: bob123 pw: passwd123 yes
yahoo.com user: bob123 pw: passwd123 yes
Forum123.tld user: bob123 pw: passwd123 no
ABCBank.tld user: bob123 pw: passwd123 yes

For now, let’s ignore the fact that Bob made a crucial mistake of using the same username and password for his bank because a large number of the population does this.  Instead, lets focus on the result of losing your password for any accounts above.

Scenario

This is an example of scenario that describes issue 1 and issue 2. Lets say cyber thief plans to steal money from Bob’s bank account. How secure is Bob’s account with ABCBank. ABCBank surely has some great security. Unfortunately, Bob’s account is only as secure as the least secure site for which Bob has use the same account. Because the cyber thief knows that Bob Robertson is bob123, the thief now has half the information needed to get into Bob’s bank account. Next the thief can first finds all the sites where the username bob123 exists and assume that they are Bob Robertson. Then the thief can try to compromise the password at the easiest site. In the above case, the easy site to compromise is forum123.tld. The thief successfully determine’s Bob’s password at Forum123 and tries the password on a number of banks that have a brick and mortar building near Bob’s house. ABCBank is one of them and the credentials work.

At this point there are any number of ways that money can be stolen from Bob’s bank account.  Of course, no one should ever have the same username and password for their bank accounts as they do for everything else. There are actually three clear security levels and a user should have a different password at each level.

twitter.com medium
facebook.com medium
google.com medium
yahoo.com medium
Forum123.tld low
ABCBank.com High

However, let’s say Bob is not very computer literate and doesn’t even know that he should have different user names and passwords at each security level. Shouldn’t each site at least tell the user their security level and suggest to the user that they don’t use the same username and password for site with different levels of security?

Now how can we help solve some of these issue with our new DISA standard?

DISA Rule #1 – Disclose your security level

Now, imagine when Bob registered for Forum123.tld, he got a popup as follows:

This site stores the password in clear text and implements little to no security. It is not recommended that you use the same password on this site as you do for more secure sites (such as bank accounts). Would you like to continue or would like you like to use a different password?
[ Continue ] [ Use a different password ]

Were this popup to become a standard and were it implemented on almost every site, this popup would help a large portion of the population improve their username and password security issues because they would know whether their password is encrypted or not.

However, it would likely also improve the sites security because a web site administrator would work to use an well-known authentication library to become DISA compliant and because they now use a well-known authentication library, they will have access to its additional security features such as cartographic hashing of passwords and the site would likely become more secure as well.

Implementation and Enforcement

So lets say we created DISA and we created this password security disclosure rule. How could we enforce it?

Enforcement by Business Entities

Security conscious entities are already enforcing security standards such as Payment Card Industry (PCI) compliance rules for taking credit cards. Banks and credit card vendors have security requirements you must meet before they allow you to use your merchant account to take credit cards online.

However, this is not the focus of where it should be enforced. It should be enforced most on the small sites that are not very secure.

Enforcement by the Government

This is probably not a good solution. So many small one person blogs and other sites pop up each day it would be impossible for a government entity to monitor and enforce this.

Enforcement by Browsers

This is actually the perfect place to enforce this. Almost all browsers can detect when you are filling out a registration form that includes a password. The browser could intercept the submit and perform the popup using a combination of information, some hard-coded in the browser (so websites can’t fool the user) and some gather from the web site itself. I

Conclusion

How a digital information, especially a password, is a huge security concern and standards and well-known practices should exist to help both the security minded as well as the uneducated to maintain a higher state of security.

Non-technical reasons for why Linux has a larger open source market share than FreeBSD

It is not always about who is better. Often an equal or better candidate loses for reasons that should not apply. This is true for many areas (politics for example) where what matters is overlooked by our humanity. So whether one operating system is technically better than the other is not the only factor for choosing it. Linux is the most used open source operating system and has a larger market share than FreeBSD (OS X not included). This article takes a look at some other reasons one might choose Linux over FreeBSD.

Note: This article also is not taking into account OS X, which while it has some foundations is BSD, is not open source, and this article is to discuss open source market share. Due to OS X, FreeBSD could make the claim that they have a larger market share than Linux.

Reason #1 Advertising

The bottom line to advertising is that Linux has it in quantities and FreeBSD doesn’t.

Advertising

For FreeBSD, there is very little, if any, advertising. I have never seen any ad on any media type for FreeBSD.

Linux has multiple enterprise size companies, Red Hat, SUSE (previously Novel), IBM, and others that are advertising it and using it. Linux is advertised by these companies quite heavily.

Buzz

There are a few user’s groups here and there and that is about it. FreeBSD has no little buzz marketing.

Linux has a lot of buzz. There is no questioning the buzz that was created by Ubuntu that still exists. Thanks to distros like Ubuntu, Linux has an extreme amount of buzz.

What is being done?

Over the past couple of years, iXSystems has provided an increase in advertising. Also the new BSD Magazine is another form of advertising that is beneficial.

Reason #2 – Brand name and Logo

A brand name has the ability to make or break an organization. A logo has this same ability. Why? Because they are the embodiment of the company. They provide the first impressions (don’t tell me you haven’t heard that saying about first impressions) and often the only impression.

And how it sounds is extremely important.

Think about it. Some people want to sound cool when they say the operating system they run.

  • “I run Linux!”
  • “I run FreeBSD!”
I have heard people say it many times: Linux as a word just sounds cooler than FreeBSD. Well, lets actually look at from a more scientific point of view than “just sounds cooler”.  Let look at reasons

The linguistics of a brand name

Linguistic experts have studied brand names and there are many “best practices” for a brand name, and FreeBSD follows none of them. Because of this, FreeBSD is not a good brand name. It is not even average. In fact, if you were to make a list of below average brand name, FreeBSD would reside near the bottom of the bad list, and here is why.

The goal of a looking at a brand name from a linguistics point of view is to find ways to make the brand easy to say, descriptive, and memorable . A brand name is poetry and all the linguistic elements that benefit or distract from poetry can benefit or distract from a brand name. Here are ten linguistic suggestions for having a good brand name.

  1. Use alliteration in your brand name.
  2. Use equal or more harmonious consonants than cacophonous sounds. Some consonants make sounds that are “in-between” such as F. A letter such as X has two sounds, K and S.
  3. Syllables. Two or three syllables is ideal. One doable too. Four is possible if other items in this list are good. Five syllables and above your pretty much a bad brand name.
  4. Use the correct “foot“. Use disyllables such as pyrrhic, iamb,  trochee, but avoid spondee; Use trisyllables such as anaepest, credic, dactyl but avoid molossus etc…
  5. Avoid using acronyms.
  6. Vowels should rhyme or match.
  7. Avoid contrasting vowel sounds, such as a long vowel followed immediately by a short vowel.
  8. The place of articulation of each consonant and transitions between them should be easy.
  9. Use a word that can become a noun or verb.
  10. Know definitions of roots, prefixes, and postfixes and use ones that apply to your business.

So lets compare FreeBSD brand to the Linux brand.

Winner FreeBSD Linux Explanation
1 Tie n/a n/a Neither alliterated.
2 Linux Good Bad Linux has three consonants, but one is X which has two consonant sounds K and S. Sot it has, three harmonious, one cacophanous which is a 3-1 ratio.
FreeBSD has five consonants, two cacophonous, two harmonious, one in-between, which is a 2-2-1 ratio.
3 Linux Good Bad Linux is idea having two syllables.
FreeBSD is four syllables and nothing to save it.
4 Linux Good Bad Linux is a single pyrrhic foot.
FreeBSD has two feet and they are same foot, spondee, which is the one you should avoid.
5 Linux Good Bad Linux avoided acronyms, FreeBSD, has a three-letter acronym.
6 Linux Good Average Linux is two short vowels.
FreeBSD has four vowels, three long Es and one short E.
7 Linux n/a Bad Linux has no vowels next to each other.
FreeBSD has a conflict of a long E followed by a short E between the B and S letters.
8 Linux Good Average Linux has the L and N and S sounds all made by very the same mouth parts and positions, well separated by vowels.
FreeBSD has sounds made by various different places and parts in the mouth less easy transistions.
9 Linux Average Bad Linux can be a noun, and I have heard linuxed used before.
FreeBSD is barely passable as a noun and can in no way be verabalized.
10 Tie n/a n/a Linux has no syllables with any dictionary meaning.
FreeBSD has the word “free” which is too general to provide any meaning. The acronyms detracts from the mean further.

If we rated these on a scale of 0 to 5, with bad being 0, average being 3, and Good being 5, here is how the points come out.

  • FreeBSD = 2 points. Two item were N/A, so that is 2 out of 40 possible points or 5% of the possible Good points a brand could have.
  • Linux = 35 points. Three items were N/A, so that is 33 out of 35 possible points or 94% of the possible Good points a brand could have.

As you can see, from a linguistics point of view, FreeBSD is a terrible brand name. If FreeBSD were an enterprise trying to stay alive, the first order of business would be to change the brand name. Also, this analysis proves the obvious, that most of the bad branding stems from the acronym, BSD.

Derivative brand names

Derivatives of Linux, such as Red Hat, and Ubuntu have average or above average brand name as well.  Red Hat is two simple words, though they unfortunately have no meaning for an open source operating system, but as brand name these words are simple and easy to say. Simple and easy.  Ubuntu has meaning, three syllables, matching vowels, though it isn’t exactly easy to say with 2 cacophonous to only one harmonious consonant.  Both of these

Unfortunately, the FreeBSD derivatives don’t get better. The main problem is that more than half of them feel the need to continue to use the BSD acronym in their brand. There reasoning is to show their ties to BSD, but the result is very bad brand names. For example, PC-BSD somehow took a step backward by extending to five syllables, still all accented, and adding one more cacophonous sound. There is no fixing the PC-BSD brand. The only option is a new brand. However, DragonFly BSD can easily be fixed by simply dropping the “BSD” acronym as it is not needed. Alone DragonFly is a good brand. Brands that have dropped the BSD acronym such as m0n0wall or pfSense are adequate brands, not good, not bad. OpenBSD is as bad as PC-BSD with the added negative that the word “open” actually contradicts the security goals of the platform.

As derivative brand names go, Linux derivatives or distros are far ahead of FreeBSD derivatives in brand name quality.

The art of a logo

The logo is every bit as important as the brand name. Lets look at the FreeBSD logo, and the Red Hat logo and compare them.

Here are some logo tips that seemed to be common themes from dozens of sites about tips for making a good logo.

  1. Keep it simple.
  2. Make it memorable.
  3. Make sure colors coordinate.
  4. Make sure the logo has a black and white version.
  5. Color psychology. Avoid having the logo be mostly one color that may be negative.
  6. Don’t stray far from a simply decorated version of the company name.
  7. Make the logo an image that is pertinent to the brand.
  8. Avoid offensive images, even if only offensive to a small portion of the population.

One might argue that the Tux, the penguin, and Beastie, the devil or demon, are both part logo and part mascot so we will look at those, first.

 

Winner Linux FreeBSD Explanation
1 Tie Bad Bad Neither the penguin or Beastie are simple logos.
2 Tie Average Average Both are memorable
3 Tie Good Good Both have colors that coordinate fine.
4 Linux Good Average The penguin translates well to black and white.
Beastie is displayed as an outline.
5 Tie Average Average Tux is black, white, and yellow. Nothing great.
Beastie is red mostly.
6 Tie bad Bad Both stray from the brand name, probably
because they are more mascots than logos.
7 Tie bad Bad Neither is pertinent to the brand.
8 Linux Good Bad The penguin is nice and cute.
Beastie is a devil and controversially offensive. The reference to daemons and forks is lost on most people.

Ok, so neither mascot makes a good logo, but Tux does have a small edge over Beastie. Now lets look at the logos. I am going to use the Red Hat logo versus the FreeBSD logo, as Linux doesn’t exactly have its own logo.

Red Hat Logo FreeBSD logo

Winner Linux FreeBSD Explanation
1 Linux Average Bad Red Hat is two colors and is a complex drawing.
FreeBSD is a 3d sphere, it is more than two colors, red and black, as it has many different shades of red.
2 Tie Average Average Both are equally memorable
3 Tie Good Good Both are very well color cordinated.
4 Tie Bad Bad The color red makes both logos. Neither look as good in black and white only.
5 Tie Average Average Both have red and black. Not much difference.
6 Tie Average Average Both are an image to the left of the brand name.
7 Linux Good Bad Red Hat has a logo of a guy in a Red Hat, not pertanent to Linux but very pretinent to the brand.
FreeBSD has sphere with horns, and the relationship to a daemon is a stretch at best.
8 Linux Good Bad The Red Hat logo is a simple image, nothing offensive.
The devil horns comes with tons of religious history and is offensive to certain individuals, even toned down as a sphere with horns.

Using the same point system, 0, 3, 5 for Bad, Average, Good…

Linux gets 27 out of 40 possible points, or 67.5%.

FreeBSD gets 14 of a  40 points, or 35%.

After analyzing this, the FreeBSD logo isn’t as good overall as the Red Hat logo using the measurement above. However, I wouldn’t say the Red Hat logo is great either. I do think that just from a “looks and coolness” despite the rating system, the new BSD logo looks better.

What is being done?

FreeBSD recently updated the logo to the one you see above. There are no plans to improve the name, logo, or brand further that I know of.

Reason #3 – Licensing

Business and enterprise drive use. In my experience, business leaders equate open source software with the GPL license. I have heard so many companies say that they have banned open source software. However, every business leader I have educated in the different open sources licenses change the ban to allow BSD and similar licensed, citing that they didn’t understand the different licenses or the business and enterprise friendliness of the BSD and similar licenses.

Both the FreeBSD license and the GPL are great licenses. However, they have a slight different focus.  FreeBSD is a license designed to share code freely. GPL is also a license to share the code freely with the added enforcement that any code that uses GPL code is also GPL.

I have another post to discuss Differences between the BSD/FreeBSD Copyrights and the GNU Public License (GPL).

  • If you distribute binaries built using BSD Licensed source, there are only two things you shouldn’t do (you wouldn’t do either anyway).
  • If you distribute binaries built using GPL source, you have to pay attention. 1) your code may also be required to use the GPL license and 2) there are actions you must perform, such as provide access to the source and your source that uses the GPL source.

Businesses and enterprises often don’t understand that there are alternate licenses beyond GPL. Sometimes they actually prefer to buy commercial software just to avoid “open source”. We need to share how enterprise friendly the BSD license is with IT managers and business decisions makers.

I have seen this from personal experience. At a previous company, they mistakenly used GPL software and other software thinking it was free, forgetting that they actually have to perform actions in order to use this software. It cost them a lot of money when they were found out. The sad part is there was alternate  software available that was BSD Licensed, so they wasted money because neither the developers nor the business leader knew better. I knew better and they were quite shocked when I gave them a simple solution: Just use this alternate software as it is BSD Licensed. They did and it saved them a lot of money.

Even though I put licensing as the third reason, after thinking about it, this comes back to Reason #1 – Advertising again, because the main problem is that the GPL seems to be advertised more and many business leader are unaware of other open source licenses.

What is being done?

I think nothing is being done. I am not sure if there is any effort to advertise the benefits of the FreeBSD’s permissive licensing over other more restrictive licenses.

Reason #4 – A law suit early on

This was before my time, but I always hear that around the time Linux and BSD were released, BSD was sued and so people shied away from BSD because the threat of a law suit. This occurred well before I cared and if you want to read more about it, check out the wikipedia artcle.

http://en.wikipedia.org/wiki/USL_v._BSDi

I can’t prove that BSD was slowed by this, or that Linux wouldn’t have the same advantage in market share over BSD had this occurred. But every time I see a question about why FreeBSD is not more popular someone brings this up.

However, when Linux was sued by SCO, it didn’t really affect the market, so I am not sure if this was really valid or not. It is a historical possibility at best.

Reason #5 – Company backing

We know that in the early days of Linux there were multiple business who backed Linux. Then Red Hat and SUSE went enterprise. Ubuntu has Canonical.

For FreeBSD, Apple took it into their product but not as open source, and they didn’t really advertise the fact that they were partially BSD. iXSystems and some hosting companies are about all that FreeBSD has when it comes to an business.

What is being done?

Well, FreeBSD is continuing to get backing from Apple. I have heard rumors that Apple is one of the primary sponsors of Clang and LLVM (tools to replace gcc as a compiler) that uses a permissive license.

iXSystems kept FreeNAS a FreeBSD product by sponsoring it and has sponsored many booths at open source conferences.

I have heard of Yahoo being a strong backer of FreeBSD, though I am not sure of any recent examples.  But it is clear that FreeBSD needs more business backing if it plans to compete in the open source market with Linux.

AOP – Tracing methods in C# with PostSharp

Suppose you are tasked with adding logging to trace when a method starts and when it ends. Now suppose that you are tasked to do this for every method in a project, lets say you have to do this for 1,000 methods scattered throughout all your objects. Every method included would have two lines of logging code, one at the start, one at the end. That means you have to add two lines of code per method or 2,000 lines of code.  Sure, you could extract the logging methods into a static or singleton making it “easier”, but in the end, you still end up with 2,000 lines of code, two per method.

Is adding 2,000 lines of code the right solution? No it is not. These lines of code can be distracting and can make a method less readable. A single line method becomes three lines. Your class files get bigger, especially if they are method heavy. Also, these lines of code break the SOLID principles in that 1) you are repeating yourself, and 2) your method no longer has a single responsibility as it is doing what it was design for and it is doing tracing, etc. It doesn’t have to be this way.

AOP can allow you to do the same task but have the code in a single place. Including spaces and brackets, the C# MethodTracingAspect file is only 36 lines of code and to implement this into all methods in a namespace an AspectInfo.cs file is used with only three lines of code.

Which would you rather deal with: 39 lines of code in two class files, or 2,000 lines of code spread throughout ever class file?

This document assumes you have the done the following already:

  1. Installed Visual Studio
  2. Installed PostSharp
  3. Licensed PostSharp

Note: While PostSharp has a free version, my examples will likely require the licensed version.

Step 1 – Create a new C# project for Aspects

  1. In Visual Studio, choose File | New | Project.
  2. Choose a Visual C# Console Application.
  3. Give the project a Name.
    Note: I named my project AspectExamples
  4. Click Ok.

Your project is now created.

Step 2 – Add a reference to PostSharp

  1. In Solution Explorer, right-click on your new project and choose Add Reference.
  2. In the Add Reference window, click to select the .NET tab.
  3. Locate PostSharp and click to highlight it.
  4. Click Ok.

You have now added PostSharp as a reference to your project.

Step 3 – Create an Aspect for method tracing

  1. Right-click on your project and choose Add | Class.
  2. Give the class a Name.
    Note: I named my version of this class MethodTraceAspect.
  3. Add a using reference to the PostSharp.Aspects namespace.
  4. Make the object inherit from OnMethodBoundaryAspect.
  5. Override the OnEntry method.
  6. Override the OnExit method.
  7. Add code to each method for logging to the Output window using Debug.WriteLine().
    Note: Obviously, you can use any logging library you software may use.
  8. Add code to make sure that methods inside methods are properly tabbed.

Here is my final class file.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using PostSharp.Aspects;

namespace AspectsExamples
{
    [Serializable]
    public class MethodTraceAspect : OnMethodBoundaryAspect
    {
        private static int _TabCount = 0;
        private static Stack<long> _StartTimeStack = new Stack<long>();

        public override void OnEntry(MethodExecutionArgs args)
        {
            Debug.WriteLine(GetTabs() + "Method started: " + args.Method.Name);
            _TabCount++;
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            _TabCount--;
            Debug.WriteLine(GetTabs() + "Method completed:" + args.Method.Name);
        }

        private static String GetTabs()
        {
            string tabs = string.Empty;
            for (int i = 0; i < _TabCount; i++)
            {
                tabs += "\t";
            }
            return tabs;
        }
    }
}

You now have a modular Aspect that you can use to add method start, method end logging to any method in any C# project.

Step 4 – Implement the Aspect for method tracing

Implementing the Aspect for method tracing is accomplished by using an Attribute. The attribute can be added to a single method, a class, or a namespace.

We will use the following Program.cs file will demonstrate this.

using System;

namespace AspectExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            HelloWordMethod();
        }

        private static void HelloWordMethod()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Option 1 – Adding the Aspect to methods

When adding this to method, you have to add it for each method.

  1. Add the MethodTraceAspect to the Main method.
  2. Add the MethodTraceAspect to the HelloWordMethod.
using System;

namespace AspectExamples
{
    class Program
    {
        [MethodTraceAspect]
        static void Main(string[] args)
        {
            HelloWordMethod();
        }

        [MethodTraceAspect]
        private static void HelloWordMethod()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Ok, lets test this.

  1. Click Debug | Start Debugging to run the application in debug mode.
  2. Look at the Output and you should see the following lines.
Method started: Main
	Method started: HelloWordMethod
	Method completed:HelloWordMethod
Method completed:Main

Option 2 – Adding the Aspect to classes

When adding this to a class, you don’t have to add it for each method in the class.

  1. Add the MethodTraceAspect to the Program class.
using System;

namespace AspectExamples
{
    [MethodTraceAspect]
    class Program
    {
        static void Main(string[] args)
        {
            HelloWordMethod();
        }

        private static void HelloWordMethod()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Ok, lets test this.

  1. Click Debug | Start Debugging to run the application in debug mode.
  2. Look at the Output and you should see the following lines.
Method started: Main
	Method started: HelloWordMethod
	Method completed:HelloWordMethod
Method completed:Main

Option 3 – Adding the Aspect to a namespace

When adding this to a namepsace, you don’t have to add it for each class or every method in each class. Instead it is automatically added to every method in every class in the namespace.

  1. Add the MethodTraceAspect to the namespace.
    Note: Notice the syntax is slight different for adding to a namespace than for a class or method.
using System;

[assembly: MethodTraceAspect]
namespace AspectExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            HelloWordMethod();
        }

        private static void HelloWordMethod()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Ok, lets test this.

  1. Click Debug | Start Debugging to run the application in debug mode.
  2. Look at the Output and you should see the following lines.
Method started: Main
	Method started: HelloWordMethod
	Method completed:HelloWordMethod
Method completed:Main

Note: For real projects that aren’t just examples, it is a good idea to implement Aspects to a namespace in a separate file, such as an AspectInfo.cs file.

using Common.Aspects;
[assembly: MethodTraceAspect]
namespace AspectExamples {}

Congratulations, you have implemented an Aspect in C# using PostSharp.

Return to Aspected Oriented Programming – Examples

How to insert table rows using a DataTable in C#

You may have already read How to query a SQL database in C#? and How to insert a row into a Microsoft SQL database using C#? but you are looking for more information on how to insert rows using a DataTable.  Well, here is how.

The example code below assumes you have a simple database called ExampleDB, with one table called Person that has an Id (Primary Key and auto increments), a FirstName, and a LastName column.

Further information is in the comments in the sample code below.

using System.Data;
using System.Data.SqlClient;

namespace SQLExamples
{
    public class Program
    {
        static void Main(string[] args)
        {
            // Step 1 - Create the connection with a Connection string

            // Create a connection builder
            var connectionBuilder = new SqlConnectionStringBuilder();
            connectionBuilder.IntegratedSecurity = true;
            connectionBuilder.DataSource = "localhost";
            connectionBuilder.InitialCatalog = "ExampleDB";

            // Create a connection that uses the connection string
            SqlConnection connection = new SqlConnection(connectionBuilder.ConnectionString);

            // Step 2 - Open the Connection
            connection.Open();

            // Step 3 - Perform database tasks with the open connection (Examples provided...)

            //
            // Example 1 - Insert data with a query
            //

            // Create an insert query
            string insertQuery = "Insert into Person (FirstName, LastName) Values ('Jared', 'Barneck')";

            // Create an SqlCommand using the connection and the insert query
            SqlCommand insertCommand = new SqlCommand() { Connection = connection, CommandText = insertQuery };

            // Run the ExecuteNonQuery() method
            int rowsAffected = insertCommand.ExecuteNonQuery();

            //
            // Example 2 - Select * from a table
            //

            // Create a String to hold the query.
            string selectQuery = "SELECT * FROM Person";

            // Create an SqlCommand using the connection and the insert query
            SqlCommand selectCommand = new SqlCommand() { Connection = connection, CommandText = selectQuery };

            // Use the above SqlCommand object to create a SqlDataReader object.
            SqlDataReader queryCommandReader = selectCommand.ExecuteReader();

            // Create a DataTable object to hold all the data returned by the query.
            DataTable dataTable = new DataTable();

            // Use the DataTable.Load(SqlDataReader) function to put the results of the query into a DataTable.
            dataTable.Load(queryCommandReader);

            //
            // Example 3 - Insert many rows DataTable insert
            //

            // Add to the DataTable from example 2
            DataRow row1 = dataTable.NewRow();
            row1["FirstName"] = "John";
            row1["LastName"] = "Johnson";
            dataTable.Rows.Add(row1);

            DataRow row2 = dataTable.NewRow();
            row2["FirstName"] = "Jenni";
            row2["LastName"] = "Jenson";
            dataTable.Rows.Add(row2);

            string adapterInsertQuery = "Insert into Person (FirstName, LastName) Values (@FirstName, @LastName)";
            SqlCommand adapterInsertCommand = new SqlCommand() { Connection = connection, CommandText = adapterInsertQuery };
            adapterInsertCommand.Parameters.Add("@FirstName", SqlDbType.NVarChar, 255, "FirstName");
            adapterInsertCommand.Parameters.Add("@LastName", SqlDbType.NVarChar, 255, "LastName");

            SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
            adapter.InsertCommand = adapterInsertCommand;
            adapter.Update(dataTable);

            // Step 4 - Close the connection
            connection.Close();
        }
    }
}

You show now have a good starting point for using ADO.NET to manipulate a Database.

 

Return to ADO.NET and Database with C#

Running Pinta on FreeBSD – A C# (Mono) Image Editor

I wanted to continue with the C# (Mono) on FreeBSD theme this week. The next C# (Mono) post for FreeBSD is simply running a .C# (Mono) app on FreeBSD. My first thought was this, “I wonder if there is a mono version of Paint.NET?”. Paint.NET is my favorite image editor for Windows. After a quick search, I found the Pintaproject, which is a Mono clone of Paint.NET.

Installing Pinta on FreeBSD

So anyway, the steps for running on FreeBSD are quite simple.  This is a preview of my next FreeBSD Friday post, as I will continue the mono them to promote you app.

  1. Follow this post to get mono on FreeBSD.
    http://rhyous.com/2010/12/10/c-mono-on-freebsd/
  2. Download the Pinta tarball.
    Note: Get the latest link from here: http://pinta-project.com/download

    $ fetch http://cloud.github.com/downloads/PintaProject/Pinta/pinta-1.3.tar.gz
  3. Extract it:
    $ tar -xzf pinta-0.5.tar.gz
  4. Change to the directory:
    $ cd pinta-0.5
  5. Run configure.
    $ ./configure
  6. Note: I am not entirely sure this is needed, but I did it because it was there.

    $ mkdir ~/.tmp
  7. Compile the solution as follows:
    $ mdtool build Pinta.sln

    Note: I am not sure why, but “make” didn’t work, though I expected it to.

  8. Then as root or with sudo, run make install.
    # make install
  9. Make the shell rehash the commands in PATH.
    $ rehash
    Or depending on your shell...
    $ hash -r
  10. Now just run pinta.
     $ pinta

 

Pinta is now installed and usable on FreeBSD or PC-BSD.

More information

Pinta installs the following files

/usr/local/bin/pinta
/usr/local/lib/pinta/
/usr/local/lib/pinta/Pinta.Core.dll
/usr/local/lib/pinta/Pinta.Effects.dll
/usr/local/lib/pinta/Pinta.Gui.Widgets.dll
/usr/local/lib/pinta/Pinta.Resources.dll
/usr/local/lib/pinta/Pinta.Tools.dll
/usr/local/lib/pinta/Pinta.exe

The first file, /usr/local/bin/pinta, is a shell script that runs this:

#!/bin/sh
exec /usr/local/bin/mono /usr/local/lib/pinta/Pinta.exe "$@"

The other files are the application. It is a little weird to see .exe and .dll files on FreeBSD, but I’ll get over it.

Adding Pinta to the KDE Menu

I use KDE so I was able to add a menu item for pinta easily. I used the same command that the shell script used:

/usr/local/bin/mono /usr/local/lib/pinta/Pinta.exe "$@"

I found a nice installed logo and used it for the menu icon:
/usr/local/share/icons/hicolor/96×96/apps/pinta.png

Pinta in Ports

According to this Problem Report (PR), Pinta will be a port soon, if it isn’t already. http://www.freebsd.org/cgi/query-pr.cgi?pr=164309