Friday, December 31, 2010

2010 wrap-up

2010 has been a decent year. It started a bit slow, but it has been pretty productive for the last couple of months. Looking back at the goals I sat for myself in January, it seems I completed most of them:

  • Released 3 open source projects: Nollie, ViewStateToDB and AutoMock.
  • Learned the basics of jQuery, ASP.NET MVC, Silverlight and Windows Phone programming.
  • Started working with the new version of Entity Framework, "Code-First", but did not have time to look into nHibernate.
  • Wrote 33 blog posts.
  • Read a few books on design patterns and Domain-Driven Design.
  • Improved my architectural skills and testing skills.
  • Though I did not manage to become a MCPD.

All in all I'm satisfied with 2010, but hopefully 2011 will be even better.

AutoMock is out on CodePlex

The first version of AutoMock is now out on CodePlex. AutoMock is a small library that simplifies the process of doing unit testing with a mocking framework. Without AutoMock, the process of unit testing a class that uses dependency injection, involves creating mocks for each dependency and injecting these into the class under test. This is both repetitive and boring, especially on classes with many dependencies. AutoMock simplifies this process by creating the mocks for you, together with an instance of the class under test. This saves us some lines of code for every test we write, it also makes the test smaller in size, thus easier to read and understand. Check out http://automock.codeplex.com for more information. Below is some sample code.

The class to test:
The class below uses constructor based dependency injection. It updates the data source with the customer name, writes a new event to the log and sends a notification e-mail.


public class CustomerUpdater
{
 private ICustomerDataProvider _customerData;
 private IMailSender _mailSender;
 private ILogWriter _logWriter;

 public CustomerUpdater(
  ICustomerDataProvider customerData,
  IMailSender mailSender,
  ILogWriter logWriter)
 {
  _customerData = customerData;
  _mailSender = mailSender;
  _logWriter = logWriter;
 }

 public void UpdateCustomerName(int customerId, string name, string email)
 {
  var customer = _customerData.GetCustomer(1);

  customer.Name = name;

  _customerData.UpdateCustomer(customer);

  _logWriter.Write(string.Format("Customer {0} has been updated", name));

  _mailSender.SendMail(email, string.Format("Customer {0} has been updated", name));
 }
}

Unit test without using AutoMock:


[TestMethod]
public void UpdateCustomerName_email_should_be_sent()
{
 var customerData = MockRepository.GenerateStub<ICustomerDataProvider>();
 customerData.Expect(x => x.GetCustomer(0)).IgnoreArguments().Return(new CustomerItem());
 var mailSender = MockRepository.GenerateStub<IMailSender>();
 var logWriter = MockRepository.GenerateStub<ILogWriter>();

 var customerUpdater = new CustomerUpdater(customerData, mailSender, logWriter);

 customerUpdater.UpdateCustomerName(1, "Frank", "frank@somecompany.com");

 mailSender.AssertWasCalled(x => x.SendMail(null, null), x => x.IgnoreArguments());
}

Unit test using AutoMock:


[TestMethod]
public void UpdateCustomerName_email_should_be_sent()
{
 var autoMocker = new RhinoAutoMocker<CustomerUpdater>();
 autoMocker.Get<ICustomerDataProvider>().Expect(x => x.GetCustomer(0)).IgnoreArguments().Return(new CustomerItem());

 autoMocker.ClassUnderTest.UpdateCustomerName(1, "Frank", "frank@somecompany.com");

 autoMocker.Get<IMailSender>().AssertWasCalled(x => x.SendMail(null, null), x => x.IgnoreArguments());
}

Tuesday, December 28, 2010

C#: Checked and unchecked keywords

Today I came across two C# keywords that I haven't noticed before, checked and unchecked.

After some research it turns out that checked and unchecked are used to control the overflow checking of integral-type arithmetic operations and conversions. This means that by using checked, if a value is out of range for the destination type, depending on the complexity of the expression either a compile-time error will be given or a runtime exception of type System.OverflowException will be thrown. While if unchecked is used, the number will be truncated. Both of these keywords can either be used as block statements or as operators.

Unchecked example:


int i = unchecked(Int32.MaxValue);
// i is now 2147483647

int i = unchecked(Int32.MaxValue + 1);
// i is now -2147483648

Checked example:


int i = checked(Int32.MaxValue);
// i is now 2147483647

int i = checked(Int32.MaxValue + 1);
// Gives a compile-time error, "Error: The operation overflows at compile time in checked mode"

checked
{ 
 int i = Int32.MaxValue;
 i++;
}
// Throws a runtime exception, "System.OverflowException: Arithmetic operation resulted in an overflow".

Saturday, December 25, 2010

Convention over configuration / Coding by convention

Convention over configuration, also known as coding by convention, is a software development principle with the goal to reduce the number of decisions that developers need to make. The way to do this is to use a set of conventions in the component, where the developer only needs to specify any unconventional aspects. For example, in an object relational mapping framework (ORM) this could imply that when a class is named Contact in the code, the ORM framework would assume the corresponding table in the database would also be named Contact. If this is not the case, then it must be configured.

The great benefits of this principle are ease of use and smaller configuration files as the developers don't have to configure or know all the details of the component.

Thursday, December 23, 2010

Creating instances dynamically within a layer that uses dependency injection and an IOC container

In a project where I use dependency injection in the business layer together with an IOC container, I had a need to create instances of a type dynamically from a string value, within the business layer itself. One way to do this would be to use reflection, however since the type to create an instance of is decided one layer up (here: service layer), this is not possible. The way I ended up doing it was to inject an instance of a type that implements an interface with a Resolve method, where the type of this instance is defined in the service layer.

Class diagram:

Class diagram

Walkthrough:

1) Created an interface in the business layer:


public interface IInstanceManager
{
 T Resolve(string type);
}

2) Created a new class in the service layer that implements the IInstanceManager interface:


public class InstanceManager : IInstanceManager
{
 public T Resolve(string type)
 {
  var typeInstance = Type.GetType(type);

  if (typeInstance == null)
   throw new Exception(string.Format("Type {0} was not found", type));

  return (T) _container.Resolve(typeInstance);
 }
}

3) Registered the InstanceManager with the IOC container (here: Castle Windsor):


_container.Register(Component.For().ImplementedBy());

4) Modified the class that needed to create instances dynamically to accept and use an instance of a type implementing IInstanceManager:


public class ClassA : IClassA
{
 private IInstanceManager _instanceManager;

 public ClassA(IInstanceManager instanceManager)
 {
  _instanceManager = instanceManager;
 }

 public void DoSomethingOnA()
 {
  var instance = _instanceManager.Resolve("ISomeTypeThatImplementsIClassB");
  instance.DoSomethingOnB();
 }
}

T-SQL: Remove or reduce decimal places, with or without rounding

In T-SQL, this is how you can remove or reduce the number of decimal places in a number:

With rounding:


select ROUND(55.4567, 2, 0)
-- Returns 55.4600

select CAST(55.4567 as decimal(38, 2))
-- Returns 55.46

Without rounding:


select ROUND(55.4567, 2, 1)
-- Returns 55.4500

select CAST(ROUND(55.4567, 2, 1) as decimal(38, 2))
-- Returns 55.45

T-SQL: How to get the difference in days between two dates

This is how you can get the difference in days between two dates in T-SQL:


declare @Today datetime
declare @NewYear datetime

set @Today = '2010/12/23';
set @NewYear = '2010/12/31';

select DATEDIFF(day, @today, @NewYear) as DifferenceInDays; 
-- Returns 8.

Monday, December 20, 2010

The 80-20 rule

The 80-20 rule, also known as the Pareto principle, states that roughly 80% of the effects come from 20% of the cases. If we apply this to software development it can be rephrased into a few different rules or principles:

  • 80% of the functionality will take 20% of the implementation time.
  • 80% of the functionality can be implemented for 20% of the cost.
  • 80% of the users only uses 20% of the functionality.
  • 80% of the errors and crashes will be eliminated if 20% of the top reported bugs are fixed.

Based on my own experience I agree with all of these principles. What about you?

Pet projects are required to be a good developer

The most skilled developers I know are those who work on pet projects in their spare time. A pet project can be anything from learning new technology or concepts by writing code, to creating or contributing to some real applications. Why should we do this? Well, for most of us with an 8 to 4 job there isn't enough time during the working hours to both finish our work duties and stay up to date on important principles, tools and frameworks. So if we can spend some hours off our spare time to write code it will improve our skills considerably.

Sunday, December 19, 2010

Always use strong typing

When working on a project with many developers it's highly recommended to have everything strongly typed. If things are loosely typed, a small change can break the entire application. If it's strongly typed a compile time error will be given unless it's a bug due to incorrect logic.

Some people would say that this is why we have tests. Well, few have 100% code coverage on both their unit tests and integration tests. So unless you are one of those, the key to fewer bugs is to use strong typing.

Tuesday, November 9, 2010

Nollie version 0.5 is out

I have spent some time lately working on a pet project known as Nollie. Nollie is a lightweight caching framework for .NET, which supports caching of objects to a MS SQL-Server database, to the memory or to both for improved performance.

Why did I decide to create a caching framework? Well it's fun and it's a great learning process to work on a pet project. Also I had a need for a lightweight caching framework in a real life project that supported tagging of items and removal of items by tags.

Yesterday I put the first release out on CodePlex: Nollie version 0.5 beta. I made it a 0.5 since the API is not 100% set yet, new features might be added and I'm generally looking for some feedback. Currently the code coverage is > 90%.

Some sample code and documentation will be added shortly.

Sunday, October 31, 2010

How to enable code coverage in Visual Studio 2010

This is how you enable code coverage for a solution in Visual Studio 2010:

1. In the top menu, choose "Test" and then "Select Active Test Settings". Make sure "Local" is selected.
2. Go to the top menu again, choose "Test" and then "Edit Test Settings". Choose "Local". The "Test Settings" window will now be shown.
3. Choose "Data and Diagnostics".
4. Under "Data and Diagnostics for selected role:", select "Code Coverage" by checking the "Enabled" box. Then click on the button "Configure" just above the grid. The Code Coverage Detail window will now be shown.
5. Select the assemblies/DLLs that you want to run code coverage on, then click "OK".
6. Click "Apply" then "Close".

After running tests the code coverage results should now be shown in the "Code Coverage Results" window.

Tuesday, September 28, 2010

Unit- and integration tests makes our code harder to maintain

There seem to be a common misunderstanding and hype by many developers and project managers that unit- and integration tests make our code easier to maintain. In my experience this is not the case. It's just as hard, if not harder, to write good and maintainable tests as there are to write good code in general. Due to this I often see developers commenting out their tests when changing or refactoring code, as the smallest change causes too many tests to break and it just makes it unmaintainable. Does this mean that we should not write tests? No, but in the same way as we work on sharpening our skills on writing good and maintainable code, we also need to sharpen our test writing skills.

Sunday, September 26, 2010

How to restore an Acer easyStore H340 Windows Home Server

This is how you restore an Acer easyStore H340 Windows Home Server:

1. Insert the Server Recovery Disc into any PC connected to the network where the Home Server is connected.
2. Turn off the server.
3. Take a paper clip and press it into the pinhole at the back right on the server while you turn it on. Keep the paper clipped pressed until you see a red light flashing.
4. Wait until the network icon on the server is flashing blue.
5. Follow the wizard from 1) to either reinstall Windows Home Server and preserve the data or to do a factory reset.

Wednesday, September 8, 2010

C#: How to let a method accept a variable number of arguments

The params keyword in C# lets you specify a method parameter that takes a variable number of arguments:


public int AddNumbers(params int[] numbers)
{
 var sum = 0;

 foreach (var number in numbers)
  sum = sum + number;

 return sum;
}

Usage:


var sum1 = AddNumbers(1, 2);
var sum2 = AddNumbers(1,2, 3);
var sum3 = AddNumbers(1,2, 3, 4);
var sum4 = AddNumbers(1,2, 3, 4, 5);

Thursday, August 26, 2010

C#: From delegates to anonymous methods to lambda expressions to Func delegates

Let's have a look at how the delegate syntax have evolved since the very first version of the .NET Framework and the C# language until today:
1. Basic delegates, .NET 1.0:

delegate int Add(int number1, int number2);

public int AddNumbers(int number1, int number2)
{
 return number1 + number2;
}

[TestMethod]
public void TestAddNumbers()
{
 var add = new Add(AddNumbers);

 Assert.AreEqual(4, add(1, 3));
}
2. Anonymous methods, .NET 2.0:

delegate int Add(int number1, int number2);

[TestMethod]
public void TestAddNumbers()
{
 Add add = delegate(int number1, int number2)
   {
    return number1 + number2;
   };
   
 Assert.AreEqual(4, add(1, 3));
}
3. Lambda expressions, .NET 3.5:

delegate int Add(int number1, int number2);

[TestMethod]
public void TestAddNumbers()
{
 Add add = (number1, number2) => number1 + number2;

 Assert.AreEqual(4, add(1, 3));
}
4. Func<> delegates, .NET 3.5:

[TestMethod]
public void TestAddNumbers()
{
 Func add = (number1, number2) => number1 + number2;

 Assert.AreEqual(4, add(1, 3));
}
Published: 25.08.2010

Thursday, August 19, 2010

C#: How to get the default value for a type using reflection

The following code snippet gives you the default value for the given type:

public static object GetDefaultValue(Type type)
{
 object value = null;

 if (type.IsValueType)
  value = Activator.CreateInstance(type);
 else
  value = null;

 return value;
}

Friday, August 13, 2010

Focus on good code instead of the latest technology

Ever since the first version of the .NET framework it has allowed us to create good object oriented code. Yet many .NET based applications have already been rewritten numerous times due to poor code and architecture and still the developers are feeling bad about the code quality.

Why is this? I think a major factor is due to the focus on technology, frameworks and tools, which by them self do not lead to good and maintainable code.

Though lately I've noticed a shift in the industry and on the projects that I'm involved in. We are slowly shifting to a more craftsmanship focus, where we value software principles and designs over technology. This has many great benefits for us developers. For years we have had to stay up to date on the latest technology. Today we can learn software principles and designs that have been around since the 70s, and reuse these across technological platforms. Over time this will give us better knowledge and more time to write good, maintainable code instead of spending valuable time learning every new framework out there. Cause today, most frameworks already enable us to create great software.

Thursday, August 12, 2010

C#: How to round up a floating-point number

If you need to round up a floating-point number to the closest integer, then you can use the System.Math.Ceiling method:

System.Math.Ceiling(3.0)  // Returns 3
System.Math.Ceiling(3.4)  // Returns 4
System.Math.Ceiling(3.8)  // Returns 4

Every developer should know SQL

Sooner or later every developer will have to touch a database. Without proper SQL knowledge, the result will be bad performance and bad security. Using an ORM doesn't change the performance part. Unless you know if the generated queries are good or bad, you risk getting a slow application.

I remember one time when helping out a customer who had some performance issues with their help desk application. When they called me, they had 1 300 help desk cases in the database and the performance was terrible. After doing some tracing I found the application to be doing 13 000 database queries on the page that showed all the help desk cases. That's 10 queries per case. When going through the code, I found a for-each loop with lazy loading inside it. After removing the lazy loading and modifying the SQL to use joins, the number of queries went down to 1 and the performance was great.

So how do we reduce the risk of getting issues like this with our software? My advice here is to:
1) Make sure all the team members have some basic knowledge on SQL and how to use a profiling application such as SQL Profiler.
2) Review any data access code and trace the application on a weekly basis.

Saturday, August 7, 2010

How to change an existing Visual Studio project into a test project

If you prefer to have your tests in the same Visual Studio project as the source code you are testing, then in order to be able to run your tests the project must be modified to be a test project. This is how to do it:

1) Choose Add reference on the project, and add a reference to "Microsoft.VisualStudio.QualityTools.UnitTestFramework".

2) Edit the project file by right clicking it and choosing "Unload Project". Then right click again and choose Edit. Notepad can optionally be used for this.

3) In the first <PropertyGroup> section, add the following element:

<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

The first GUID is the project type identifier for a test project, the second is the identifier for a C# class library. If your project is of any other type, replace the second GUID with the correct project type GUID defined here.

4) Save and choose Reload project.

You should now be able to run your tests through Visual Studio.

Think twice before changing to a NOSQL database

For the 15 years or so that I have been involved in the IT industry, the most stable technology around has been relational databases. A SQL Server database created more than 10 years, if modeled properly, is just as good today.

The same cannot be said about most other technologies. Front end technologies for instance, moves faster than ever. Any front end code written today is most likely to be rewritten within a few years time.

An important success factor in a project is to have as few moving, unstable parts as possible. Relational databases have been around for decades with a good track record, while most NOSQL databases on the market are new and immature. I would thus think twice before deciding to use a NOSQL database.

Thursday, August 5, 2010

C#: How to dynamically get or set property values using reflection

Snippet for dynamically getting the value of a property using reflection:


var customer = new Customer();
customer.CustomerId = 3;

var id = customer.GetType().GetProperty("CustomerId").GetValue(customer, null);
// id is 3.

And to set the value of a property:


var customer = new Customer();

customer.GetType().GetProperty("CustomerId").SetValue(customer, 3, null);
// customer.CustomerId is now 3.

C#: How to check if a type has a default/parameterless constructor

The following C# snippet returns true if the passed in type has a default/parameterless constructor:


public bool HasDefaultConstructor(Type type)
{
 if (type.IsValueType)
  return true;

 var constructor = type.GetConstructor(Type.EmptyTypes);

 if (constructor == null)
  return false;

 return true;
}

C#: How to get all the classes that inherits from a specific type

Code snippet for getting all the classes that inherits from a specific type:

public IList GetAllDerivedClasses(Type baseType)
{
 return baseType.Assembly.GetTypes().Where(
  x => 
   x.IsClass
   && x.IsSubclassOf(baseType)).ToList();
}

Wednesday, August 4, 2010

Don't implement things you dont need

In most of the projects that I have been involved with over the years, the users have requested different type of functionality which seemed critical at the time. But after it was implemented it has not been used. This feels annoying to us developers. However before criticizing others we should look at ourselves first. How often is it not that we implemented code with unnecessary complex abstractions? Very often.

Wednesday, May 19, 2010

How to auto-register types in Castle Windsor

This is how you can use Castle Windsor's fluent interface to auto-register all the types within one or more assemblies:

private static void RegisterTypes(WindsorContainer container)
{
        var assemblies = GetAssembliesToRegister();
 
        foreach (var assembly in assemblies)
        {
            container.Register(
                    AllTypes.Pick().FromAssemblyNamed(assembly)
                    .If(x => x.IsPublic)
                    .If(x => x.GetInterfaces().Length > 0)
                    .Configure(x => x.LifeStyle.Transient)
                    .WithService.FirstInterface()
                    );
        }
}
private static List GetAssembliesToRegister()
{
        var assemblies = new List();
 
        assemblies.Add("DemoApp.DataAccess");
 assemblies.Add("DemoApp.BusinessLogic");
 
        return assemblies;
}

Sunday, May 9, 2010

Paging in SQL Server 2005/2008

In order to do paging in SQL Server 2005 or later, we need to use a Common Table Expression (CTE). Below is a practical example.

Regular SQL query without paging:


select *
from Person.Contact
order by FirstName, LastName;

Query as a CTE without paging:


with Persons as
(
 select *
 from Person.Contact
)
select *
from Persons
order by FirstName, LastName;

Query as a CTE with paging, retrieving row number 41 to 60:


with PagedPersons as
(
 select *,
  row_number() over (order by FirstName, LastName) as RowNumber
 from Person.Contact
)
select *
from PagedPersons
where RowNumber between 41 and 60
order by FirstName, LastName;

Convert between PageNumber/RowsPerPage and FirstRow/LastRow:


declare @PageNumber int
declare @RowsPerPage int
declare @FirstRow int
declare @LastRow int

set @PageNumber = 3
set @RowsPerPage = 20

set @LastRow = @PageNumber * @RowsPerPage
set @FirstRow = @LastRow - @RowsPerPage + 1;

with PagedPersons as
(
 select *,
  row_number() over (order by FirstName, LastName) as RowNumber
 from Person.Contact
)
select *
from PagedPersons
where RowNumber between @FirstRow and @LastRow
order by FirstName, LastName;

Sunday, March 28, 2010

How to run WordPress locally against a live database

If you try to run a local version of WordPress against a live database, you will be redirected to the live URL. The reason for this is that the URL is defined in the database (wp_options table). In order to work around this, you can add the local URL to the /wp-config.php file:

define('WP_SITEURL', 'http://localhost:81');
define('WP_HOME', 'http://localhost:81');

Sunday, February 28, 2010

How to get Fiddler to work under Windows 7

If you try to trace your web applications using Fiddler with default settings under Windows 7, you will get the following error in your browser:


[Fiddler] Connection to localhost. failed.
Exception Text: No connection could be made because the target machine actively refused it ::1:80

This can be fixed by disabling IPv6 in Fiddler:


1. Go to Fiddler, then Tools > Fiddler Options.
2. Uncheck "Enable IPv6 (if available)".

Tracing should now work.

How to get Fiddler to trace localhost traffic

Fiddler is a great tool for tracing the HTTP traffic for your web applications. However, if you try to trace http://localhost/ you will see that it does not work. This can be fixed by either using the machine name or adding a dot at the end of the localhost address:

http://mycomputername/

or

http://localhost./

Wednesday, February 10, 2010

A generic FindControl extension method

In order to clean up and make our code more readable, generics and extension methods comes in very handy. In ASP.NET, the Control class has a FindControl method which is used as follows:


((TextBox) Page.FindControl("TxtName")).Text = "Some name";

Since this method returns a Control type, we must cast it to it's actual type before we can access any of it's members. A way to improve this code, is to create a new generic FindControl method. Since all the controls in ASP.NET such as Page, Button, TextBox, inherits from the Control class, we can make this method an extension method. By doing this, our method can be accessed the same way as the non-generic FindControl method:


Page.FindControl("TxtName").Text = "Some name";

This code is tidier and easier to read. Here is the code for the extension method:


public static class ControlExtensions
{
 public static T FindControl(this System.Web.UI.Control control, string id)
  where T : System.Web.UI.Control
 {
  return (T) control.FindControl(id);
 }
}

Always wire your events in the code behind, NOT in the aspx/ascx template file

With ASP.NET you can wire your events in the aspx/ascx template file or in the code behind file. If you wire your events in the template file, you will not get compile time support. This means that if a method is renamed or removed without updating the template file, the compiler will not throw an error. However, if the event is wired in the code behind, an error will be thrown. Events should therefore always be wired in the code behind.
Template file event wiring - not recommended:
<asp:Button runat="server" ID="BtnSave" OnClick="Save" Text="Save" />
Code behind event wiring - recommended:
protected override void OnInit(EventArgs e)
{
 base.OnInit(e);

 BtnSave.Click += new EventHandler(Save);
}

Friday, January 1, 2010

Goals for 2010

2009 achievements:

  • In 2002 I was offered a job as a developer just before finishing a college degree in computer science. I finished the college degree, but later regretted that I didn't finish at least a Bachelor degree. 1,5 years ago I decided it was time to get the degree. I took the subjects needed part time, as I still had my full time job. My last exam was finished in December. Feels great!
  • Learned and worked intensively with Windows Communication Foundation (WCF) and SOA architecture both at my full time job and as part of my Bachelor thesis.
  • Learned and used Test Driven Development (TDD) together with principles and design patterns optimized for this such as SOLID principles with dependency injection (DI) and dependency injection containers (IOC). My preferable IOC so far has been Castle Windsor.
  • Slowly started with jQuery.

Goals for 2010:

  • Learn ASP.NET MVC.
  • Learn object oriented JavaScript, Microsoft AJAX and jQuery.
  • Learn the basics of Silverlight.
  • Get up to date on the ADO.NET Entity Framework and NHibernate.
  • Write two blog posts per month.
  • Read a new technology book every 3 months.
  • Improve on creating loosely coupled architecture.
  • Create 3 new open source projects and contribute to 1 existing open source project.
  • Become a Microsoft Certified Professional Developer (MCPD).