Rafal Spacjer blog

{ skirmishes with code }

Tesoro Durandal G1N Mechanical Keyboard Review

A few weeks ago I’ve decided to change my keyboard. For the last two or three years I’ve been using Microsoft Wired Keyboard 600, which is nice, low profile keyboard. During my research for the new keyboard I’ve found many articles about mechanical keyboards and how good they are in the comparison to “traditional rubber domes” ones. This convinced me to buy one. Still there was a question about exact model. So again I’ve spent some time reading materials about key switches and their purpose (I can recommend this thread - it contains lots of useful information). The final decision was to buy keyboard with Cherry MX Brown switches.

Unfortunately in Europe and especially in Poland there is problem with getting mechanical keyboard, not saying about the possibility of choosing the type of keys switches. You can buy some keyboards with Cherry MX Redswitches, because those are used in the “gaming keyboards” and therefore more popular. Of course I could import a keyboard from the USA, but then the price would be too big for me - the shipping cost is pretty big, plus I would need to pay duty and value added tax. All of this makes that I bought Tesoro (in the United States it’s Max Keyboard) Durandal G1N mechanical keyboard, which has just shown on the European and Polish market.

Quality

The keyboard has simple, US international layout. There is one additional key - Fn which allows using multimedia functions keys that are mapped to keys from F1 to F6 (mute, change volume, play, pause, rewind). The keyboard looks almost like the “normal” one, except the right, upper corner, which is a bit bigger and has lighting sign of Tesoro company. You can also see the name of the brand on the bottom of the keyboard, just beneath the space bar. The maximal dimension of the keyboard is 46 cm (18.1 in) length and 17 cm (6.7 in) width. The front case imitate brushed metal, which looks good and prevents leaving fingerprints. On the back of the case there are rubberized elements that prevents slipping keyboard on the table. The keyboard itself is heavy and made from good quality of plastic. It has braided cable, which is also a nice addition. In summary I can say, that I’m pleased with the quality of my new keyboard.

Writing experience

This is my first mechanical keyboard and I have to admit that writing on it is a real pleasure. You can easily feel the moment when the key switch has been activated (for the MX Brown switch it’s in the half way through the key press) and you can release it. This allows you to use less force to write something on the keyboard. The result is that you can write faster and your hands are less exhausted. Unfortunately I haven’t used any other mechanical keyboard so I can’t compare this one with others - maybe in the future I will be able to do this ;)

I’ve decided to buy keyboard with the brown switches because they are advertiser as quieter than the blue ones (for the blue switches you can hear the ‘click’ sound when you press the key), but still good for typing. Despite of it I have to admit that this keyboard is quite loud. For me this isn’t a problem, but for my wife it is ;) She complains about the noise, so I have to close the door to my room when I’m typing a lot of text or playing any game. To solve this problem I’m going to buy the rubber o-ring switch dampeners to reduce the noise. When I do this I will try to write something about it on my blog.

Conclusion

If you are looking for good and not expensive keyboard for writing and occasionally playing games I can recommend you the Tesoro Durandal G1N keyboard. I’ve been using it for more than a month and I’m very happy with it. My wife apparently not …

Tesoro Durandal G1N Tesoro Durandal G1N Tesoro Durandal G1N Cherry MX Brown switches

Moving to Octopress

I’ve decided to move, my not very often updated blog, to the new platform. I’ve made a choice to use Octopress blog engine. Octopress uses Jekyll, a static site generator in ruby, that basically takes bunch of templates files and produce a set of html pages. I could use Jekyll, but Octopress extends it with additional files, themes and plugins, so you can create your blog very fast with small effort.

Till now my blog was powered by Wordpress engine, so why I wanted to change it? The main reason is that Wordpress is quite complex engine (with many plugins and settings) that I’ve never fully understood. Changing something in it was more like hacking for me than full understandable programming. Additionally Wordpress uses mysql database to store posts which adds complexity to backup strategy - I needed to store all Wordpress files, plus database with posts. This is why I decided to change it.

What I like in Octopress:

  • simplicity - the whole blog can be generated by one command (rake generate), which creates a set of HTML and JavaScript files that can be uploaded to the server; by default Octopress supports Github Pages and Heroku, it can also uses rsync to deploy files to custom server.
  • customization - there are many plugins you can use (twitter and github integration for example) and the design of the blog can also be easily changed by tweaking Sass (*.scss) files.
  • beautiful, built-in code highlighter with support for many languages - it uses Solarized color scheme (light or dark) which looks great;
  • possibility of writing post as a simple text file, using markdown - you can create/edit them in your favorite text editor (Sublime Text is my choice);
  • easy backup - I store all files in a git repository;
  • a chance to work with ruby language - currently I’m trying to extend my knowledge about it, which gives me a lot of fun.

Finally I would like to say few words about my transition from Wordpress to Octopress. The migration process I’ve started from exporting all my posts from Wordpress to markdown files - I did it by using WordPress to Jekyll Exporter plugin. After this I’ve tweaked generated posts, installed default theme (I’ve changed it a little bit - my inspiration was darkstripes theme by Alessandro Melandri) and set base settings in _config.yml file. The final results you can see here, I hope you like it.

Live Template for Caliburn.Micro Framework

Recently I’ve been working on the WPF application that extensively uses Caliburn.Micro framework for MVVM pattern. MVVM usually force you to write many properties in the ViewModel. Those properties should typically notify View about their values changes – to do that every ViewModel has to implement INotifyPropertyChanged interface and in the setters of the properties we need to rise NotifyPropertyChanged event, for example like that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class SelectTagsViewModel : Screen
{
  public event PropertyChangedEventHandler PropertyChanged;

  private string _property;

  public string Property
  {
      get { return _property; }

      set
      {
          _property = value;
          NotifyPropertyChanged("Property");
      }
  }

  private void NotifyPropertyChanged(string name)
  {
      if (PropertyChanged != null)
      {
          PropertyChanged(this, new PropertyChangedEventArgs(name));
      }
  }
}

In Caliburn.Mirco your ViewModel can inherit from PropertyChangedBase class (or other classes that internally inherit from PropertyChangedBase class – like Screen, Conductor and so on) and then in properties you can use NotifyOfPropertyChange method:

1
2
3
4
5
6
7
8
9
10
11
private string _property;

public string Property
{
  get { return _property; }
  set
  {
      _property = value;
      NotifyOfPropertyChange(() => Property);
  }
}

Because in my project I have to write many properites with NotifyOfPropertyChange method in their setters, I’ve decided that I write Resharper Live Template for this purpose. To do this you should go to the ‘Resharper‘ menu in Visual Studio, then ‘Live Templates‘ and there you should select ‘New Template‘ button. After this you will get the window like this one:

In the left part you can write the code of the snipped. In my case it was:

1
2
3
4
5
6
7
8
9
10
11
12
private $TYPE$ _$PRIVATEMEMBER$;

public $TYPE$ $PROPERTYNAME$
{
  get   { return _$PRIVATEMEMBER$; }
  set
  {
      _$PRIVATEMEMBER$ = value;

      NotifyOfPropertyChange(() => $PROPERTYNAME$);
  }
}

where:

  • $TYPE$ – the type of the property
  • $PRIVATEMEMBER$ – the name of the private field
  • $PROPERTYNAME$– the name of the property

The most tricky part of this template is setting properties of the template in the right pane of the window. This should be done in this way:

  • In the Editable Occurrence column we specify the order of defining elements of the template – first the type and the name of the field that will be used for this property.
  • In the Value column we can set how the value of the template field will be calculated – the value of $PROPERTYNAME$ property is set as name of the private field with first character as upper case.

The last thing to do is to set a shortcut for this snippet (in this case: propnot) and the description. And this is it, after saving you have a new live template that can be use in code editor by simply writing “propnot“. If you do that you will get something like this in Visual Studio:

Case Insensitive Contains Method for a String Class

I decided that in the next few weeks I will write series of short blog posts with code snippets that I use during my everyday work.

Very often I have to check if a string contains specific sequence of characters, to do it I write something like this:

1
2
3
4
if (text.Contains("some text"))
{
  DoSomething();
}

and after few seconds I realize that it won’t work correctly because Contains method is case-sensitive. To solve this problem I’ve written an extension method that does case-insensitive checking. Here is my method:

1
2
3
4
5
6
7
8
9
10
11
12
public static class StringExtensionMethods
{
  public static bool ContainsWithIgnoreCase(this string text, string value)
  {
     if (text == null)
     {
         return false;
     }
     return
      (text.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0);
  }
}

and now I can simply write:

1
2
3
4
if (text.ContainsWithIgnoreCase("some text"))
{
  DoSomething();
}

At the beginning of the extension method I check if text isn’t null and if so I return false. This causes that I don’t have to check if a variable is null before using this method.

Template Method Pattern

Sometimes I write a class that has many similar methods. All those methods start from initialization block, then there is a processing part and at the end there is finalizing segment. In other words those methods are only different in processing code – rest is the same.

When I see that kind of class I immediately start thinking about using template method patter. You can read about this pattern here . The general idea is that you have an abstract class that creates template method for concrete classes that derive from it and add its own functionality to this method.

I will show it by examples.

First let’s assume we have to write a class that will process a text file. The file contains only one line with an integer number. Our task is to write a methods that will increment (n ), decrement (n–) or multiple by two (n=*2) this number.

Let’s start from trivial implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public class IntegerFileOperation
{
    private string filePath;

    public IntegerFileOperation(string filePath)
    {
        this.filePath = filePath;
    }

    public int Increment()
    {
        string numerText = File.ReadAllText(filePath);

        int integer;
        if (int.TryParse(numerText, out integer))
        {
            integer  ;

            File.WriteAllText(filePath, integer.ToString());

            return integer;
        }

        throw new InvalidOperationException();
    }

    public int Decrement()
    {
        string numerText = File.ReadAllText(filePath);

        int integer;
        if (int.TryParse(numerText, out integer))
        {
            integer--;

            File.WriteAllText(filePath, integer.ToString());

            return integer;
        }

        throw new InvalidOperationException();
    }

    public int MultipleByTwo()
    {
        string numerText = File.ReadAllText(filePath);

        int integer;
        if (int.TryParse(numerText, out integer))
        {
            integer *= 2;

            File.WriteAllText(filePath, integer.ToString());

            return integer;
        }

        throw new InvalidOperationException();
    }
}

As we can see our  class has three methods: Increment(), Decrement() and MultipleByTwo() – the only difference between them is in line where we change integer variable, rest is the same. There is lots of redundant code that should be removed, to do it we can introduce a base, abstract class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public abstract class IntegerFileOperationBase
{
    private string filePath;

    protected abstract int DoOperation(int number);

    public IntegerFileOperationBase(string filePath)
    {
        this.filePath = filePath;
    }

    public int ChangeNumber()
    {
        string numerText = File.ReadAllText(filePath);

        int integer;
        if (int.TryParse(numerText, out integer))
        {
            integer = DoOperation(integer);

            File.WriteAllText(filePath, integer.ToString());

            return integer;
        }

        throw new InvalidOperationException();
    }
}

In IntegerFileOperationBase class we have a method ChangeNumber() which is a template method. This method opens a text file, reads its content, parses it as an integer and then invokes DoOperation method to change the integer variable. After all the new value is saved to the file. By various implementation of DoOperation method we can change the way that ChangeNumber method works. Here’s how we can do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class IncrementIntegerInFile : IntegerFileOperationBase
{
    public IncrementIntegerInFile(string filePath)
        : base(filePath)
    {
    }

    protected override int DoOperation(int number)
    {
        return   number;
    }
}

public class DecrementIntegerInFile : IntegerFileOperationBase
{
    public DecrementIntegerInFile(string filePath)
        : base(filePath)
    {
    }

    protected override int DoOperation(int number)
    {
        return --number;
    }
}

public class MultipleByTwoIntegerInFile : IntegerFileOperationBase
{
    public MultipleByTwoIntegerInFile(string filePath)
        : base(filePath)
    {
    }

    protected override int DoOperation(int number)
    {
        return number * 2;
    }
}

The result of our  refactoring is a code without redundancy. I don’t like this solution, because I feel it’s too complicated for such an easy task (we have four classes instead of one). We can solve this problem by reimplementing it with delegate mechanism. Instead of an abstract  DoOperation() method we can use a delegate that will be passed to the ChangeNumber() method as a parameter (I use generic Func<int, int> delegate as a type – read more. To implement Increment(), Decrement() and MultipleByTwo() methods we use ChangeNumber method with lambda expression as a parameter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class IntegerFileOperationWithDelegate
{
    private string filePath;

    public IntegerFileOperationWithDelegate(string filePath)
    {
        this.filePath = filePath;
    }

    public int ChangeNumber(Func doOperation)
    {
        string numerText = File.ReadAllText(filePath);

        int integer;
        if (int.TryParse(numerText, out integer))
        {
            integer = doOperation(integer);

            File.WriteAllText(filePath, integer.ToString());

            return integer;
        }

        throw new InvalidOperationException();
    }

    public int Increment()
    {
        return ChangeNumber(n =>   n);
    }

    public int Decrement()
    {
        return ChangeNumber(n => --n);
    }

    public int MultipleByTwo()
    {
        return ChangeNumber(n => n * 2);
    }
}

This makes that we have only one, clean class without redundant code. If I need to write a class with lots of repeated code I try to use this pattern to solve it.

Do you like that kind of solution? Or maybe it’s completely wrong? Please tell me in the comments.

My Top 10 Features of JetBrains ReSharper

I have to say that I’m a big fan of ReSharper plugin (or maybe a better word: tool) for Visual Studio. I’ve been using it for almost 3 years now.  After this time I can only say that I’m really angry if I have to code in VS without ReSharper. Working with it is a pleasure and every .Net developer should at least try it, you don’t regret it!

To give only a small overview of its potential I will describe here 10 functions that I use the most:

(ReSharper allows us to use one of two keymaps: Visual Studio scheme or IDEA scheme. In all my description I will use VS scheme)

  1. Go to Type (Ctrl + T)

    In my work I usually know a name of a class I’m looking for, but I don’t know where it is (in which project, folder etc.). The solution is very simple: I hit Ctrl + T and I start writing class name – ReSharper shows me all matching types, I only have to select the one I need. In the editor we can use special characters that can substitute zero or more characters (*), zero or one character (?) and one or more characters ( )

  2. Go to Inheritor (Alt + End)

    As the name says, it allows us to go to the inheritor of selected class. After hitting the shortcut you get the dialog with all inheritors. Especially I like it when I see an interface in code and I want to go to its implementation. Really cool!

  3. Find Usages (Shift + F12)

    It helps find all usages of a class, method, property and any other object in code. With this functionality we can easily understand where and why any object is used.

  4. Locate in Solution Explorer (Shift + Alt + L)

    As I wrote before I use “Go to type” all the time, but sometimes when I work with a file in Visual Studio I need to change one of its properties or simply see in which folder in solution it is. Everyone who works with VS knows that finding a file in big solution is frustrating, with this option it won’t be anymore. Simple use this method for opened file and it will be highlighted in solution explore.

  5. Create from Usage (Alt + Enter)

    Another great feature of ReSharper.  Let’s assume you’re writing a code in VS that needs to parse some string variable. So you can write something like this:

    string number = ParseMyVariable(someText);

    The name of the method will be marked with red, so you can simply hit Alt + Enter and select: Create method ParseMyVariable, RS will create method with good signature for you.

  6. Symbol Code Completion (Ctrl + Space)

    This function is great for lazy people (yes, I’m and I use it all the time).  Again I will show it by example: I need to create instance of SqlCommand, so I write SqlCommand and hit Ctrl + Space, after that ReSharper will suggest me possible names for a variable. I only need to select the one I like. The names are usually very smart created, so for SqlCommand proposition will be command or sqlCommand

  7. Rename (Ctrl + R, R)

    I can’t say much about it, because the name tells everything.  It changes the name of a symbol (method, class, property and so on) in every file it is.

  8. Introduce Parameter (Ctrl + R, P)

    Sometime, during refactoring we need to change a local variable to the method parameter and this function is great for this. The best is that ReSharper will try to change every invocation of the method by adding appropriate parameter – it takes it value from the context.

  9. ‘Surround With’ Templates (Ctrl + E, U)

    I use it usually when I need to add try…catch block or a region in code (there is more build in statements). To do it I select a part of a code, hit the shortcut and select the statement I want – rest is done automatically (ex. code is nice formatted)

  10. Go to File Member (Alt + \)

It allows us quickly go to any file member:
- method, property, field for a class
- node element for xml file

So this is my top 10 of ReSharper features and what is your? Or maybe you’re big fan of CodeRush  if so please write me why it’s better then ReSharper.

Useful Applications for Android Phones

I’ve been using Htc Hero for almost half a year. After I bought the phone I’ve started exploring the Android Market in search of free, useful applications. There is so many of them that it’s really hard to find any good among them.  I’m still searching but for now I’m using those (this is my list of best tools for Android):

  • Advanced Task Killer – simple task manager that allows us to kill not used apps (it saves battery lifetime and releases memory).
  • ASTRO File Manager – advance file manager (copy, cut, past files; working with zip files; editing text files etc.).
  • Evernote – mobile version of great PC/Mac notes taking tool. I use the PC version to manage all my notes and this small app allows me to view them on my phone. We can also create notes and send them to the Evernote account.
  • Dropbox – another mobile version of PC/Mac tool. Dropbox lets us store, sync and share files using Internet. It’s especially helpful if we have many computers and we need to have access to the same files on them.
  • Astrid – a simply, but powerful TODO list. It has tagging, partial progress, remainders, syncing with Remember The Milk.
  • Twidroid – twitter client with very clear GUI.
  • NewsRob – RSS/Atom reader that syncs with Google Reader. I like the interface – it’s simple but powerful
  • NetCounter – a simple network traffic counter for EDGE/3G and WiFi.
  • TuneWiki – music player with many options (it can even show lyrics of currently listened song).  It can also stream music from last.fm which is great.
  • Aldiko – an eBook (ePub file format) reader for Android with option to download books from internet.
  • WordPress – it allows us to manage (write posts, create pages, moderate comments) our WordPress blog.

Hello World!

I was thinking about my own blog for a long time and I decided finally to write it.  I would like to test here if I’m able to share my knowledge and opinions with others. I don’t have a big experience in public speeches or writing articles, so this is a good place to train it

Mainly I will be writing here about .Net framework and C# language, but also about other computer staff like tools, hardware, interesting sites and so on. I hope you enjoy it!

I apologize in advance for any grammatical errors but I’m not native speaker of English. I hope to continually improve my language skills.