Sina Iravanian

I blog about software development

Moved My Blog to Octopress

| Comments

I’ve moved my blog from Wordpress to my homepage domain. It makes use of Octopress, which is based on Jekyll, and is a static site generator. The blog is hosted on GitHub pages, and is open source.

The great benefit of this stack of tools is that I can easily create and edit my posts in Markdown, re-generate the blog through command line, and make use of Rake (Ruby’s make tools) to perform various tasks ranging from post creation to deployment to GitHub pages. It’s awesome.

How to Make More Refactoring Friendly Data-bindings With C# 5

| Comments

Imagine that we want to create a Person business object for whose properties we desire a two-way data binding. The source-to-target data-binding can be triggered by implementing INotifyPropertyChanged interface, like this:

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
public class Person : INotifyPropertyChanged
{
    private string _name;
    private double _age;

    public string Name
    {
        get
        {
            return _name;
        }

        set
        {
            if (value != _name)
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
    }

    public double Age
    {
        get
        {
            return _age;
        }

        set
        {
            if (_age != value)
            {
                _age = value;
                OnPropertyChanged("Age");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

See how the setters pass the property name in a string. This is not nice, because whenever we change the property name through refactoring tools, the string value remains untouched and we have to manually change them as well (if we are lucky enough to get notified before run-time). Anyway we had to tolerate them for years…

C# 5 comes with a nice feature, which is addition of two attributes [CallerFilePath] and [CallerMemberName] in the System.Runtime.CompilerServices namespace. If you decorate an optional string parameter of a method with one of these attributes, then the value of that parameter will be replaced with the caller’s file name or the caller’s member name at runtime, if no explicit value is passed for the optional parameter. They come very handy in logging scenarios, but we can use the latter for making our data-binding code nicer. This is how:

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
public class Person : INotifyPropertyChanged
{
    private string _name;
    private double _age;

    public string Name
    {
        get
        {
            return _name;
        }

        set
        {
            if (value != _name)
            {
                _name = value;
                OnPropertyChanged();
            }
        }
    }

    public double Age
    {
        get
        {
            return _age;
        }

        set
        {
            if (_age != value)
            {
                _age = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName]string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Now that string constants are removed from the setters we can more freely refactor our code. After being spoiled by automatic properties, this is still a very verbose way of defining properties; however it is much better than before.

Different Ways of Generating New GUIDs

| Comments

In C# Code

1
var newGuid = Guid.NewGuid();

In Visual Studio

Go to: Tools > Create GUID

In SQL Server Management Studio

Execute either of the following queries:

1
SELECT NEWID()

or

1
PRINT NEWID()

None of the above

Go to newguid.com, and refresh the page as many times as you want.

An Example for C# Dynamic in Action

| Comments

Recently I was involved with enabling validation for a Windows Forms form containing several pages shown through a tree view. There were one user control defined for each page, therefore whenever a node in tree-view got activated, an instance of that user-control were shown. The user-controls did not have a common user-defined parent base-class or interface. The author of the existing code had defined a Save method in each control separately which performed updating data with values entered in the forms.

First, I changed all void Save() methods to bool Save(), and performed the validation stuff in each control separately. Then in the parent form, I created an array of Controls, so that I could loop through them, and call their Save method. But wait, Save is not inherited from any base-class or interface, so there’s no polymorphism at hand. How can I call them through references of type Control?

Well honestly, the best solution would be adding a new interface to the project, say ISavableControl or something, add the Save method to it, and let the controls implement that interface. But I wanted to make a quick fix to the problem without adding new files and types to the code. Here C#’s dynamic comes into action.

Using dynamic keyword, one postpones binding methods, properties, and fields to run-time. In our scenario we know that the user-controls each have a method called Save, which is not derived from a parent. Without dynamic, I would need to have a reference explicitly from each user control’s type, and I would have to call them one by one, as in:

1
2
3
4
5
6
bool succeeded = false;
succeeded = userControl1.Save();
succeeded = succeeded || userControl2.Save();
succeeded = succeeded || userControl3.Save();
// ...
succeeded = succeeded || userControln.Save();

However using dynamic keyword, life gets a lot easier:

1
2
3
4
5
6
7
8
9
10
// objects are not inherited from a base class or interface,
// therefore we cannot call Save using polymorphism
bool succeeded = false;
foreach(var ctrl in controlsArray)
{
    dynamic dynCtrl = ctrl;
    succeeded = succeeded || dynCtrl.Save();
}

// do something with the value of succeeded

Take care that binding the Save methods to controls happen at runtime. Therefore if a control does not implement a Save method, or if another one misspells Save, as say Svae, you will get no hints at compile time. So, try to avoid this style of coding, unless you have good reasons for doing so.

Programming Koans: One of the Best Ways to Learn a New Language or Framework

| Comments

Based on Wikipedia, originally a Koan in Zen-practice is a paradoxical question that provokes doubt and tests a student’s progress. On the other hand, programming Koans are a set of failing unit-tests, for which the learner is required to fix the code or fill the required fields with proper values in order to make each test pass. Probably one of the earliest and most popular Koans were Ruby Koans. Now there are several Koans implemented for different languages and frameworks. Search the word “Koan” in GitHub or BitBucket and you will find the gems.

My first experience of Koans was MoqKoans, a great set of Koans for learning Moq, a mocking library for the .NET framework. That was really a wonderful learning experience. These days I’m trying to strengthen my web programming skills, and as one of the early steps I decided to remaster JavaScript. I found two JavaScript Koans on GitHub; both of them are great. However, I suggest that one should start with the JavaScript Koans by Liam McLennan, which is easier to begin with. after finishing this step, I highly recommend proceeding with theJavaScript Koans by David Laing. This one is a smaller set of Koans, but gets more advanced, and contains an introduction to Underscore.js as well.

Experience the joy of learning with Koans, and having all the reds going green in the end.

Using Git With GitHub on Windows

| Comments

If you’re new to Git and don’t know how to install Git on Windows, read my earlier post: How to Setup Git for Windows

In an earlier post, I described the preliminary steps required to work with git on CodePlex. However using git withGitHub requires more initial steps.

Generating SSH Keys. Before proceeding to Git operations we need to create SSH public and private keys, and register the public key on the GitHub site. In order to generate the keys we can use PuTTY Key Generator, which is already bundled with TortoiseGit fortunately. This program is called “Puttygen” and can be found in start-menu under TortoiseGit:

puttygen under TortoiseGit in Windows start-menu

After running Puttygen you need to press “Generate”, and make some crazy mouse movements in the spotted area to provide some random data for the program (wow, what a brilliant idea). When finished you will have the public key generated. It is recommended that you provide a passphrase so that you would have a more secure private key. After that save your public and private keys using the 2 save buttons near the bottom of the window. But these are not all that you need to save! The public key format that GitHub and some other applications require you to provide is not the one that this program has saved for you. The topmost field which is labelled “Public key for passing into OpenSSH authorized_keys file” is the one that GitHub needs. It should be in one line (i.e., with no line-breaks), therefore we would refer to it later as the one-line-public-key. Please save the contents of this field and the next “key fingerprint” field somewhere for future references.

Puttygen fields

Registering SSH Keys in GitHub. Browse to GitHub, and go to your Account Seetings, and select SSH Keystherein. Press the Add SSH key button on the right. Provide a name for the key (I chose TortoiseGit), and paste the one-line-public-key in the Key field. Press Add Key. You may be prompted for your GitHub account password next. When finished, GitHub adds this key to its list of keys and provides a fingerprint. Make sure this fingerprint matches the key fingerprint that Puttygen created for you.

Creating a Repository in GitHub. Browse to the GitHub page and press the “Create a New Repo” button at the top of the page.

GitHub Create New Repo

In the new form that appears, enter desired values for your project’s name and description. Currently there’s an option to add a README file or an appropriate .gitignore file to the repository. While making use of these options are recommended, in this tutorial I intend to start from a completely empty repository; therefore I unchecked those options. When finished press the “Create repository” button. With these steps I created a project called “PdfRenamer”.

Setting up TortoiseGit for the new project. After creating the repository, GitHub introduces some helpful basic commands to start working with the repository. We don’t intend to use the command-line, however this page contains useful information such as user-name and email with which GitHub recognizes you, and the git repository address, as highlighted below:

GitHub New Project Address And User-Name

We need to do the following steps next:

  1. Right click somewhere in the Windows explorer window, and from the context-menu go to: TortoiseGit > Settings Git branch; and fill the user-name and email fields with the ones suggested by GitHub, and press OK.
  2. Create a folder preferably with the same name as your project (in my case PdfRenamer), and browse into it with Windows explorer.
  3. Right click somewhere in the folder and from the context menu select “Git Create repository here…”. A window pops-up. Make sure that “Make it Bare” is not checked; and press OK.
  4. Right click somewhere in the folder and from the context menu go to: TortoiseGit > Settings Git branch Remote sub-branch. In the “Remote” field enter “origin”, in the URL field enter the git repository address which was highlighted above and is in the form of git@github.com:[username]/[projectname].git; and finally in front of “putty key” provide the address to the SSH private key which we saved earlier in this tutorial, and has the .ppk extension. When finished press the “Add New/Save” button. After that origin should be added to the list of Remotes.

TortoiseGit Remote Setting

Add files to the project structure. With git, adding a file to a project structure and having it reflected in the remote repository requires 3 operations: add, commit, and push. The first 2 operations are required for adding the file to the local repository, and the third one reflects the changes to the remote repository. This last operation can be postponed to a later time when you want to push a bundle of changes all at once.

To start, create a Readme.txt file in the root folder. Right click on the newly added file, from the context menu select: TortoiseGit > add; check the files to be added, and press OK. This was the first operation: add. In the new window press “commit …”, provide a meaningful commit message in the new window, and press OK when finished. This was the second operation: commit which reflects the changes to your local repository, the one in your hard-drive. You can push the changes in the next window if you want, however it’s not a good idea to push every local commit to the remote repository (that’s why we are using a DVCS after all).

Before continuing to the push command, let’s talk about some naming conventions in the Git world. With DVCSs such as git you can have different remote repositories which you may choose from to push your changes to. By convention, the default name for the remote repository is “origin”. In our case origin is the remote repository at the GitHub server, for which we manually added the link before. On the other hand, each project may have several branches. Conceptually a branch is another copy of the same project where other features are developed and tested. For example imagine that at a certain stage of development you may decide to add a new feature to your project. You may create a new branch called “test”, develop and test the feature there, and finally merge the changes with the code at the main branch. By convention, the main branch is called “master”.

When it comes to push, you need to know which branch of the code you want to push to which remote repository. In our simple case we want to push the master branch to the origin repository. For this purpose, right click somewhere on the Windows explorer that shows the project root folder, and select: TortoiseGit > Push…. Make sure the name of the branches for local and remote repositories and the name of the remote repository are selected correctly. More importantly make sure that the “Autoload Putty Key” check-box is also checked, and press OK. Next, the TortoiseGit will prompt you for the private-key passphrase. Note that this is not your GitHub account password, this is the passphrase that you chose when creating the private key with Puttygen. After finishing the push operation, check the sources in the project’s GitHub page to make sure the changes have been reflected there. Note that after the first push, the PuTTY authentication agent (Pageant) gets run in the background, so that you won’t need to enter the passphrase any time you want to push to GitHub.

Updating the local repository with the latest changes made by other team members to the remote repository. Well, there are two solutions. The one that I prefer is using git pull. You can easily find this command in the TortoiseGit’s context menu. The pull command, preserves the history of changes made by different people and makes a final merge afterwards. The other solution is git fetch and rebase. The fetch command only receives the latest changes from the remote repository but does not apply them. The rebase command first applies the remote changes to the repository, then applies your changes. Therefore it always seems that you have made the recent changes, while it may not be true. See this stackoverflow question for a better explanation.

Note: At any stage, if git complains about connecting through a null proxy, then you will have to remove proxy settings from the global .gitconfig file. For more information see tip 7 on my earlier post

You may also want to see my earlier post that describes using git with CodePlex on Windows.

Using Git With CodePlex on Windows

| Comments

If you’re new to Git and don’t know how to install Git on Windows, read my earlier post: How to Setup Git for Windows

On 21 March 2012, the CodePlex team announced their support for Git.

Creating a project with Git as source control is very easy in CodePlex and is done with a few clicks at no time. Suppose the project name is CodePlexGitTest. In order to make any changes to the project structure you need to clone the project first. This way you will have your own copy of the repository on your hard disk. To do this, the path to the git repository is needed. This can be obtained from the Source Code tab of the project’s CodePlex page, by pressing the Git link/button under “Source Control” section on the right pane, as seen below:

CodePlex Git settings

In order to clone the project, move to the folder that is going to host the project directory. Right click somewhere in the Windows explorer window and choose Git Clone. In the opened window set the “Url” field to the “Clone URL” value above, leave other options unchanged, and press OK. After prompting for your CodePlex user-name and password, it should now create the folder structure for your empty repository (Note: in case that git complains about connecting through a null proxy, then you will have to remove proxy settings from the global .gitconfig file. For more information see tip 7 on my earlier post).

Now that you have the currently empty project structure at your hard-drive, it’s time to add some files to it. Using git, adding a file to a project structure and having it reflected in the remote repository requires 3 operations: add, commit, and push. The first 2 operations are required for adding the file to the local repository, and the third one reflects the changes to the remote repository. This last operation can be postponed to a later time when you want to push a bundle of changes all at once.

To start, create a Readme.txt file in the root folder. Right click on the newly added file, from the context menu select: TortoiseGit > add; check the files to be added, and press OK. This was the first operation: add. In the new window press “commit …”, provide a meaningful commit message in the new window, and press OK when finished. This was the second operation: commit which reflects the changes to your local repository, the one in your hard-drive. You can push the changes in the next window if you want, however it’s not a good idea to push every local commit to the remote repository (that’s why we are using a DVCS after all).

Before continuing to the push command, let’s talk about some naming conventions in the git world. With DVCSs such as git you can have different remote repositories which you may choose from to push your changes to. By convention, the default name for the remote repository is “origin”. In our case origin is the remote repository at the CodePlex server. On the other hand, each project may have several branches. Conceptually a branch is another copy of the same project where other features are developed and tested. For example imagine that at a certain stage of development you may decide to add a new feature to your project. You may create a new branch called “test”, develop and test the feature there, and finally merge the changes with the code at the main branch. By convention, the main branch is called “master”.

When it comes to push, you need to know which branch of the code you want to push to which remote repository. In our simple case we want to push the master branch to the origin repository. For this purpose, right click somewhere on the Windows explorer that shows the project root folder, and select: TortoiseGit > Push…. Make sure the name of the branches for local and remote repositories and the name of the remote repository are selected correctly, and press OK. Enter CodePlex user-name and passwords which are prompted. Now check the sources in the project’s CodePlex site to make sure the changes have been reflected there.

How to update the local repository with the latest changes made by other team members to the remote repository? Well, there are two solutions. The one that I prefer is to use git pull. You can easily find this command in the TortoiseGit’s context menu. The pull command, preserves the history of changes made by different people and makes a final merge afterwards. The other solution is git fetch and rebase. The fetch command only receives the latest changes from the remote repository but does not apply them. The rebase command first applies the remote changes to the repository, then applies your changes. Therefore it always seems that you have made the recent changes, while it may not be true. See this stackoverflow question for a better explanation.

See also:
How to Setup Git for Windows
Using Git With GitHub on Windows

How to Setup Git for Windows

| Comments

These are some easy steps required to setup Git for Windows:

  1. Download msysGit from: http://code.google.com/p/msysgit
    I prefer to use the portable version. At the time of this writing there’s no difference between 32 bit and 64 bit versions and the filename for the portable version is: PortableGit-1.7.10-preview20120409.7z. Currently it seems that the development of the project has been moved to GitHub, but the releases are still located in Google Code.

  2. Extract the contents in a proper location. I made them into:
    D:\PortableProgs\msysGit

  3. If you intend to use the git command-line for every git operation simply run git-bash.bat in the root folder of msysGit. This is the old lovely Cygwin command-line.

  4. If you don’t intend to use command-line (like me) install TortoiseGit. It is hosted on Google Code:
    http://code.google.com/p/tortoisegit/
    Note that it comes with different releases for 32-bit and 64-bit systems. At the time of this writing the latest version is 1.7.8.0. After installing TortoiseGit you may need to restart Windows, or the Windows explorer process, or none.

  5. Right click somewhere on a Windows Explorer window, and from the context menu select: TortoiseGit > Settings. There will be a message-box appearing begging for adjusting the path to msysGit. Click on “Set MSysGit path” button (If you have ever missed this window, or want to change the path to an already existing msysGit, simply go to: TortoiseGit > Settings the General branch).
    In the field titled as “Git.exe path:” enter the path to the bin folder of the msysGit installation/copy.

  6. You don’t have to, but it is highly recommended that before starting any git operations you set some global settings such as your name, email, and AutoCrlf. To this aim in the Windows explorer’s context menu go to: TortoiseGit > Settings the Git branch. Fill in the fields labelled Name and Email with proper values. Then make sure that AutoCrlf check-box is unchecked, so that you don’t touch every file in order to change their line-endings. Read more about this kind of problem here, and see here to know more what AutoCrlf and SafeCrlf options do for you.

  7. [UPDATED on 3 May 2012] When performing some git operations, git may complain that it cannot connect through a null proxy. It may happen for some versions if in git settings the value for proxy is assigned to an empty string. If this is the case for you, simply remove proxy settings in the global .gitconfig file. To do this, right click somewhere in Windows explorer, go to: TortoiseGit > Settings The Git Branch Edit Global .gitconfig button. From there remove the line that assigns proxy, or the whole [http] section if it only contains proxy settings.

See also:
Using Git With CodePlex on Windows
Using Git With GitHub on Windows

How I Built My First Qt Application in Visual Studio 2010

| Comments

I downloaded the Qt SDK (offline installer version which was 1.7 GB) from: http://qt.nokia.com/downloads

At the time of this writing, the Qt libraries version was 4.7.3.

Then I downloaded the VS-Addin, using the link at the bottom of the downloads page, titled “Qt Visual Studio Add-in”.

After installing both SDK, and the VS-Addin on my system, I started Visual Studio 2010. I tried to create a sample project by selecting: File > New > Project… > Qt4 Projects > Qt Application, and specified proper values for Name and Location. After going through the Qt wizard to the end, I encountered the following error message:

unable to find Qt Build!
To solve this problem specify Qt Build!

By going to the Qt setup directory, one sees that there are Qt SDKs available for different target platforms. For example I installed Qt in “D:\QtSDK” and in that directory I see some folders which correspond to different target platforms such as Desktop, Madde, Symbian, and others. An appropriate platform directory should contain a bin folder inside. This is true about Madde, and Symbian, but the Desktop folder is a root for subdirectories related to different Qt versions and C++ compilers. Since I wanted to develop Qt applications with Microsoft Visual C++ for the Windows Desktop platform I went to the following directory which contains the required bin folder: D:\QtSDK\Desktop\Qt\4.7.3\msvc2008

For the next step, I had to introduce this directory for the Qt VS-addin. From the main menu, I selected Qt > Qt Options > Qt Versions. I pressed the Add button, and entered “Win 4.7.3” in the “Version name” field, and entered the above path in the “Path” field, and pressed OK. The path that I specified was added to the gird. Then I made sure that in the Default Qt/Win version, the version that I have just specified (i.e., Win 4.7.3) is selected. I pressed OK, and tried once more with the Qt New Project wizard. This time everything went OK, and I succeeded to create and build my first Qt Application in the VS 2010 environment.

Note: In fact the current Qt binaries are targeted for Visual Studio 2008. I was able to use the binaries (i.e., libs and dlls) because I had also Visual Studio 2008 and the corresponding C++ compiler installed on my machine. Otherwise, I presume that I would need to recompile the sources with the VS-2010 C++ compiler.