Logging Experiences

A JavaScript Primer

Posted in JavaScript, Programming by Sina Iravanian on May 28, 2012

These are lessons learned when I tried to strengthen my JavaScript skills, by learning from these Koans:

  1. JavaScript Koans by Liam McLennan, hosted on GitHub
  2. JavaScript Koans by David Laing, again hosted on GitHub

I highly recommend learning from both of these Koans in the same order as specified above. The first one is easier to start with. While the second one is a smaller set of Koans, but gets more advanced, and contains an introduction to Underscore.js as well.

I come from a C#, Java, and C++ background, so that it’s probable that my terminology is not consistent with those used by the JavaScript community; particularly when it comes to object oriented concepts.

To test the code snippets here, you will need to host the JavaScript code within an html page, and open that page into your browser. A simple way is using the following template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script language="javascript" type="text/javascript">
            // TODO: put other JavaScript codes here
            console.log("Hi");
        </script>
        <title>JavaScript Testing...</title>
    </head>
<body>
    <h1>Let's See...</h1>
</body>
</html>

The examples in this post make use of console.log function to print to the output. To view the results on the browser console do the following in each browser:

  • Google Chrome (19.x and most probably others): Press F12, and go to the Console tab
  • Mozilla Firefox (12.0 and most probably others): go to Firefox main menu > Web Developer > Web Console (Ctrl + Shift + K)
  • Microsoft Internet Explorer (9): Press F12, and go to the Console tab

Basic Concepts

Comparison and Equality. Comparison via == Considers equality, regardless of type.

Comparison via === checks identity, and types must match. Always use this syntax, if possible.

Corresponding inequality operators are: !== and !=== . These are some examples of the behaviour of the equality operator:

console.log(3 == "3");  // true: equality with type correction
console.log(3 === "3"); // false: equality without type correction
console.log(3 === 3);   // true
console.log(3 === 2+1); // true

More examples for odd behaviours of == operator. The result to all the examples below would be false if we use === instead of ==:

console.log(0 == false);  // true
console.log(true == 1);   // true
console.log(true == 5);   // *false*
console.log("" == false); // true
console.log("" == 0);     // true

Note that NaN (short for not a number) is never equal to itself! It must always be checked using the function isNaN.

Strings enclosed in single-quotes and double-quotes are the same. Note that in JavaScript there’s no such thing as character data-types.

console.log("something" === 'something'); // true

Global variables are assigned to the window object:

function() {
    temp = 1; // note that it does not start with `var`
    equals(temp, window.temp, 'global variables are assigned to the window object');
}

Creating objects from anonymous types:

var person = {
        name: "John Doe",
        age: 27
    };

Enumerating properties of an object with the for in loop:

var person = {
    name: "John Doe",
    age: 27
};

var result = "";
// for in enumerates the property names of an object
for (property_name in person) {
    result = result + property_name + " ";
};
console.log(result); // name age

Null coalescing operator: The same as C#’s ?? operator, is logical OR || in Javascript. If the first argument (the one at left-hand-side of ||) is null, it chooses the second argument (the one at the right-hand-side of ||):

var result = null || "a value";
console.log(result); // a value

See this wondoerful explanation here.

Sinagle vs Double quoted strings. They are the same and of the same type.

console.log("str1" === 'str1'); // true

tyepof. It receives an object as an argument and returns its type (as opposed to C#, it does not need the type-name as the argument).

typeof(2) -> number
typeof(2.0) -> number
typeof("Hi") -> string
typeof('Hi') -> string
typeof('H') -> string
typeof("Hi".charAt(0)) -> string
typeof(false)-> boolean
typeof(null) -> object

As you see, there’s no such thing as character type, they’re all strings.

The type informations are also strings:

typeof(typeof(2.0)) -> string

How to include unicode chars in a string.

var stringWithAnEscapedCharacter  = "\u0041pple";

The string slice method. returns a substring of the given string. This is the syntax of the method [+]: string.slice(start,end).

  • start: Required. The index where to begin the extraction.
  • end: Optional. The index (up to, but not including) where to end the extraction, If omitted, slice() selects all characters from the start-position to the end of the string.

NaN (short for not a number) is the result of failed arithmatic operations. Two NaN objects are not equal to each other, always use the isNaN function to check.

var resultOfFailedOperations = 7/'apple';
console.log(isNaN(resultOfFailedOperations)); // true
console.log(resultOfFailedOperations == NaN); // false

Objects

Empty objects (no properties, no methods): var empty_obj = {};

Objects can have properties in definition:

var myObject = {
    name: "John Doe",
    age: 28
}; 

Or properties can be added later:

var myObject = {};
myObject.name = "John Doe";
myObject.age = 29;

Properties can be added from strings dynamically:

var myObject = {};
myObject["name"] = "John Doe";
myObject["age"] = 28;

Objects can have methods, and fields can be accessed via the this qualifier:

var myObject = {
    name: "John Doe",
    age: 28,
    toString: function() {
        return "I'm " + this.name + ".";
    }
}

Properties can be accessed by their name in the code, as in: myObject.name or accessed from a string at run-time, as in: myObject["name"].

Arrays

Arrays can contain objects from different types:

var favouriteThings = ["cellar door", 42, true]; 
// array elements do not have to be of the same type
// elements are referenced by [] indexer
// favouriteThings[1] -> 42
// array type is "object"
// typeof(favouriteThings) -> "object"
// the length is accessed via `.length` property

Creating arrays with a predefined length:

var arr = new Array(10);
console.log(arr.length); // 10
console.log(arr); // [undefined × 10]

Or one can explicitly assign to the array.length property. Note that if the new value is less than the original array size, the trailing elements will be removed:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
arr.length = 5;
console.log(arr.length); // 5
console.log(arr); // [1, 2, 3, 4, 5] 

Note: The for in loop in arrays, iterates through the indices only, not the values.

Arrays are passed to functions by reference. Therefore any change to the passed array in the body of the function will modify the original array too. Also when assignments are done, the reference to tha array is assigned, hence this also has the risk of modifying the original array:

var arr = [0, 1, 2, 3, 4, 5];
function changeArray(someArray) {
    someArray[1] = 10;
}
changeArray(arr);
console.log(arr.toString()); // [0, 10, 2, 3, 4, 5]
var anotherArr = arr;
anotherArr[4] = 40;
console.log(arr.toString()); // [0, 10, 2, 3, 40, 5]

You can create a copy of an array using arr.slice().

Array join method creates a string by concatenating all array members using the provided separator:

var arr = [1, 2, false, 4.5, "hi"];
console.log(arr.join(","));
// 1,2,false,4.5,hi

Array slice method. Returns the sub-array of a given array, from the first index inclusive, to the second index exclusive; or returns an empty array if the provided indices do not match a valid range within the provided array:

var arr = [0, 1, 2, 3, 4, 5];
var sub = arr.slice(2, 4);
// [2, 3]

The slice function, when called without arguments creates a copy of the array. Changing the copied arrays elements will not affect the original array’s contents.

var copyOfArr = arr.slice();

Array splice method. The splice method adds/removes items to/from an array, and returns the removed item(s) if any [+].

Syntax: array.splice(index,howmany,item1,.....,itemX)

Parameter Values:

  • index: Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array
  • howmany: Required. The number of items to be removed. If set to 0, no items will be removed
  • item1, ..., itemX: Optional. The new item(s) to be added to the array

Return Value:

Type: Array; A new array containing the removed items, if any

This is a demo of splice. Note that, only when we remove items from an array, the method returns the removed items.

var array1 = [];
console.log("Empty Array:\n" + array1.toString());

var array2 = [1, 2, 3, 4];
console.log("Array2:\n" + array2.toString());

var array3 = array2.splice(2, 0, 2.25, 2.5, 2.75);
console.log("array2 after additive splice():\n" + array2.toString());
console.log("returned array from additive splice():\n" + array3.toString());

var array4 = array2.splice(2, 3);
console.log("array2 after deductive splice()\n" + array2);
console.log("returned array from deductive splice()\n" + array4);

//Empty Array:
// 
//Array2:
//1,2,3,4 
//array2 after additive splice():
//1,2,2.25,2.5,2.75,3,4 
//returned array from additive splice():
// 
//array2 after deductive splice()
//1,2,3,4 
//returned array from deductive splice()
//2.25,2.5,2.75

Array stack methods: push and pop. Javascript arrays have push and pop methods. push inserts at the end of an array, and pop removes from the end of an array. The push function can receive more than 1 argument to add to the end of an array.

Array unshift and shift methods. The unshift method inserts one or more items at the beginning of an array, while shift removes one item from the beginning of an array [+, +].

Functions

This is the way a named function can be defined in JavaScript:

function fname() {
    // body
}

But the following syntax, is assigning a variable to an anonymous function:

var fn = function() {
    // body
};

and as seen above we receive a warning if we don’t put a semicolon after the closing brace. That’s because it is just an assignment statement, but a little bit fatter.

Invokation of both is the same: fn(), and fname().

typeof(fn) -> "function"
typeof(fname) -> "function"

The toString method of each function returns the signature and the body of a function as well as its comments. See the result of fn.toString() or fname.toString() to get amazed.

The Function object. An alternative way to defining functions is creating an object from Function, and providing all the details in arguments as strings, e.g.:

var add = new Function("a", "b", "return a + b;");
console.log(add(1, 2)); // 3

Functions can return functions. See this nice example from JavaScript Koans by David Laing:

function makeIncreaseByFunction(increaseByAmount) {
    var increaseByFunction = function increaseBy(numberToIncrease) {
        return numberToIncrease + increaseByAmount;
    };
    return increaseByFunction;
}
var increaseBy3 = makeIncreaseByFunction(3);
var increaseBy5 = makeIncreaseByFunction(5);
console.log(increaseBy3(10) + increaseBy5(10)); // 28;

Reflection

Properties of an object can be accessed at run-time via the for in loop. This function, prints the properties of an object as well as their values:

function printProps(obj) {
    console.log("{");
    for (var propName in obj) {
        console.log(propName + ": " + obj[propName]);
    }
    console.log("}");
}

The in keyword, when not used along with the for loop, can be used to check whether an object has a specific property with the given name:

var obj = { name: "John", age: 29 };
var hasName = "name" in obj;     // true
var hasFamily = "family" in obj; // false

Object Constructor functions: A function with a typical signature, but used for initializing objects. These functions usually assign fields using the this qualifier. Note that after each assignment, the specified field will be created, it doesn’t need to be declared beforehand:

function fnObject() {
    this.name = "John";
    this.age = 23;
}

The above code can be regarded as the constructor of an object, with 2 fields namely name, and age. This is how we can instantiate this object with the new keyword:

var obj = new fnObject();

You can add properties at runtime to an instantiated object, not the class/prototype, via this syntax: obj["newprop"] = "newvalue";

How to add properties to a class/object prototype? Via the prototype chain. E.g., to add a property to the fnObject statically (namely weight) use the following syntax. The property will be added to all instances of the class:

fnObject.prototype.weight = 75.0;

To do the same job dynamically use the following syntax:

fnObject.prototype["weight"] = 75.0;

To add a set of properties which currently exist in another class, simply set the prototype property with a new instance of that class. For example:

function fnObj2() {
    this.salary = 20.0;
    this.eyeColor = "Brown";
}

fnObject.prototype = new fnObj2();

Then objects from fnObject will have the following properties: {name, age, salary, eyeColor}. This reminds us of inheritance.

As another example, take a look at this piece of code from JavaScript Koans by David Laing, that demonstrates attaching a function to an object vs to a class (or object prototype):

function Circle(radius)
{
    this.radius = radius;
}
var simpleCircle = new Circle(10);
var colouredCircle = new Circle(5);
colouredCircle.colour = "red";
console.log(simpleCircle.colour); //undefined
console.log(colouredCircle.colour); // red
Circle.prototype.describe = function () {
    return "This circle has a radius of: " + this.radius;
};
console.log(simpleCircle.describe());
// This circle has a radius of: 10
console.log(colouredCircle.describe()); 
// This circle has a radius of: 5

How to tell which property belongs to the orignial class of the object, and which one has been added through the prototype chain? This can be checked with the hasOwnProperty method of the object. For example:

var obj2 = new fnObj2(); // as defined above
obj2.hasOwnProperty("name") // -> true
obj2.hasOwnProperty("salary") // -> false

The eval() method. Runs the JavaScript code, that is stored in a string:

var result = "";
eval("result = 'apple' + ' ' + 'pie'");
// result equals "apple pie" after eval

Inheritance and Prototype Chain

Many of the materials in this section are taken form [+] (a must read):

A “constructor” in JavaScript is “just” a function that happens to be called with the new operator.

Object.create method. Calling this method creates a new object. The prototype of this object is the first argument of the function.

This is an example:

var father = {
  b: 3,
  c: 4
};

var child = Object.create(father);
child.a = 1;
child.b = 2;

// child has properties "a", and "b" as its own
// child.prototype <- father
// child has properties "c", and (shadowed) "b"
// from its prototype i.e., not its own

Property Shadowing. Is something like method overriding. For example in the code above, property b from object child, hides the effect of property b from object father. This is called shadowing.

Removing a property from an object can be achieved by calling delete. For example removing property b from object child is accomplished by calling:

delete child.b;

Doing this would neutralize the shadowing effect, and the child.b property would be that of its prototype, not of its own.

The call method calls a method from an object, but with a different this provided. This is the syntax (many parts taken from [+]):

FuncToCall.call(theNewThis, arg1, arg2, ...);

Consider this example (adapted from reference above):

var animals = [
  {species: 'Lion', name: 'King'},
  {species: 'Whale', name: 'Fail'}
];

for (var i = 0; i < animals.length; i++) {
  (function(i) {
      console.log('#' + i + ' ' + this.species + ': ' + this.name);
  }).call(animals[i], i);
}

It defines a dynamic function which prints information from this.species and this.name. It then calls the function replacing this with each array item.

Another usage for call is chaining constructors (as in C# or Java we can call other constructors to do the initialization and then we do the rest). This is an example (again taken from reference above):

function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0)
    throw RangeError('Cannot create product "' + name +
         '" with a negative price');
  return this;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

In the above example we reused construction logic of Product for Food and continued further. However this technique emulates inheritance too. To make it look like a real inheritance we set Product as the prototype for Food:

Food.prototype = new Product();

Since functions such as call and apply, allow you to set the callers this context, you should not expect any more that this is a user-defined type; this can be anything, a string, or even a numeric:

var invokee = function( message ){
    return this + message;    
};

var result = invokee.call("I am this! ", "Where did it come from?");
console.log(result);
// "I am this! Where did it come from?

See also this nice example taken from JavaScript Koans by Liam McLennan:

var person = {
    handle: 'bob',
    intro: function () {
        return "Hello, my name is " + this.handle;
    } 
}

// calling a function with 'call' lets us assign 'this' explicitly
var message = person.intro.call({handle: "Frank"});

The apply method operates just like call, except that it sends the arguments to the invokee function through an array:

var invokeeFunc = function( a, b ) {
    return this + a + b;
};
// using apply
var sum1 = invokeeFunc.apply(1, [2, 3]);
// using call
var sum2 = invokeeFunc.call(1, 2, 3);
// sum1 == sum2 == 6

Emulating maps with objects

One can define objects to have a map functionality, e.g.,

var map1 = { 0: "Zero", 2: "Two" };
console.log(map1[0]); // zero
console.log(map1[2]); // two
console.log(map1[1]); // undefined

var map2 = { "zero": 0, "two": 2 };
console.log(map2["zero"]); // 0
console.log(map2["two"]); // 2
console.log(map2["one"]); // undefined

Self-invoking functions

This is how we can define and call a function in one statement:

//(func_definition)(func_arguments);
var theMessage = "Hello World!";
(
    function(msg) { console.log(msg); }
)(theMessage);

The arguments map

Every function, whether having defined a set of arguments or not, will have access to the arguments passed to it, through the arguments map. The arguments map, maps the argument index to its value, and has a length property:

var add = function() {
    var total = 0;
    for(var i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
};

In JavaScript, you can pass any arguments of any type, and any number, to any function (no need to match the number of arguments with the parameters list). You can always access them through the arguments map.

Regular Expressions

In JavaScript, regular expressions are objects instantiated from RegExp. However, one can create regular expression objects easily with syntactic sugars integrated into the language. Using them, regular expression objects are a special kind of string which are delimited within two slashes /pattern/ instead of quotation marks, reminding unix style regular expression search programs and commands.

var regex = /\d+/;

This has the benefit that the programmer does not need to escape the backslash characters in the pattern (something like at-quoted strings in C#). For example the equivalant object for the above pattern is:

var regex = new Regexp("\\d+");

Besides the pattern, one can make use of flags or modifiers which modify the behaviour of the regular expression engine [+]:

  • i: Perform case-insensitive matching
  • g: Perform a global match (find all matches rather than stopping after the first match)
  • m: Perform multiline matching

These flags can come after the closing slash of the pattern, or inside a string as the second argument to the RegExp constructor. For example the following defines a regular expression pattern that is going to find all of its mateches within a given string case-insensitively:

// words beginning and ending in "a" or "A"
var regex = /a\w*a/gi;
// ... or ...
var regex = new Regexp("a\\w*a", "gi");

The exec method returns the matches of the whole regular expression as well as its groups. For example the following regular expression for matching words starting and ending with the character “a” returns also the “a” characters themselves, because they have been defined within a group (i.e., inside parantheses). Note that upon calling it returns only the first match, if any:

var regexp = /(a)\w*(a)/;
var results = regexp.exec("1. ABA 2. aba 3. aca!");
if(results != null) {
    console.log("index: " + results.index + " found [" + results + "]");
} else {
    console.log("Not found!");
}
// index: 10 found [aba,a,a] 

To find all the matches, we have to carry out these two steps: 1) add the g (global) flag to the regular expression pattern. 2) call exec iteratively until it returns null. Note that without adding the g flag, the second step will be trapped within an infinite loop. The following example looks for all words (hence the g flag) beginning and ending in the letter “a”, case-insensitively (hence the i flag):

var regexp = /(a)\w*(a)/ig;
var input = "1. ABA 2. aba 3. aca!";
var results = regexp.exec(input);
while(results != null) {
    console.log("index: " + results.index + " found [" + results + "]");
    results = regexp.exec(input);
} 
// index: 3 found [ABA,A,A]
// index: 10 found [aba,a,a]
// index: 17 found [aca,a,a] 

The test method tests whether a string contains a pattern:

var doesItContain = /ye(s|ah)/.test("He said: yeah!");
console.log(doesItContain); // true

The string match method returns the match(es) of the specified regular expression within the caller string:

var matches = "1. ABA 2. aba 3. aca!".match(/(a)\w*(a)/ig);
console.log(matches);
//["ABA", "aba", "aca"] 

The string replace method replaces the instances of the found pattern within the given input string and returns the new string:

var result = "1. ABA 2. aba 3. aca!".replace(/(a)\w*(a)/, "oops");
console.log(result); // 1. ABA 2. oops 3. aca! 
// add "ig" flags -> case-insensitive global replace
result = "1. ABA 2. aba 3. aca!".replace(/(a)\w*(a)/ig, "oops");
console.log(result); // 1. oops 2. oops 3. oops! 

One of the beauties of the replace method is that it can receive a function as the second argument, so that we can decide dynamically on what to replace with each single instance of the found pattern:

var result = "1. ABA 2. aba 3. aca!".replace(/(a)\w*(a)/ig, function (found) {
    if (found[0] == "A") {
        return "OOOPSS";
    } else if (found[1] == "b") {
        return "oobs";
    } else {
        return "oocs";
    }
});
console.log(result); // 1. OOOPSS 2. oobs 3. oocs! 
Advertisements

Programming Koans: One of the best ways to learn a new language or framework

Posted in Programming by Sina Iravanian on May 27, 2012

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 the JavaScript 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.

YAXLib is Now Hosted on GitHub Too

Posted in Programming by Sina Iravanian on May 14, 2012

YAXLib is an XML serialization library which focuses on XML formatting, and creating human-editable results. To know more about YAXLib read this CodeProject article. It was originally hosted on CodePlex, under the SVN source-control. Now, hoping more contribution from the community, the source-control of YAXLib on CodePlex is changed to Git. Besides, YAXLib is hosted on GitHub too. So, feel free to fork YAXLib on either CodePlex or GitHub.

Tagged with:

Using Git with Github on Windows

Posted in Git by Sina Iravanian on May 5, 2012

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 with Github 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 labeled “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 Keys therein. 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) get’s run in the background, so that you won’t need to enter the passphrase anytime 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

Posted in Git by Sina Iravanian on May 4, 2012

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 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:

Git Repository Information on CodePlex

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 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.

See also:
How to setup Git for Windows
Using Git with Github on Windows

How to setup Git for Windows

Posted in Git, Programming by Sina Iravanian on May 1, 2012

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. Yes, 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 at 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 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 labeled 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

Tagged with: , ,