Archive for the ‘Development’ Category.

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[shell]
    Or depending on your shell...
    [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

AOP – Implementing Role Based Security

You may want to implement role-based security, where you only allow users assigned a certain role to perform certain actions in an application. Many different classes in your code will need role-based security added to them. As it turns out, role-based security is a cross-cutting concern. Well, Aspect Oriented Programming (AOP) can help you modular such a role-based security structure.

Lets start with an example. Maybe you have a database filled with people (people being a list of user or person objects). You want to control the list of people. Now think of the Create, Read, Update, Delete (CRUD) pattern. Now turn those into four permissions.  Any role could potentially have or not have rights to create a person, read a person’s info, update a person’s info, or delete a person.  An admin user would likely have all of the four CRUD rights. A user would likely have CRUD rights for their own user, but just read rights for other users. Your design might have multiple levels of rights as well. You may want to provide multiple levels of read permissions. Think of any social network where you have more read rights if you are a friend of another Person.

If it was just for a Person object, you probably would implement an AOP-based solution. However, a large application will have dozens of classes around the Person class. It will have many entities besides Person and those entities have many surrounding data classes as well. What if you had to add code to over 100 class objects? Now you can really benefit from an AOP-based design.

Well, I am going to show you example to help get you started.
Lets say you want to encrypt a field of a class. You might think that this is not a crosscutting concern, but it is. What if throughout and entire solution you need to encrypt random fields in many of your classes. Adding encryption to each of the classes can be a significant burden and breaks the “single responsibility principle” by having many classes implementing encryption. Of course, a static method or a single might be used to help, but even with that, code is must be added to each class. With Aspect Oriented Programming, this encryption could happen in one Aspect file, and be nice and modular.

Prereqs

This example assumes you have a development environment installed with at least the following:

  • JDK
  • AspectJ
  • Eclipse (Netbeans would work too)

Step 1 – Create an AspectJ project

  1. In Eclipse, choose File | New | Project.
  2. Select AspectJ | AspectJ Project.
  3. Click Next.
  4. Name your project.
    Note: I named my project AOPRolePermissions
  5. Click Finish.
The project is now created.

Step 2 – Create a class containing main()

  1. Right-click on the project in Package Explorer and choose New | Class.
  2. Provide a package name.
    Note: I named my package the same as the project name.
  3. Give the class a name.
    Note: I often name my class Main.
  4. Check the box to include a public static void main(String[] args) method.
  5. Click Finish.
package AOPRolePermissions;

public class Main
{
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
	}
}

Step 3 – Create an object that needs Role-based security

For this example, I am going to use a simple Person object.

  1. Right-click on the package in Package Explorer and choose New | Class.
    Note: The package should already be filled out for you.
  2. Give the class a name.
    Note: I named mine Person.
  3. Click Finish.
  4. Add String fields for FirstName and LastName.
  5. Add a getter and setter for each.
package AOPRolePermissions;

public class Person
{
	// First Name
	private String FirstName = "";

	public String getFirstName()
	{
		return FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		FirstName = inFirstName;
	}

	// Last Name
	private String LastName = "";

	public String getLastName()
	{
		return LastName;
	}

	public void setLastName(String inLastName)
	{
		LastName = inLastName;
	}
}

a

Step 4 – Implement example role-based code

For this I created the following objects:

  • Role
  • Permission
  • Permissions
  • FakeSession

The implementation of these is not important to this article, so I am not posting their code. However, you will see these classes if you download the project.

Step 5 – Implement an Annotation for  Role-based Security

Lets add an annotation to mark methods that should use role-based security.

  1. Right-click on the package in Package Explorer and choose New | Annotation.
    Note: The package should already be filled out for you.
  2. Give the annotation a name.
    Note: I named mine RoleBasedSecurity.
  3. Click Finish.
  4. Add a value for the permission type.
  5. Add a value for the Field name (in case the method is named completely different from the field).
  6. Set the Retention to RetentionPolicy.RUNTIME.
  7. Maybe add a comment that this annotation is for use by the Aspect (which we will create shortly).
package AOPRolePermissions;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface RoleBasedSecurity
{
	Permission.Type value() default Permission.Type.All;
	String FieldName() default "";
}

Step 6 – Add the @RoleBasedSecurity annotation to methods

  1. In the Person class, add @RoleBasedSecurity(Type.Read) tag above the gettersof Person.
  2. In the Person class, add @RoleBasedSecurity(Type.Update) tag above the setters of Person.
package AOPRolePermissions;

import AOPRolePermissions.Permission.Type;

public class Person
{
	// First Name
	private String FirstName = "";

	@RoleBasedSecurity(value = Type.Read)
	public String getFirstName()
	{
		return FirstName;
	}

	@RoleBasedSecurity(Type.Update)
	public void setFirstName(String inFirstName)
	{
		FirstName = inFirstName;
	}

	// Last Name
	private String LastName = "";

	@RoleBasedSecurity(value = Type.Read)
	public String getLastName()
	{
		return LastName;
	}

	@RoleBasedSecurity(Type.Update)
	public void setLastName(String inLastName)
	{
		LastName = inLastName;
	}
}

Step 7 – Create an Aspect to check Role-based permissions

  1. Right-click on the package in Package Explorer and choose New | Other.
  2. Choose AspectJ | Aspect.
  3. Click Next.
    Note: The package should already be filled out for you.
  4. Give the Aspect a name.
    Note: I named mine SecureByRoleAspect.
  5. Click Finish.
package AOPRolePermissions;

public aspect SecureByRoleAspect
{

}

Step 7 – Add the pointcut and advice

  1. Add a pointcut called RoleBasedSecurityMethod.
  2. Implement it to work for any method called that is annotated with @RoleBasedSecurity: call(@RoleBasedSecurity * *(..)).
  3. Add a !within(SecureByRoleAspect) (to prevent an infinite loop).
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut RoleBasedSecurityMethod() : call(@RoleBasedSecurity * *(..)) && !within(SecureByRoleAspect);
}

You now have your pointcut.

Step 8 – Implement around advice to check for permissions

  1. Add around advice that returns an Object.
  2. Implement it to be for the RoleBasedSecurityMethod pointcut.
  3. Add code to check for permissions.
  4. Add a return statement.
package AOPRolePermissions;

import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

public aspect SecureByRoleAspect
{
	pointcut RoleBasedSecurityMethod() : call(@RoleBasedSecurity * *(..))	
									&& !within(SecureByRoleAspect);
	
	
	Object around() : RoleBasedSecurityMethod()
	{
		System.out.println("Checking permissions...");
		
		RoleBasedSecurity rbs = getRBSAnnotation(thisJoinPointStaticPart);

		// Use the FieldName if specified, otherwise guess it from the method name
		String field = (rbs.FieldName().equals("")) ? removeLowerCasePrefix(thisJoinPointStaticPart
				.getSignature().getName()) : rbs.FieldName();

		if (FakeSession.Instance.getCurrentRole().GetPermissions()
				.can(rbs.value(), field))
		{
			System.out.println(String.format(
					"Success: Role has permissions to %s field named %s.%s.",
					rbs.value(), thisJoinPointStaticPart.getSignature()
							.getDeclaringType().getName(), field));
			return proceed();
		}
		else
		{
			System.out
					.println(String
							.format("Failure: Role has insufficient permissions to %s field named %s.%s.",
									rbs.value(), thisJoinPointStaticPart
											.getSignature().getDeclaringType()
											.getName(), field));
		}

		return null;
	}

	private String removeLowerCasePrefix(String inString)
	{
		int startPoint = 0;
		for (int i = 0; i < inString.length(); i++)
		{
			if (Character.isUpperCase(inString.charAt(i)))
			{
				startPoint = i;
				break;
			}
		}
		return inString.substring(startPoint);
	}

	private RoleBasedSecurity getRBSAnnotation(JoinPoint.StaticPart inStaticPart)
	{
		RoleBasedSecurity rbs = null;
		Signature sig = inStaticPart.getSignature();
		if (sig instanceof MethodSignature)
		{
			// this must be a call or execution join point
			Method method = ((MethodSignature) sig).getMethod();
			rbs = method.getAnnotation(RoleBasedSecurity.class);
		}
		return rbs;
	}
}

You are done. Go ahead and run the program. You should get the following output.

Checking permissions...
Success: Role has permissions to Update field named AOPRolePermissions.Person.FirstName.
Checking permissions...
Success: Role has permissions to Update field named AOPRolePermissions.Person.LastName.
Checking permissions...
Success: Role has permissions to Read field named AOPRolePermissions.Person.FirstName.
John
Checking permissions...
Success: Role has permissions to Read field named AOPRolePermissions.Person.LastName.
Johnson
Checking permissions...
Failure: Role has insufficient permissions to Update field named AOPRolePermissions.Person.FirstName.
Checking permissions...
Failure: Role has insufficient permissions to Update field named AOPRolePermissions.Person.LastName.
Checking permissions...
Success: Role has permissions to Read field named AOPRolePermissions.Person.FirstName.
John
Checking permissions...
Success: Role has permissions to Read field named AOPRolePermissions.Person.LastName.
Johnson

Role Based Security with AOP Project Download

AOPRolePermissions.zip

Return to Aspected Oriented Programming – Examples

AOP – Logging method execution time  in Java with AspectJ

This is not a walk-thru. This is just an example AspectJ class.

Note: For logging, the log singleton which I previously posted is used, but of course you can hook this up to your own logging methods or just print to the console.

This class is intended to log when a method executes and when a method ends and include the time it took for a method to execute in nanoseconds. Methods inside methods are tabbed. This is an enhancement to this post: AOP – Logging all method calls and executions

package mainExample;

import java.util.Stack;
import org.aspectj.lang.JoinPoint;

public aspect AspectLogMethodExecution
{
	private int tabCount = 0;
	private Stack _StartTimeStack = new Stack();

	pointcut AnyMethod() : (call(* *.*(..)) || execution(* *.*(..)))
						&& !within(AspectLogMethodExecution)
						&& !within(Log);

	before() : AnyMethod()
	{
		PrintMethod(thisJoinPointStaticPart);
		tabCount++;
		_StartTimeStack.add(System.nanoTime());
	}

	after() : AnyMethod()
	{
		Long methodExecutionTime = EvaluateExecutionTime();
		tabCount--;
		PrintMethod(thisJoinPointStaticPart, methodExecutionTime);
	}

	private Long EvaluateExecutionTime()
	{
		Long methodExecutionTime = System.nanoTime() - _StartTimeStack.pop();
		return methodExecutionTime;
	}

	private void PrintMethod(JoinPoint.StaticPart inPart)
	{
		Log.WriteLine(GetTabs() + inPart);
	}

	private void PrintMethod(JoinPoint.StaticPart inPart, long inExecutionTime)
	{
		Log.WriteLine(GetTabs() + inPart + " Execution Time: "
				+ inExecutionTime + " nanoseconds");
	}

	private String GetTabs()
	{
		String tabs = "";
		for (int i = 0; i < tabCount; i++)
		{
			tabs += "\t";
		}
		return tabs;
	}
}

So if you have a simple Hello, World app, this is the log output.

execution(void mainExample.Main.main(String[]))
	call(void java.io.PrintStream.println(String))
	call(void java.io.PrintStream.println(String)) Execution Time: 112063 nanoseconds
execution(void mainExample.Main.main(String[])) Execution Time: 904636 nanoseconds

I ran it multiple times and the executions times were sporadic. I remember reading somewhere that System.nanoTime() in java was not extremely accurate, but it is accurate enough for this example.

 
Return to Aspected Oriented Programming – Examples

AOP – Logging all method calls and executions in Java with AspectJ

This is not a walk-thru. This is just an example AspectJ class.

Note: For logging, the log singleton which I previously posted is used, but of course you can hook this up to your own logging methods or just print to the console.

This class is intended to log when a method executes and when a method ends. Methods inside are tabbed.

package mainExample;

import org.aspectj.lang.JoinPoint;

public aspect AspectLogMethodExecution
{
	private int tabCount = 0;

	pointcut AnyMethod() : (call(* *.*(..)) || execution(* *.*(..)))
						&& !within(AspectLogMethodExecution)
						&& !within(Log);

	before() : AnyMethod()
	{
		PrintMethod(thisJoinPointStaticPart);
		tabCount++;
	}

	after() : AnyMethod()
	{
		tabCount--;
		PrintMethod(thisJoinPointStaticPart);
	}

	private void PrintMethod(JoinPoint.StaticPart inPart)
	{
		Log.WriteLine(GetTabs() + inPart);
	}

	private String GetTabs()
	{
		String tabs = "";
		for (int i = 0; i < tabCount; i++)
		{
			tabs += "\t";
		}
		return tabs;
	}
}

So if you have a simple Hello, World app, this is the log output.

execution(void mainExample.Main.main(String[]))
	call(void java.io.PrintStream.println(String))
	call(void java.io.PrintStream.println(String))
execution(void mainExample.Main.main(String[]))

Return to Aspected Oriented Programming – Examples

AOP – Encrypting with AspectJ using an Annotation

This is a continuation of AOP – Encrypting with AspectJ. It is expected you have read (or skimmed) that article first. This article uses the same project. The files in the project so far are these:

  • Encrypt.java
  • EncryptFieldAspect.aj
  • FakeEncrypt.java
  • Main.java
  • Person.java

The final version of EncryptFieldAspect.aj in the previous article is not exactly a “good” Aspect. The problem with it is that it isn’t very reusable. There is a one to one relationship between this Aspect and the field it encrypts. We want a one to many relationship where one Aspect works for encrypting many fields.

Another problem is there is nothing in the objects that would inform a developer that any Aspect Oriented Programming is occurring.

Step 9 – Making the Aspect reusable

Lets make the aspect reusable. Lets make one aspect with a single pointcut and a single around advice work for multiple setters in a class.

  1. In the Person class, add a forth field, DriversLicense. This field should also be encrypted.
  2. Add a getter and setter for the DriversLicense field.
  3. In the Main class, add sample code to set and later print out the DriversLicense field.
  4. In the EncryptFieldAspect, change it to work for all setters by using a * after the word set and making it work for any method that takes a string, not just the SSN setter.
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut encryptStringMethod(Person p, String inString):
	    call(void Person.set*(String))
	    && target(p)
	    && args(inString)
	    && !within(EncryptFieldAspect);

	void around(Person p, String inString) : encryptStringMethod(p, inString) {
		proceed(p, FakeEncrypt.Encrypt(inString));
		return;
	}
}

Ok, now it is reusable but we now have another problem. It is encrypting all the fields, including FirstName and LastName. It is definitely reusable, but now we need something to differentiate what is to be encrypted from what isn’t.

Step 10 – Create an Encrypt annotation

Lets add and use an annotation to mark setters that should use encryption.

  1. Right-click on the package in Package Explorer and choose New | Annotation.
    Note: The package should already be filled out for you.
  2. Give the annotation a name.
    Note: I named mine Encrypt.
  3. Click Finish.
  4. Maybe add a comment that this annotation is for use by the Encrypt Aspect.
public @interface Encrypt
{
	// Handled by EncryptFieldAspect
}

Step 11 – Add the @Encrypt annotation to setters

  1. In the Person class, add @Encrypt above the setSSN setter.
  2. Also add @Encrypt above the setDriversLicense setter.
	@Encrypt
	public void setSSN(String inSSN)
	{
		SSN = inSSN;
	}

 

	@Encrypt
	public void setDriversLicense(String inDriversLicense)
	{
		DriversLicense = inDriversLicense;
	}
}

Step 12 – Alter the EncryptFieldAspect to work for multiple objects

Well, now that it works for any setter in the Person object that is marked with @Encrypt, the next step is to make it work for any setter marked with @Encrypt no matter what object it is in.

  1. Remove any reference to Person. We don’t even need it or the parameter ‘p’.
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut encryptStringMethod(String inString):
		call(@Encrypt * *(String))
		&& args(inString)
		&& !within(EncryptFieldAspect);

	void around(String inString) : encryptStringMethod(inString) {
		proceed(FakeEncrypt.Encrypt(inString));
		return;
	}
}

Great, now let’s test it.

Step 11 – Test Using @Encrypt on multiple objects

Ok, let’s create a second object that has an ecrypted field to test this. Lets create a Credentials.java file with a UserName and Password fields, getters and setters. Of course the Password should be encrypted.

  1. Right-click on the package in Package Explorer and choose New | Class.
    Note: The package should already be filled out for you.
  2. Give the class a name.
    Note: I named mine Credentials.
  3. Click Finish.
  4. Add both a UserName and Password field.
  5. Add a getter and setter for both.
  6. Add the @Encrypt annotation above the setPassword setter.
package AOPEncryptionExample;

public class Credentials
{
	// UserName
	private String UserName;

	public String getUserName()
	{
		return UserName;
	}

	public void setUserName(String userName)
	{
		UserName = userName;
	}

	// Password
	private String Password;

	public String getPassword()
	{
		return Password;
	}

	@Encrypt
	public void setPassword(String password)
	{
		Password = password;
	}
}

Now lets create a Credentials object in the main() method and print out the values.

package AOPEncryptionExample;

public class Main
{
	public static void main(String[] args)
	{
		Person p = new Person();
		p.setFirstName("Billy");
		p.setLastName("Bob");
		p.setSSN("123456789");
		p.setDriversLicense("987654321");

		System.out.println("Person:");
		System.out.println("         FirstName: " + p.getFirstName());
		System.out.println("          LastName: " + p.getLastName());
		System.out.println("               SSN: " + p.getSSN());
		System.out.println("  Driver's License: " + p.getDriversLicense());
		System.out.println();

		Credentials c = new Credentials();
		c.setUserName("billybob");
		c.setPassword("P@sswd!");

		System.out.println("Person:");
		System.out.println("       UserName: " + c.getUserName());
		System.out.println("       Password: " + c.getPassword());
	}
}

Ok, test it. The output should be as follows:

Person:
         FirstName: Billy
          LastName: Bob
               SSN: #encrypted#123456789#encrypted#
  Driver's License: #encrypted#987654321#encrypted#

Person:
       UserName: billybob
       Password: #encrypted#P@sswd!#encrypted#

Well, now you have learned how to encrypt using Aspect Oriented Programming.

Here are a couple of benefits of encrypting with AOP.

  1. The crosscutting concern of security is now modular.
  2. If you wanted to change/replace the encryption mechanism, including the encryption method names, you can do that in a single place, the EncryptFieldAspect object.
  3. The code to encrypt any field in your entire solution is nothing more than an annotation, @Encrypt.
  4. The @Encrypt annotation can provide documentation in the class and in API documentation so the fact that encryption is occurring is known.
  5. You don’t have to worry about developers implementing encryption differently as it is all done in a single file in the same predictable manner.

Congratulations on learning to encrypt using AOP, specifically with AspectJ and Annotations.

What about decryption?

By the way, I didn’t show you how to decrypt. Hopefully I don’t have to and after reading you know how. Maybe in your project the design is that the getters return the encrypted values and you don’t need to decrypt. However, maybe in your design you need your getters to decrypt. Well, you should be able to impement a DecryptFieldAspect and a @Decrypt annotation for that.

If you use decrypt on the getter, the output is the same as if there were no encrypt/decrypt occuring. However, it is still enhanced security because the value is stored encrypted in memory and not as plain text in memory.

However, I have a version of the project that decrypts that you can download.

AOP Encryption example project Download

Download the desired version of the project here:

Return to Aspected Oriented Programming – Examples

AOP – Encrypting with AspectJ

Lets say you want to encrypt a field of a class. You might think that this is not a crosscutting concern, but it is. What if throughout and entire solution you need to encrypt random fields in many of your classes. Adding encryption to each of the classes can be a significant burden and breaks the “single responsibility principle” by having many classes implementing encryption. Of course, a static method or a single might be used to help, but even with that, code is must be added to each class. With Aspect Oriented Programming, this encryption could happen in one Aspect file, and be nice and modular.

Prereqs

This example assumes you have a development environment installed with at least the following:

  • JDK
  • AspectJ
  • Eclipse (Netbeans would work too)

Step 1 – Create an AspectJ project

  1. In Eclipse, choose File | New | Project.
  2. Select AspectJ | AspectJ Project.
  3. Click Next.
  4. Name your project.
    Note: I named my project AOPEncryptionExample
  5. Click Finish.
The project is now created.

Step 2 – Create a class containing main()

  1. Right-click on the project in Package Explorer and choose New | Class.
  2. Provide a package name.
    Note: I named my package the same as the project name.
  3. Give the class a name.
    Note: I often name my class Main.
  4. Check the box to include a public static void main(String[] args) method.
  5. Click Finish.
package AOPEncryptionExample;

public class Main
{
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
	}
}

Step 3 – Create an object with an encrypted value

For this example, I am going to use a Person object, and we are going to encrypt the SSN on that object.

  1. Right-click on the package in Package Explorer and choose New | Class.
    Note: The package should already be filled out for you.
  2. Give the class a name.
    Note: I named mine Person.
  3. Click Finish.
  4. Add String fields for FirstName, LastName, and SSN.
  5. Add getters and setters for each.
package AOPEncryptionExample;

public class Person
{
	// First Name
	private String FirstName = "";

	public String getFirstName()
	{
		return FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		FirstName = inFirstName;
	}

	// Last Name
	private String LastName = "";

	public String getLastName()
	{
		return LastName;
	}

	public void setLastName(String inLastName)
	{
		LastName = inLastName;
	}

	// Social Security Number
	private String SSN = "";

	public String getSSN()
	{
		return SSN;
	}

	public void setSSN(String inSSN)
	{
		SSN = inSSN;
	}
}

Right now, SSN has no encryption. We don’t want to clutter our Person class with encryption code. So we are going to put that in an aspect.

Step 4 – Add sample code to main()

  1. Create in instance of Person.
  2. Set a FirstName, LastName, and SSN.
  3. Ouput each value.
public static void main(String[] args)
{
	Person p = new Person();
	p.setFirstName("Billy");
	p.setLastName("Bob");
	p.setSSN("123456789");

	System.out.println("FirstName: " + p.getFirstName());
	System.out.println(" LastName: " + p.getLastName());
	System.out.println("      SSN: " + p.getSSN());

}

If you run your project, you will now have the following output.

FirstName: Billy
 LastName: Bob
      SSN: 123456789

Step 5 – Create and object to Simulate Encryption

You don’t have to do full encryption, or any encryption at all for that matter, to test this. The important thing to realize is that you can configure how the value is stored in an object without cluttering the object with the encryption code.

I created a FakeEncrypt static object and will use this object as an example.

package AOPEncryptionExample;

public class FakeEncrypt
{
	public static String Encrypt(String inString)
	{
		return "#encrypted#" + inString + "#encrypted#";
	}
}

The goal is to passing in an SSN, 123-456-789, and have it return an encrypted value (or in this case a fake encrypted value), #encrypted#123-456-789#encrypted#.

Step 6 – Create an Aspect object

  1. Right-click on the package in Package Explorer and choose New | Other.
  2. Choose AspectJ | Aspect.
  3. Click Next.
    Note: The package should already be filled out for you.
  4. Give the Aspect a name.
    Note: I named mine EncryptFieldAspect.
  5. Click Finish.
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{

}

Step 7 – Add the pointcut

  1. Add a pointcut called SetSSN.
  2. Include two parameters, the Person object and the SSN string.
  3. Implement it with a call to void Person.setSSN(String).
  4. Add a target for the Person p.
  5. Add an args for the SSN string.
  6. Add a !within this class (to prevent an infinite loop).
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut setSSN(Person p, String inSSN):
	    call(void Person.set*(String))
	    && target(p)
	    && args(inSSN)
	    && !within(EncryptFieldAspect);
}

You now have your pointcut.

Step 8 – Implement around advice to replace the setter

  1. Add void around advice that takes a Person and a String as arguments.
  2. Implement it to be for the setSSN pointcut.
  3. Add code to encrypt the SSN.
  4. Add a return statement.
package AOPEncryptionExample;

public aspect EncryptFieldAspect
{
	pointcut setSSN(Person p, String inSSN):
	    call(void Person.set*(String))
	    && target(p)
	    && args(inSSN)
	    && !within(EncryptFieldAspect);

	void around(Person p, String inSSN) : setSSN(p, inSSN) {
		p.setSSN(FakeEncrypt.Encrypt(inSSN));
		return;
}

You are done with this one method. Here is the output of running this program.

FirstName: Billy
 LastName: Bob
      SSN: #encrypted#123456789#encrypted#

So we aren’t exactly done because we have two issues that would be nice to resolve. First, the Aspect is not reusable and second, their is no way for a developer to know by looking at the Person object that the SSN should be encrypted. Both of these issue are resolved by using annotations and will be explained in the next article.

Continue reading at AOP – Encrypting with AspectJ using an Annotation

Return to Aspected Oriented Programming – Examples

AOP – Adding Advice before or after main() in Java with AspectJ

This is a very easy example of Aspect Oriented Programming. Lets add advice (code to run) before the main() executs and when main() finishes. You will see how without cluttering our Main class or our main() method, we can add modular code to run before or after main().

Prereqs

This example assumes you have a development environment installed with at least the following:

  • JDK
  • AspectJ
  • Eclipse (Netbeans would work too)

Step 1 – Create an AspectJ project

  1. In Eclipse, choose File | New | Project.
  2. Select AspectJ | AspectJ Project.
  3. Click Next.
  4. Name your project.
    Note: I named my project mainExample
  5. Click Finish.
The project is now created.

Step 2 – Create a class containing main()

  1. Right-click on the project in Package Explorer and choose New | Class.
  2. Provide a package name.
    Note: I named my package mainExample, the same as the project name.
  3. Give the class a name.
    Note: I often name my class Main.
  4. Check the box to include a public static void main(String[] args) method.
  5. Click Finish.
package mainExample;

public class MainExample
{
	static void main(String[] args)
	{
		// TODO Auto-generated method stub
	}
}

Step 3 – Create an Aspect object

  1. Right-click on the mainExample package in Package Explorer and choose New | Other.
  2. Choose AspectJ | Aspect.
  3. Click Next.
    Note: The package should already be filled out for you with “mainExample”.
  4. Give the Aspect a name.
    Note: I named mine StartEndAspect.
  5. Click Finish.
package mainExample;

public aspect StartEndAspect
{

}

Step 4 – Add a pointcut to the StartEndAspect

  1. Create a pointcut named mainMethod().
  2. Configure the pointcut to use “execution”.
  3. Configure the pointcut to be specifically for the “public static void main(String[] args)” method.
package mainExample;

public aspect StartEndAspect
{
    pointcut mainMethod() : execution(public static void main(String[]));
}

Note: Notice that to be specific for a method, you include everything but the parameter name.

Step 5 – Add before advice

  1. Add a before() statement for mainMethod().
  2. Have it simple write to the console a message such as “The application has started.”
package mainExample;

public aspect StartEndAspect
{
    pointcut mainMethod() : execution(public static void main(String[]));

    before() : mainMethod()
    {
        System.out.println("Application has started...");
    }
}

Step 6 – Add after advice

  1. Add an after() statement for mainMethod().
  2. Have it simple write to the console a message such as “The application has ended.”
package mainExample;

public aspect StartEndAspect
{
    pointcut mainMethod() : execution(public static void main(String[]));

    before() : mainMethod()
    {
        System.out.println("The application has ended...");
    }

    after() : mainMethod()
    {
        System.out.println("The application has ended...");
    }
}

So the advice is applied and even though there is not code in main(), the advice is applied and the console output is as follows:

The application has started…
The application has ended…

Congratulations you have learned one simple way to use Aspect Orient Programming for Java with AspectJ.
Return to Aspected Oriented Programming – Examples

Xml Serialization in Java using Simple – Inheritance

This is a continuation from this post: Xml Serialization in Java using Simple

Example 4 – Serializing a list of objects that inherit from Person

Lets create some objects that inherit from Person. I looked at some documentation to try to get it right the first time. And then I hoped that it would just work….

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element(name="FirstName")
	private String _FirstName = "";

	@Element(name="LastName")
	private String _LastName = "";

	public String getFirstName()
	{
		return _FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		_FirstName = inFirstName;
	}

	public String getLastName()
	{
		return _LastName;
	}

	public void setLastName(String inLastName)
	{
		_LastName = inLastName;
	}
}
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root
public class People 
{
	@ElementList(inline=true)
	List<Person> List = new ArrayList<Person>();
}

I didn’t want to get too complex so I only added a single item to Patient, a list of Symptoms.

import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;

public class Patient extends Person
{
	@ElementList(entry = "Symptom", inline = true)
	public List<String> Symptoms = new ArrayList<String>();
}

For the Physician, again to keep it simple, I only added a list of Hospitals.

import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;

public class Physician extends Person
{
	@ElementList(entry = "Hospital", inline = true)
	public List<String> Hospitals = new ArrayList<String>();
}

And here is the main method where I create the instances and serialize them.

import java.io.File;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Run
{
	public static void main(String[] args) throws Exception
	{
		People people = new People();
		
		Patient p1 = new Patient();
		p1.setFirstName("Jared");
		p1.setLastName("Barneck");
		p1.Symptoms.add("Runny nose");
		p1.Symptoms.add("Congestion");
		people.List.add(p1);

		Physician p2 = new Physician();
		p2.setFirstName("Mike");
		p2.setLastName("Michaels");
		p2.Hospitals.add("Intermount Health Care");
		p2.Hospitals.add("St. Marks");
		people.List.add(p2);
		
		Serializer serializer = new Persister();
		File file = new File("people.xml");

		serializer.write(people, file);
	}
}

And yeah! This worked. Here is the Xml.

<people>
   <person class="Patient">
      <FirstName>Jared</FirstName>
      <LastName>Barneck</LastName>
      <Symptom>Runny nose</Symptom>
      <Symptom>Congestion</Symptom>
   </person>
   <person class="Physician">
      <FirstName>Mike</FirstName>
      <LastName>Michaels</LastName>
      <Hospital>Intermount Health Care</Hospital>
      <Hospital>St. Marks</Hospital>
   </person>
</people>

There you go.

There are a lot more examples here:
Simple Xml Serialization Tutorial

Xml Serialization in Java using Simple

So, I have to serialize some code in Java and I have used Simple (a java Xml Serialization library) before for Xml serialization with Android in Java, so I thought I would use it again for a regular java project.

Here is what I have done. Some examples have failed, some have succeed. Here are my results.

Example 1 – Serializing a simple Person object

Attempt 1 – Failed with exception

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element
	public String FirstName;

	@Element
	public String LastName;
}

And here is the Run.java with the main method.

import java.io.File;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Run
{
	public static void main(String[] args) throws Exception
	{
		Person p = new Person();

		Serializer serializer = new Persister();
		File file = new File("person.xml");

		serializer.write(p, file);
	}
}

Result

An Exception was thrown because FirstName is null. So maybe it cannot handle null values?

Attempt 2 – Succeeded

Lets try be setting the default values to an empty string.

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element
	public String FirstName = "";

	@Element
	public String LastName = "";
}

It worked. Here is the xml file.

<person>
   <FirstName>
   <LastName>
</person>

Attempt 3 – Succeeded

Of course if we set the values for FirstName and LastName…

    Person p = new Person();
    p.FirstName = "Jared";
    p.LastName = "Barneck";

…they show in the Xml as well.

<person>
   <FirstName>Jared</FirstName>
   <LastName>Barneck</LastName>
</person>

Example 2 – Serializing a Person object with getters and setters

Attempt 1 – Succeeded

I changed the member variables to be private and created public getters and setters.

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element
	private String FirstName = "";

	@Element
	private String LastName = "";

	public String getFirstName()
	{
		return FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		FirstName = inFirstName;
	}

	public String getLastName()
	{
		return LastName;
	}

	public void setLastName(String inLastName)
	{
		LastName = inLastName;
	}
}

I now use the setters to set the values in the main method.

import java.io.File;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Run
{
	public static void main(String[] args) throws Exception
	{
		Person p = new Person();
		p.setFirstName("Jared");
		p.setLastName("Barneck");

		Serializer serializer = new Persister();
		File file = new File("person.xml");

		serializer.write(p, file);
	}

}

That worked and output the desired Xml.

<person>
   <FirstName>Jared</FirstName>
   <LastName>Barneck</LastName>
</person>

Example 3 – Using a custom name

What if the name of the member variables were _FirstName and _LastName. We wouldn’t want the underscore “_” to show up in the Xml.

So what do we do? The documentation says to use this line:

@Element(name=”FirstName”)

Attempt 1 – Success

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Person
{
	@Element(name="FirstName")
	private String _FirstName = "";

	@Element(name="LastName")
	private String _LastName = "";

	public String getFirstName()
	{
		return _FirstName;
	}

	public void setFirstName(String inFirstName)
	{
		_FirstName = inFirstName;
	}

	public String getLastName()
	{
		return _LastName;
	}

	public void setLastName(String inLastName)
	{
		_LastName = inLastName;
	}
}

This worked, and the Xml output was unchanged.

Example 3 – Serializing a List

Ok, now we want to serialize a list of Person objects.

Attempt 1 – Failed with exception

I tried to use an ArrayList<Person> and it didn’t work. The person object is the same as in example 2, but I changed the main method as follows:

import java.io.File;
import java.util.ArrayList;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Run
{
	public static void main(String[] args) throws Exception
	{
		ArrayList<Person> people = new ArrayList<Person>();

		Person p1 = new Person();
		p1.setFirstName("Jared");
		p1.setLastName("Barneck");
		people.add(p1);

		Person p2 = new Person();
		p2.setFirstName("Mike");
		p2.setLastName("Michaels");
		people.add(p2);

		Serializer serializer = new Persister();
		File file = new File("people.xml");

		serializer.write(people, file);
	}
}

So that didn’t work.

Attempt 2 – Failed, no exception, just bad Xml

I created a People class that extends ArrayList<Person>.

import java.util.ArrayList;
import org.simpleframework.xml.Root;

@Root
public class People extends ArrayList<Person>
{
}

I then used this class in the main method.

	public static void main(String[] args) throws Exception
	{
		People people = new People();

		Person p1 = new Person();
		p1.setFirstName("Jared");
		p1.setLastName("Barneck");
		people.add(p1);

		Person p2 = new Person();
		p2.setFirstName("Mike");
		p2.setLastName("Michaels");
		people.add(p2);

		Serializer serializer = new Persister();
		File file = new File("people.xml");

		serializer.write(people, file);
	}

It didn’t throw and exception but the Xml was basically empty.

<people/>

That isn’t what we want.

Attempt 3 – Succeeded but not quite right

Ok, so how about a container object instead of an extending object. The documentation has an @ElementList attribute that can be used if the class contains a list. So lets use that.

import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root
public class People
{
	@ElementList
	List<Person> List = new ArrayList<Person>();
}

The main method changed slightly to accommodate the People class.

	public static void main(String[] args) throws Exception
	{
		People people = new People();

		Person p1 = new Person();
		p1.setFirstName("Jared");
		p1.setLastName("Barneck");
		people.List.add(p1);

		Person p2 = new Person();
		p2.setFirstName("Mike");
		p2.setLastName("Michaels");
		people.List.add(p2);

		Serializer serializer = new Persister();
		File file = new File("people.xml");

		serializer.write(people, file);
	}

The Xml was created and looks as follows:

<people>
   <List class="java.util.ArrayList">
      <person>
         <FirstName>Jared</FirstName>
         <LastName>Barneck</LastName>
      </person>
      <person>
         <FirstName>Mike</FirstName>
         <LastName>Michaels</LastName>
      </person>
   </List>
</people>

That is almost correct. However, we don’t need to the List line between People and person.

Attempt 4 – Succeeded

Ok, so I read the documentation and it said to use this to remove the useless List Xml element.

@ElementList(inline=true)

So I tried and sure enough, it worked.

<people>
   <person>
      <FirstName>Jared</FirstName>
      <LastName>Barneck</LastName>
   </person>
   <person>
      <FirstName>Mike</FirstName>
      <LastName>Michaels</LastName>
   </person>
</people>

Ok…lets continue this a bit later in another post.

Xml Serialization in Java using Simple – Inheritance

A Log singleton in java

I needed a simple logger in java. I wrote a quick singleton. I sort of want to keep this around if I ever need to use it again, so I thought I would post it here.

Note: Feel free to complain about this singleton using my own code style and not the java code style. 🙂

package ClinicSoft.Singletons;

import java.io.File;
import java.io.FileWriter;

public class Log
{
	public static Log Instance = new Log();

	private String _FileName;
	private String _Extension = ".log";
	private int _LogId = -1;

	private Log()
	{
		SetFileName("ClinicSoft");
	}

	public String GetFileName()
	{
		if (_LogId > -1)
			return _FileName + "." + _LogId + _Extension;
		else
			return _FileName + _Extension;
	}

	// The root file name, without the extension
	public void SetFileName(String inFileName)
	{
		_FileName = inFileName;
		while (FileExists(GetFileName()))
			_LogId++;
	}

	private boolean FileExists(String inFile)
	{
		return new File(inFile).exists();
	}

	public static void WriteLine(String inLogMessage)
	{
		Log.Instance.WriteLog(inLogMessage
				+ System.getProperty("line.separator"));
	}

	public void WriteLog(String inLogMessage)
	{
		try
		{
			// Create file
			FileWriter file = new FileWriter(GetFileName(), true);
			file.write(inLogMessage);

			// Close the output stream
			file.close();
		}
		catch (Exception e)
		{
			// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}
}

Unit Testing with Parameter Value Coverage (PVC)

Parameter Value Coverage (PVC) is the ability to track coverage of a method based on the common possible values for the parameters accepted by the method.

Current code coverage tools fail to take into consideration the possibility that a value for a parameter is not handled resulting in a bug. However, there may not be any code addressing this value in any way, introducing the possibility of obtaining 100% code coverage or line coverage (LC) without detecting the bug.

If the common values for types, especially primitive types and known types, are documented and methods that use them are required to have a test for each possible parameter value, bugs can be avoided.

The following is a table of parameter value requirements for an int or System.Int32 and string or System.String. A unit test should exist for each of the possible values in order to have 100% PVC.

System.Int32 System.String
  1. A positive integer
  2. A negative integer
  3. Zero
  4. int.MaxValue or 2,147,483,647
  5. int.MinValue or -2,147,483,648
  1. A null string
  2. An empty string, String.Empty, or “”
  3. One or more spaces ” “
  4. One or more tabs ” “
  5. A new line or Environment.NewLine
  6. A valid string.
  7. An invalid or junk string
  8. Unicode characters such as Chinese

See Parameter Value Coverage by Type for more complete list of common Parameter Values per type.

Were code coverage tools enhanced to take into account Parameter Value Coverage (PVC), better tests would be written and more bugs would be found.

Such PVC lists should be created for each primitive type and a list of required parameter values to test against for each of primitive type should be standard for each language. You could also create a list of parameter values for you own types though you may find that your own type is actually a collection of primitive types and methods, and if they are tested with PVC, your class is automatically tested with PVC as well.

Finding bugs beyond 100% Code Coverage with PVC

100% code coverage or line coverage (LC) can fail to find many bugs. Developers often write a unit test with only the goal to get as close to 100% LC as they can. Unfortunately, they are only covering the written code, but bugs may exist due to code not written.

Here is a quick example. The method below is a very common example of a piece of code that looks so simple, most assume there is no way there is a bug, but after a brief analysis, the bug becomes obvious.

public class Adder()
{
    private int Add(int val1, int val2)
   {
        return val1 + val2;
   }
}

To get 100% LC, the following test could be used.

private void Add_Test()
{
    Adder adder = new Adder();
    var actual = adder.Add(1,2);
    var expected = 3;
    Assert.AreEqual(expected, actual)
}

You now have 100% LC, but have you found all the bugs? No you haven’t. Here are two problems:

  1. An int or System.Int32 is a 32-bit integer with a max value of 2,147,483,647. What happens if you add one or more to the max value?
  2. The minimum value is -2,147,483,648. What happens if you subtract one or more from the minimum value?

How should this problem be fixed?

  • Should you enabled “checked” to disallow overflows?
  • Should you return a long so two 32-bit integers can always be added together?
  • Or should you ignore the issue as it isn’t going to matter in your project?

Your answer may be different depending on your project. I am not going to tell you how to fix this bug in this article, that is not the point. The point is to show that 100% LC failed to find this bug, proving that some level of coverage is missing; some value is not being tracked and reported on.

What is the missing value? Parameter Value Coverage (PVC).

If PVC were taken into account, the test above only provides 20% coverage as only one of the five integer value types were tested. Reaching 80% to 100% PVC would have found this bug.

Every bug that is found internally will cost your business far less money overall than if a customer finds the bug.

Return to C# Unit Test Tutorial

Better Unit Tests in C#

When you test the right thing, you get better unit tests. Better unit tests often lead to better design, testable design, and easier maintainability of code.

Look at an example of testing a Copy() method in a Person object. You will see that as you unit test this method, you are forced to think. If you think about what you really want to test (instead of just thinking about 100% coverage), and test for that, it will lead you to changing your code for the better.

With a Copy() method, you want to make sure that every property in the Person object is copied. You want to make sure that any new Property added in the future is copied.

Lets see if we can do this. Lets start with our simple example Person object with a Copy() method and lets test the copy method.

using System;

namespace FriendDatabase
{
    public class Person
    {
        #region Properties
        public int Age { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        #endregion

        #region Methods
        public Person Copy()
        {
            Person retPerson = new Person();
            retPerson.Age = this.Age;
            retPerson.FirstName = this.FirstName;
            retPerson.LastName = this.LastName;
            return retPerson;
        }
        #endregion
    }
}

Lets list the three most obvious tests for the copy method.

  1. Age is the same value.
  2. FirstName is the same value.
  3. LastName is the same value.

If you are an expert at Unit Testing, you are probably already thinking that there are more tests to run that just these three tests.0

A simple Unit Test

A test for this that would give use 100% code coverage and covers the three most obvious tests would be as follows:

[Test]
public void Person_Copy_Test()
{
    // Step 1 - Arrange
    Person p = new Person() { FirstName = "John", LastName = "Johnson", Age = 0 };

    // Step 2 - Act
    Person copy = p.Copy();

    // Step 3 - Assert
    Assert.AreEqual(p.Age, copy.Age);
    Assert.AreEqual(p.FirstName, copy.FirstName);
    Assert.AreEqual(p.LastName, copy.LastName);
}

The code coverage is now 100%. But is this a good test? No.

What are the problems with our tests?

Problem 1 – The Unit Test does not guarantee every property is copied

In the Person.Copy() method, comment out the line that copies the Age. Run the test again.

Oops! The test still passes.

What is the problem? Well, int defaults to zero.

Change the age to a value other than zero and try again.  The test now fails.

[Test]
public void Person_Copy_Test()
{
    // Step 1 - Arrange
    Person p = new Person() { FirstName = "John", LastName = "Johnson", Age = 25 };

    // Step 2 - Act
    Person copy = p.Copy();

    // Step 3 - Assert
    Assert.AreEqual(p.Age, copy.Age);
    Assert.AreEqual(p.FirstName, copy.FirstName);
    Assert.AreEqual(p.LastName, copy.LastName);
}

This fixed this one problem.

Is the test good enough now? Of course not.

Problem 2 – The Unit Test does not guarantee every property is copied

Wait, you might be saying that my problem 2 is named the same as problem 1 and you might think this is a typo. It is not a typo.

We still have a similar problem to the first problem.

Imagine a new user developer takes over the code, and decides that a MiddleName property is needed. Go ahead and add a middle name property. Don’t modify the Copy() method yet. Now run your Unit Test again.

Our one test still passes.

Shouldn’t there be a test that fails because the copy is now failing to copy to all properties? Yes there should. We have just identified a new test that actually includes the previous three tests. The goal of our three tests were all the same overall goal. Our three tests were actually slightly wrong. Instead we really had only one test: Test that when Copy() is invoked, all properties should be copied.

Now that we have gain more insight on what we are actually testing, how do we test it? How do we test all properties. One idea might be to use reflection.

[Test]
public void Person_Copy_Test()
{
    // Step 1 - Arrange
    Person p = new Person() { FirstName = "John", LastName = "Johnson", Age = 25 };

    // Step 2 - Act
    Person copy = p.Copy();

    // Step 3 - Assert
    PropertyInfo[] propInfo = typeof(Person).GetProperties();
    foreach (var prop in propInfo)
    {
        object pObj = typeof(Person).GetProperty(prop.Name).GetValue(p, null);
        object copyObj = typeof(Person).GetProperty(prop.Name).GetValue(copy, null);
        Assert.AreEqual(pObj, copyObj);
    }
}

At first this looked like a good idea, because it will check each property for us, even properties added in the future. However, it turns out that because int and string have default values, This test didn’t exactly test what we wanted to test. This test still passes when it should fail and that is a problem.

Remember the test: to test that when Copy() is invoked, all properties should be copied.

We need guarantee that each property was called and to do this. If only we were using an interface, then we could mock the interface and assert that each public property were called…A good rule to live by when developing is if you hear yourself say or you think “if only…” you should actually try implementing the “if only…” you just thought of. So lets do that.

This is a little longer of a solution but a better design, so here are some steps to get there.

  1. Create an IPerson interface that has the properties and methods we want to guarantee exist.
    using System;
    
    namespace FriendDatabase
    {
        public interface IPerson
        {
            int Age { get; set; }
            String FirstName { get; set; }
            String MiddleName { get; set; }
            String LastName { get; set; }
    
            IPerson Copy();
            void CopyTo(IPerson inIPerson);
        }
    }
    
  2. Change the person object so that you can never get a Person object, you always get an IPerson.
  3. We also need to be able to mock the instance of IPerson that is getting created by the Copy method and our current design doesn’t allow for that. Lets change our Copy method and add a CopyTo method to make this possible.
    using System;
    
    namespace FriendDatabase
    {
        public class Person : IPerson
        {
            #region Constructor
            ///
    <summary> /// Nobody should use Person, but on GetPerson()
     /// which returns and IPerson
     /// </summary>
            protected Person()
            {
            }
            #endregion
    
            #region Properties
            public int Age { get; set; }
            public String FirstName { get; set; }
            public String MiddleName { get; set; }
            public String LastName { get; set; }
            private String NickName { get; set; }
            #endregion
    
            #region Methods
            public static IPerson GetPerson(string inFirstName, string inMiddleName, String inLastName = null, int inAge = 0)
            {
                return new Person()
                {
                    FirstName = inFirstName,
                    MiddleName = inMiddleName,
                    LastName = inLastName,
                    Age = inAge
                };
            }
    
            public IPerson Copy()
            {
                IPerson retIPerson = new Person();
                CopyTo(retIPerson);
                return retIPerson;
            }
    
            public void CopyTo(IPerson inIPerson)
            {
                inIPerson.Age = this.Age;
                inIPerson.FirstName = this.FirstName;
                inIPerson.LastName = this.LastName;
            }
            #endregion
        }
    }
    
  4. Now we need a Mocking tool. Download you favorite mocking library (RhinoMocks, NMock2, or MOQ). I am going to use NMock2 which can be downloaded here: NMock2
  5. Lets put the mocking library in a lib directory in your test project.
  6. Add a reference to the dll.
  7. Now lets change our test. Lets go ahead and use the reflection still, but this time, we want to guarantee that each property was called.
    [Test]
    public void Person_Copy_All_Properties_Copied_Test()
    {
        // Step 1 - Arrange
        Mockery mock = new Mockery();
        IPerson p = Person.GetPerson("John", "J.", "Johnson", 25);
        IPerson mockIPerson = mock.NewMock();
        PropertyInfo[] propInfo = typeof(IPerson).GetProperties();
    
        // Step 2 - Expect
        foreach (var prop in propInfo)
        {
            Expect.AtLeastOnce.On(mockIPerson).SetProperty(prop.Name);
        }
    
        // Step 3 - Act
        p.CopyTo(mockIPerson);
    
        // Step 4 - Assert
        mock.VerifyAllExpectationsHaveBeenMet();
    }
    

    Note: NMock2 requires a slight variation of the Arrange, Act, Assert (AAA) unit test model in that it is more Arrange, Expect, Act, Assert (AEAA), which is just as good and just as clean. One could argue that the expectations are part of the Arrange and I would somewhat agree with that too.

  8. Ok, now run your test again and it should fail because we are not calling MiddleName in our CopyTo() method. You have now written the correct unit test for the goal.

So by taking time to think of the correct test and Unit Testing the correct test, solving the right problem, we gained a few benefits.

  • Better future maintainability
  • Better design
  • Testable design

Now hopefully you can go and do this when you write your Unit Tests.

Return to C# Unit Test Tutorial

Mocking an internal interface with InternalsVisibleTo in C#

Previously, posted instructions for setting this up.

How to Mock an internal interface with NMock2?

Attached is a sample solution that demonstrates actually implementing this.

ExampleOfIVT.zip

How to Mock an internal interface with NMock2?

I was attempting to mock an internal interface with NMock2 and no matter what I tried I continued to get the following failure.

Test 'M:ExampleOfIVT.PersonTests.FirstTest' failed: Type is not public, so a proxy cannot be generated. Type: ExampleOfIVT.IPerson
	Castle.DynamicProxy.Generators.GeneratorException: Type is not public, so a proxy cannot be generated. Type: ExampleOfIVT.IPerson
	at Castle.DynamicProxy.DefaultProxyBuilder.AssertValidType(Type target)
	at Castle.DynamicProxy.DefaultProxyBuilder.CreateInterfaceProxyTypeWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
	at NMock2.Monitoring.CastleMockObjectFactory.GetProxyType(CompositeType compositeType)
	at NMock2.Monitoring.CastleMockObjectFactory.CreateMock(Mockery mockery, CompositeType typesToMock, String name, MockStyle mockStyle, Object[] constructorArgs)
	at NMock2.Internal.MockBuilder.Create(Type primaryType, Mockery mockery, IMockObjectFactory mockObjectFactory)
	at NMock2.Mockery.NewMock[TMockedType](IMockDefinition definition)
	at NMock2.Mockery.NewMock[TMockedType](Object[] constructorArgs)
	PersonTests.cs(59,0): at ExampleOfIVT.PersonTests.FirstTest()

Obviously I have a project, ExampleOfIVT, and a test project, ExampleOfIVTTests.

All the Google searching suggested that I should be adding these lines to my AssemblyInfo.cs file in the ExampleOfIVT project but these line did NOT work.

Please not that I downloaded NMock2 from here: http://sourceforge.net/projects/nmock2/

[assembly: InternalsVisibleTo("Mocks")]
[assembly: InternalsVisibleTo("MockObjects")]

Turns out that they have changed to use Castle.DynamicProxy and so the only assembly I needed was this one.

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

Return to C# Unit Test Tutorial

Beginning Unit Testing Tutorial in C# with NUnit (Part 2)

Continued from Beginning Unit Testing Tutorial in C# with NUnit (Part 1)

Step 4 – Create your first NUnit test

  1. Choose a method from the class you want to test. For example, SimpleAddSubtractTool has the Add() method.
  2. Create a corresponding test method.  Try to name your test as follows: Method_Param1_Param2_Test() and you can add any other words to help clarify the test.
  3. Place the [Test] attribute above the test function.
  4. Add code to test the Add function.
    Note: A common testing method is Arrange Act Assert (AAA). Lets write the code in our method with this in mind.

            [Test]
            public void Add_1_And_2_Test()
            {
                // Step 1 - Arrange (Basically create the objects)
                SimpleAddSubtractTool tool = new SimpleAddSubtractTool();
    
                // Step 2 - Act
                int actual = tool.Add(1, 2);
    
                // Step 3 - Assert
                int expected = 3; // This makes it clear what you expect.
                Assert.AreEqual(expected, actual);
            }
    
  5. Now Create a similar test for the Subtract method.

You are now ready to run your test.

Step 5 – Run the test

You might think you can just right-click on the project and choose Run Tests. However, by default you cannot do this. To add a plugin called TestDriven.NET that provides this right-click Run Tests functionality,  see this post.

How to run a Unit Tests in Visual Studio?

Now you should be able to run your tests.

Step 6 – Check your code coverage

Code Coverage is basically the number of lines of code tested divided by the total number of lines of code.  If you have 10 lines of code but your test only touches five lines of code, you have 50% code coverage. Obviously the goal is 100%.

Again, by default you cannot just right-click and run the Unit Tests unless you have installed TestDriven.NET.

You should now see your code coverage. The Add() method should be 100% covered.

Step 7 – Parameter Value Coverage

You may think that you are good to go. You have unit tests, and your code is 100% covered (based on line coverage). Well, there are bugs in the code above and you haven’t found them, so you are not done. In order to find these bugs you should research the possible parameter values. You will find some more tests to run. I coined the term Parameter Value Coverage (PVC). Most code coverage tools completely ignore PVC.

Both parameters are of the type int or System.Int32. So these are 32 bit integers.

How many possible values should be tested to have 100% PVC? You should have at least these five:

  1. Positive value: 1, 2, 3, …, 2147483647.
  2. Negative vlaue: -1, -2, -3, …, -2147483648.
  3. Zero
  4. int.MaxValue or 2147483647.
  5. int.MinValue or -2147483648.
So while we have 100% code coverage we only have 20% PVC.
So looking at these five possible values, the following questions come to mind.
  • What happens if you add 1 (or any number for that matter) to int.MaxValue?
  • What happens if you subtract 1 (or any number for that matter) from int.MinValue?

Well, write unit tests to answer these questions. Adding 1 to 2,147,483,647 will fail if the expected value is the positive integer 2,147,483,648. In fact, the answer is the negative integer -2,147,483,648. Figure out why this is. Determine where the bug is, then decide how to handle it.

[Test]
        public void Add_Int32MaxValue_and_1_Test()
        {
            // Step 1 - Arrange (Basically create the objects and prepare the test)
            SimpleAddSubtractTool tool = new SimpleAddSubtractTool();

            // Step 2 - Act (Bacically call the method)
            int actual = tool.Add(int.MaxValue, 1);

            // Step 3 - Assert (Make sure what you expect is true)
            int expected = 2147483648; // This won't even compile...
            Assert.AreEqual(expected, actual);
        }

It is up to you to decide how to fix this bug, as the right way to fix this bug is not part of this article.

Return to C# Unit Test Tutorial