Monthly Archives: July 2012

ReSharper hidden features – Generate Delegating Members

A frequently-used design pattern is the Decorator. This is also known as a mixin (or they might not be the very same thing but certainly they are related).

Typically you might need to create a class that implements a certain interface and uses another class that implements that exact interface but you need to provide some additional feature(s). An example would be a class that adds transactional behavior to an existing data-access class (a naive example) :


public interface IDataAccess
{
    void AddCustomerInvoice(Invoice invoice, User user);
}

public class DataAccess : IDataAccess
{
    public void AddCustomerInvoice(Invoice invoice, User user)
    {
        InsertInvoice(invoice, user);
        UpdateCustomerDebt(user, invoice.Total);
    }

    // ... the rest of the implementation
}

public class TransactionalDataAccess : IDataAccess
{
    private readonly IDataAccess _dataAccess;

    public TransactionalDataAccess(IDataAccess dataAccess)
    {
        if (dataAccess == null)
        {
            throw new ArgumentNullException();
        }
        _dataAccess = dataAccess;
    }

    public void AddCustomerInvoice(Invoice invoice, User user)
    {
         using(var tx = new TransactionScope())
         {
             _dataAccess.AddCustomerInvoice(invoice, user);
             tx.Complete();
         }
    }

    // ... the rest of the implementation
}

Another type of example would be the Adapter design pattern. An example would be providing access to a (static) class (that may be out of your control) in a mock-able manner. That is, implement another class, non-static, which implements a defined interface and eases unit-testing :

Read more »

Windows 8 – first impressions

I downloaded and installed Windows 8 Release Preview on two of my computers since one (the laptop) was up for selling to a friend and the (up to then) unused desktop was OS-less.

The installation is well streamlined, just like Office 2010 (or maybe even 2007?) in that it provides a large and attractive “Install now” button so you have very little to think. If you need to customize the installation there is a small link beneath that allows you to do just that. I didn’t opt for that.

It took, I think, 20 minutes to install completely which is pretty decent in my opinion. At this moment I need to state the hardware involved :

As you can guess the major visual difference is the start menu which looks pretty freaky as in the picture above. You will need some time to get accustomed to it. The tiles at the left are metro apps (which work pretty different, running in full screen and having the same visual style). At the right there are non-metro apps (should we call them “legacy apps”?). The desktop itself is a metro app.

The taskbar does not have the start button anymore since the start menu is a full screen thing. So you’ll probably start up, by mistake, IE 10 a few times since by default it is the leftmost thing on the taskbar. IE 10 seems to be pretty much the same thing as IE 9 but snappier.

I also struggled a bit to change the audio volume but I found that “touching” (with the mouse cursor) the top right corner brings up a band/pane which contains several settings such as audio volume, power commands and others (search, share, start, devices and settings).

A similar “charm” (it seems this is the name) exists on the left, for switching apps. You can get used to these, it ain’t too hard.

A really nice improvement is the copy/cut files dialog :

It’s nice because it has a graph and shows actual average as a horizontal line which varies depending on the actual speed of the process. It also has a nice new addition : the pause button which can be pretty handy if you need to relax a drive’s load.

The Win-TAB 3D animation for switching apps seems gone (or at least you won’t be able to trigger it with Win-TAB) which kinda sucks.

The dialog boxes are somewhat improved in the way they are simpler to understand and to decide what to do further. The file searching seems faster and app searching too.

All in all it seems like a real upgrade.

Beware of switch

I am by no means against any of the instructions which exist in C#, including goto (wow, I said that). Each of them can have its place and its normal use in an application. However things can be abused and code gets nasty.

For example let’s consider we are displaying a hierarchy of people in an organization in a tree-like visual component. We will create a class that models a person :

public class Person
{
    public string Name { get; set; }
    public IEnumerable Subordinates { get; set; }
}

All is nice but some requests come in, such as : each type of person should have a distinctive icon at its left, the managers should have salutation type displayed etc.

Then you think “I know, I’ll create a PersonType enum”. That’s when things will begin to get nasty.

public enum PersonType
{
    Undefined,
    Simple,
    Manager
}

public class Person
{
    public IEnumerable Subordinates { get; set; }

    // new members :
    public PersonType Type { get; set; }
    public string Salutation { get; set; }
    private string _name;

    // modified members :
    public string Name
    {
        get
        {
             switch(Type)
             {
                 case PersonType.Simple: return _name;
                 case PersonType.Manager : return Salutation + " " + _name;
                 default : throw new InvalidOperationException();
             }
        }
        set { _name = value; }
    }

    public Image Icon
    {
        get
        {
            switch(Type)
            {
                 case PersonType.Simple: return Icons.SimplePersonIcon;
                 case PersonType.Manager : return Icons.ManagerIcon;
                 default : throw new InvalidOperationException();
            }
        }
    }
}

If you find yourself writing switches in one or more properties or methods of the class, switching on the same thing (PersonType here) then stop it. You are writing hard-to-maintain and error-prone code. Plus its inelegant. This practically is a cry for polymorphism.

The right thing to do™ is to have three classes : an abstract Person class, a SimplePerson class (inheriting the Person class) and a ManagerPerson class (also inheriting the Person class) :


public abstract class Person
{
    public virtual string Name { get; set; }
    public IEnumerable Subordinates { get; set; }
    public abstract Image Icon { get; }
    public string Salutation { get; set; }
}

public class SimplePerson : Person
{
    public override Image Icon { get { Icons.SimplePersonIcon; } }
}

public class ManagerPerson : Person
{
    private string _name;

    public override Image Icon { get { Icons.ManagerIcon; } }
    public override string Name
    {
        get
        {
            return Salutation + " " + _name;
        }
        set
        {
            _name = value;
        }
    }
}

Notice that the code is shorter, simpler to follow and understand. Furthermore although we did introduce two more classes, we also removed the PersonType enum so at a total we introduced only one more class.

New features for database developers in SQL Server 2012 : simpler paging, sequences and FileTables

TL;DR :

  • Paging got simpler and more efficient
  • Sequences have been introduced; better performance for auto-generated IDs and easier to have IDs unique across tables
  • FileTables have been introduced : building upon the FileStream feature now we can have non-transactional access to files stored in the DB as a windows share along with transactional access via T-SQL

Lengthier version :

SQL Server 2012, in my opinion does not come with earth-shaking changes but comes with performance improvements, feature improvements and a some new features.

First of all, Management Studio has the same engine as Visual Studio which means you get a nice WPF experience, better font rendering and CTRL-scroll quick zoom-in/zoom-out.

Let’s say you want to retrieve data from the database in a paged way (that means chunks of data of a requested size or smaller). Typically you would write this in SQL Server 2008 R2 or older :


DECLARE	@Offset		AS INT = 6
DECLARE @PageSize	AS INT = 5

SELECT	Id,
		Name
FROM
(
	SELECT	Id,
			Name,
			ROW_NUMBER()	OVER (ORDER BY Id)	AS	RowNumber
	FROM	Users
) UsersSelection

WHERE	UsersSelection.RowNumber >  @Offset
	AND	UsersSelection.RowNumber <= @Offset + @PageSize

In SQL Server 2012 the T-SQL syntax has been updated introducing keywords that facilitate a simpler and more efficient paging, keywords such as OFFSET, FETCH, NEXT ROWS and ONLY. A script that would retrieve the same data would be :


DECLARE	@Offset		AS INT = 6
DECLARE @PageSize	AS INT = 5

SELECT		Id,
			Name
FROM		Users
ORDER BY	Id
OFFSET		@Offset		ROWS
FETCH NEXT	@PageSize	ROWS ONLY

Observe the simpler, clearer syntax. Also, considering that the subselect has been eliminated (the subselect was required because the ROW_NUMBER column could not be addressed in the same select – for the WHERE clause), also the query cost was improved :

2008 :

2012 :

Read more »

SQL Server 2012 local talk

Tuesday, July 10th, I’ll hold a small presentation on the new features of SQL Server 2012 for the database developer, consisting mainly of the sequences, new paging semantics and filetables.

I’ll post the code and slides soon after the presentation. I decided to drop (oh the irony) the slides.

Anyone close to Bucharest is more than welcome to come! Details can be found here.

The opening of the evening will be made by Alex Peta, presenting a cool notification system built upon JS and ASP.NET MVC 3.

WP Like Button Plugin by Free WordPress Templates