Git, SSH Agent and PowerShell

I’m writing this post to thank Mark Embling by the insightful post on how to setup SSH Agent inside PowerShell.

It saved me a lot of time, and helped me keeping my git workflow inside PowerShell. So, if you are still using bash, get his PowerShell script and give it a try.

Categories: Uncategorized Tags: , ,

iPhone UI Templates and Vector Elements

May 25th, 2010 Vasco Oliveira No comments

Here are three useful resources for those who are prototyping iPhone apps. To give your demos a realistic look, you can download these iPhone UI elements, available in three different formats:

 

Adobe Illustrator Vector Elements (.ai) – Mercury Intermedia Blog

Download iPhone UI Vector Elements Now (2.6MB)

 

Adobe Photoshop (.psd)- teehan-lax Blog

Download The iPhone GUI PSD Here (9MB)

 

OmniGraffle - Graffletopia

http://graffletopia.com/stencils/413

 

ui_vector_preview_01_thumb[1]  ui_vector_preview_02_thumb[1] ui_vector_preview_03_thumb[1]

 

You can also get them in XAML format through Mike Swanson’s Adobe Illustrator to XAML Export plugin.

Categories: Uncategorized Tags:

Perf Tools for WPF 4 now available

May 25th, 2010 Vasco Oliveira No comments

The perf tools for WPF 4.0 are now available for download, and you can use them for profiling both 3.5 and 4.0 applications.

The tools are included in the Windows SDK 7.1 for Windows 7 and .NET Framework 4.

Categories: Uncategorized Tags:

mdf is Compressed But Does not Reside in a Read-only Database or Filegroup. The File Must be Decompressed.

May 21st, 2010 Vasco Oliveira No comments

Last night I loaded a massive ASP.NET 2.0 project I did some years ago in VB.NET. It used a SQL 2000 database for data storage, so I had to attach the mdf file to get it to work. So I opened SQL Server Management Studio, opened a connection to the server instance, and went for the Attach database option.

When I selected the file, the following error came up:

“Store.mdf is Compressed But Does not Reside in a Read-only Database or Filegroup. The File Must be Decompressed.”

So here’s a quick tip for anyone who faces a similar issue. It took a few seconds to understand the problem but then I remembered file compression options. Opened my mdf file properties dialog box, and in the advance tab the problem was revealed: the “compress content” checkbox was checked.

After unchecking and saving changes, SQL Server accepted the attach with no problem whatsoever.

Categories: Uncategorized Tags:

Runtime Intelligence support in VS2010

May 9th, 2010 Pedro Pombeiro No comments
Visual Studio 2010 comes with support for adding Runtime Intelligence to your software out-of-the-box (courtesy of PreEmptive Solutions). Runtime Intelligence allows you to implement something like Microsoft Office’s Customer Experience Improvement Program (think of it as the desktop equivalent of web analytics). I have tried this with Scrum Sprint Monitor, and it really is as

Refactoring: Extracting the Singleton Pattern

May 4th, 2010 Pedro Sampaio No comments

With this post I will be starting a series of posts on refactoring. The purpose is to use real production code (whenever possible) as a start point and improve it, instead of just random pointless examples.

Starting point

So the main class we will be changing is the DeviceManager. This class manages a collection of Devices (or a dictionary, to be more precise) and allows us to set which is the active device and to get a device by id. Note that this last feature could be handled by the Devices collection, but we are taking advantage of the dictionary to make that look-up more efficient.

One of the key points is that it has a singleton Instance property, that we use throughout the code.

namespace PSampaio.Refactoring.Example1.Old
{
	using System.Collections.Generic;
	using System.Linq;

	public class DeviceManager
	{
		private static DeviceManager deviceManager;
		private static readonly object singletonLock = new object();
		private readonly Dictionary<string, Device> devices;

		public static DeviceManager Instance
		{
			get
			{
				lock (singletonLock)
				{
					if (deviceManager == null)
					{
						deviceManager = new DeviceManager();
					}
					return deviceManager;
				}
			}
		}

		public Device ActiveDevice { get; set; }

		public IEnumerable<Device> Devices
		{
			get { return devices.Values.AsEnumerable(); }
		}

		public DeviceManager()
		{
			devices = new Dictionary<string, Device>();
		}

		public void AddDevice(Device device)
		{
			if (!this.devices.ContainsKey(device.DeviceId))
			{
				this.devices.Add(device.DeviceId, device);
			}
		}

		public bool RemoveDevice(Device device)
		{
			var result = false;
			if (this.devices.ContainsKey(device.DeviceId))
			{
				result = this.devices.Remove(device.DeviceId);
			}
			return result;
		}

		public Device GetDeviceById(string id)
		{
			Device device;
			if (!devices.TryGetValue(id, out device))
			{
				device = null;
			}
			return device;
		}
	}
}

Then we have the actual Device. This class was edited down to the basics, as the real behavior of the Device is not important. For example purposes, it just has an Id that we use to index it in the dictionary.

namespace PSampaio.Refactoring.Example1.Old
{
	public class Device
	{
		public string DeviceId { get; private set ; }

		public Device(string id)
		{
			DeviceId = id;
		}
	}
}

The ActiveDeviceSupport class is the one that uses both the DeviceManager and the Devices. Again, for example purposes, this only sets the first Device we have on the DeviceManager as the ActiveDevice.

namespace PSampaio.Refactoring.Example1.Old
{
	using System.Linq;

	public class ActiveDeviceSupport
	{
		public void SetFirstDeviceAsActive()
		{
			var devices = DeviceManager.Instance.Devices;
			var firstDevice = devices.FirstOrDefault();
			if (firstDevice != null)
			{
				DeviceManager.Instance.ActiveDevice = firstDevice;
			}
		}
	}
}

And finally, we have the set of unit tests run against the DeviceManager. In case you are wondering, yes, these are the actual tests (albeit being slightly edited to protect the innocent) that we have for these classes.

namespace PSampaio.Refactoring.Example1.Old
{
	using System.Collections.Generic;
	using System.Linq;

	using Microsoft.VisualStudio.TestTools.UnitTesting;

	[TestClass]
	public class Tests
	{
		[TestMethod]
		public void AddDevice()
		{
			var devices = new List<Device>();
			for (var i = 1; i < 5; i++)
			{
				var device = new Device(string.Format("Device {0}", i));
				devices.Add(device);
				DeviceManager.Instance.AddDevice(device);
			}
			var thirdDevice = DeviceManager.Instance.GetDeviceById("Device 3");
			Assert.AreSame(devices.First(d => d.DeviceId == "Device 3"), thirdDevice);
		}

		[TestMethod]
		public void ListDevices()
		{
			var devices = DeviceManager.Instance.Devices;
			Assert.AreEqual(4, devices.Count());
		}

		[TestMethod]
		public void RemoveDeviceTest()
		{
			var devices = DeviceManager.Instance.Devices;
			var device = devices.ElementAt(2);
			Assert.IsTrue(DeviceManager.Instance.RemoveDevice(device));
			devices = DeviceManager.Instance.Devices;
			Assert.AreEqual(3, devices.Count());
			Assert.IsFalse(DeviceManager.Instance.RemoveDevice(device));
		}

	}
}

So what’s wrong with the code? The short answer is: a lot!

Fixing the Singleton instance… and removing it

Lets start by analyzing the Singleton instance. The first thing we need to consider when implementing a Singleton instance is whether we really need it, as it’s very likely we don’t. If we do, we should at least implement a double-check lock. See this MSDN page and this Stack Overflow question for more information. Please note that this implementation has to be done just right, so be careful when writing it. I’ve read the block of code below a couple of times, and I think it’s correct, but you never know.

Here’s what we ended up with. Don’t just copy/paste it!

private static volatile DeviceManager instance;
private static readonly object instanceLock = new object();
public static DeviceManager Instance
{
	get
	{
		if (instance == null)
		{
			lock (instanceLock)
			{
				if (instance == null)
				{
					instance = new DeviceManager();
				}
			}
		}

		return instance;
	}
}

In this case, we won’t be needing the Singleton instance so we will just remove this code altogether.

Depend on abstractions

The reason we don’t need the Singleton instance is twofold. First, it limits our ability to test any behavior that uses the DeviceManager (more on this later). Secondly, it forces us to depend on the concrete implementation of the DeviceManager, while what we want is to depend on abstractions. This way, we can promote the cohesiveness of our classes without having a tight coupling between them.

This is better stated in the book Agile Software Development – Principles, Patterns, and Practices by Robert “Uncle Bob” Martin. He calls this the Dependency-Inversion Principle:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.

In order to do this, we need to extract an interface from DeviceManager.

namespace PSampaio.Refactoring.Example1.New
{
	using System.Collections.Generic;
	using System.Linq;

	public interface IDeviceManager
	{
		Device ActiveDevice { get; set; }
		IEnumerable<Device> Devices { get; }
		void AddDevice(Device device);
		bool RemoveDevice(Device device);
		Device GetDeviceById(string id);
	}

	public class DeviceManager : IDeviceManager
	{
		private readonly Dictionary<string, Device> devices;

		public Device ActiveDevice { get; set; }

		public IEnumerable<Device> Devices
		{
			get { return devices.Values.AsEnumerable(); }
		}

		public DeviceManager()
		{
			devices = new Dictionary<string, Device>();
		}

		public void AddDevice(Device device)
		{
			if (!this.devices.ContainsKey(device.DeviceId))
			{
				this.devices.Add(device.DeviceId, device);
			}
		}

		public bool RemoveDevice(Device device)
		{
			var result = false;
			if (this.devices.ContainsKey(device.DeviceId))
			{
				result = this.devices.Remove(device.DeviceId);
			}
			return result;
		}

		public Device GetDeviceById(string id)
		{
			Device device;
			if (!devices.TryGetValue(id, out device))
			{
				device = null;
			}
			return device;
		}
	}
}

We also need to change the ActiveDeviceSupport class. Instead of having a concrete dependency on DeviceManager, we now depend on an abstraction, and that dependency is explicit. We could later evolve this design to use an IOC container to resolve the dependencies automatically.

namespace PSampaio.Refactoring.Example1.New
{
	using System.Linq;

	public class ActiveDeviceSupport
	{
		private readonly IDeviceManager deviceManager;

		public ActiveDeviceSupport(IDeviceManager deviceManager)
		{
			this.deviceManager = deviceManager;
		}

		public void SetFirstDeviceAsActive()
		{
			var devices = deviceManager.Devices;
			var firstDevice = devices.FirstOrDefault();
			if (firstDevice != null)
			{
				deviceManager.ActiveDevice = firstDevice;
			}
		}
	}
}

Correcting the tests

The tests we started with are a perfect example of how not to do unit testing, as they will only pass if they are run all together and in a specific order. While the first (CanAddDevice) test is isolated, the other two depend on the previous ones passing. Obviously, the tests will fail if we run each one separately. The reason for this is that they depend on the Singleton instance of the DeviceManager. So based on the changes we have been making, we can now write the tests differently.

namespace PSampaio.Refactoring.Example1.New
{
	using System.Linq;

	using Microsoft.VisualStudio.TestTools.UnitTesting;

	[TestClass]
	public class Tests
	{
		[TestMethod]
		public void CanAddDevice()
		{
			const string id = "Device 1";
			var deviceManager = new DeviceManager();
			var device = new Device(id);
			deviceManager.AddDevice(device);
			Assert.AreSame(device, deviceManager.GetDeviceById(id));
		}

		[TestMethod]
		public void CanListDevices()
		{
			const int deviceCount = 4;
			var deviceManager = new DeviceManager();
			for (var i = 0; i < deviceCount; i++)
			{
				var device = new Device(string.Format("Device {0}", i));
				deviceManager.AddDevice(device);
			}
			Assert.AreEqual(deviceCount, deviceManager.Devices.Count());
		}

		[TestMethod]
		public void CanRemoveDevice()
		{
			var deviceManager = new DeviceManager();
			var device = new Device("Device 1");
			deviceManager.AddDevice(device);
			Assert.AreEqual(1, deviceManager.Devices.Count());
			deviceManager.RemoveDevice(device);
			Assert.AreEqual(0, deviceManager.Devices.Count());
		}
	}
}

As you can see, each test is now isolated from the others, testing a specific code path in the DeviceManager. There are still changes that we could make, namely the for loop in the ListDevices test and the fact that we call IDeviceManager.AddDevice on the CanRemoveDevice test, but I’m OK with leaving it like that for now.

As a positive side-effect, if we need to test the ActiveDeviceSupport class, we don’t depend on DeviceManager anymore, so we can just mock the IDeviceManager interface and test ActiveDeviceSupport in isolation also.

Hope this helps!

Microsoft announces Kin I and Kin II Windows Phones

April 13th, 2010 Vasco Oliveira No comments

Kin I and Kin II

It’s here, and it’s finally official. Microsoft recently announced two Windows Phone devices called Kin I and Kin II, the outcome of the highly rumored Microsoft Project Pink.

 

They both feature Windows Phone OS, but differ in hardware specs. Kin II it’s the biggest, featuring 8Gb memory, 8Mp camera that records 720p video, while KIN I has a smaller form factor and features a 5Mp camera with full VGA Video. It’s been said that battery life will last an entire weekend. But this is still subject of testing, you know how marketing works, right?

 

The new OS is very much social oriented. It’s main screen, called Loop shows all your contacts strictly organized and somewhat optimized from a User Experience point of view. Personally, It won’t do much to me, since I use my personal devices in a more professional level, but it’s great for social usage scenarios.

 

Other than this, it seems sharp will be the device manufacturer for the 1st round, and both devices will be available in

Vodafone Spain, Italy, Germany and Uk.

Categories: Uncategorized Tags: ,

How to configure Git on Windows

In the previous article, I’ve shown how to install Git on Windows 7, but before you can start using it, there’s some basic configuration that needs to be done.

In this article I’ll show how to setup your user name and email address, and configuring external tools like Notepad++ and Beyond Compare to edit your comments and to visualize changes in your code.

Before proceeding, open Cygwin bash shell (Start –> All Programs -> Cygwin -> Cygwin Bash Shell).

Setting user name and email

Git needs to know your user name and email address to properly credit your commits,

$ git config --global user.name "Your Name"
$ git config --global user.email your@email.com

NOTE: The “email” setting doesn’t need to a valid email address, it only needs to match the “user@server naming scheme.

this will setup your user name and email address globally within Git. If you want, you can override this settings on a per-repository basis:

$ cd your_repository
$ git config user.name "Your Name"
$ git config user.email your@email.com

 

Setting the core editor

To properly use Notepad++ editor, you need to create a wrapper script “git-core-editor.sh” with the content,

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar -nosession $*

and save it at the path “C:\Cygwin\usr\local\bin”.

Now, lets proceed with the editor configuration:

$ git config --global core.editor /usr/local/bin/git-core-editor.sh

The next time you commit something,

$ git commit

Notepad++ will show up, type your comments, save and close.

Setting the diff tool

Similar to the editor configuration, you also need to create a wrapper script “git-difftool-warpper.sh” with the content,

#!/bin/sh
REMOTE="$(cygpath -w "${1}")";
LOCAL=${2};
echo Launching BComp.exe $REMOTE $LOCAL
"C:/Program Files (x86)/Beyond Compare 3/BComp.exe" $REMOTE $LOCAL

and save it at the path “C:\Cygwin\usr\local\bin”.

Now, lets proceed with diff tool configuration:

$ git config --global diff.tool bc3
$ git config --global difftool.bc3.cmd "git-difftool-wrapper.sh \"\$LOCAL\" \"\$REMOTE\""
$ git config --global difftool.prompt false

To visualize your code changes

$ git difftool <file_name>

That’s all you need to start using Git.

Shout it

Categories: Uncategorized Tags: ,

New Visual Studio 2010 Feature: Pin To Source

March 30th, 2010 Vasco Oliveira No comments

A cool feature in Visual Studio 2010 is Pin To Source. This command is available in the Visual Studio code editor context menu and allows you to create a kind of little “Post-It!” on your code showing variable values and expressions that you want to watch during a debugging session. Its very handy:

 

VSPin

 

Just right click on the variable you wish to watch (or create your own expression) and select Pin To Source. And Voilá! A tip shows up with the current inspected value. When you aren’t debugging it all becomes grayed out, just like the Watch window.

 

I’m having a blast with this feature. But use it wisely and if you see yourself creating huge “post-it” farms, you’ll maybe want to consider calling it a day!

 

EDIT: Visual Studio 2010 RC has some issues with this feature though. Pinned variables/expressions get a marking on the left bar of the code editor (where debug markers stay) with a pin icon. In design time you can see their latest values and you also have the options to clear them and arrange them. When doing the later, VS 2010 crashes in all its glory... Another one to get in the bug fixing line to the final release.

 

Technorati Tags:
Categories: Uncategorized Tags: ,

Listing an Element’s Attached Properties

March 24th, 2010 Vasco Oliveira No comments

I was recently confronted with a scenario in witch a xaml element needed to be dynamically replaced and nested in a container control. There’s nothing unusual about this except for the fact that when this happens the element being replaced might have attached dependency properties set on it. Needless to say that in this scenario such operation might have significant impact. Imagine if your element is inside a Canvas panel and has some of its attached properties set, like Canvas.Top or Canvas.Left.

 

My first approach was to go through reflection on the parent and get all DependencyProperties, then invoke GetValue() on the element for each one. It worked but it got me thinking that there had to be a cleaner way, since Attached Property values collection is internal and not directly accessible. Then I got to know a primitive called MarkupWriter. In fact, I’ve crossed with it before on a previous project but never got to actually use it. This time around I’ll make it official, so I’m sharing a little snippet that checks an element for Attached Properties, followed by an example:

public static IDictionary<DependencyProperty, object> GetAttachedProperties(DependencyObject element)
{
    var attachedPropertyList = new Dictionary<DependencyProperty,object>();
    var markupObject = MarkupWriter.GetMarkupObjectFor(element);
    
    foreach (var prop in markupObject.Properties)
    {
        if (prop.IsAttached)
            attachedPropertyList.Add(prop.DependencyProperty, prop.Value);
    }
    return attachedPropertyList;
}

 

Here’s a simple usage example:

var border = new Border()
             {
                 Width = 200, Height = 200, 
                 BorderBrush = Brushes.Blue, 
                 BorderThickness = new Thickness(1)
             };
            
border.SetValue(Canvas.TopProperty, 10d);
border.SetValue(Canvas.LeftProperty, 50d);

var list = GetAttachedProperties(border);

// Beware that ForEach is a Unity enumerable extension.
list.ForEach(prop => Console.WriteLine("Attached property Name: {0}", prop)); 

/* 
Outputs: 
Attached property Name: [Left, 50]
Attached property Name: [Top, 10]   
*/

 

Hope it helps.

 

Technorati Tags:
Categories: Uncategorized Tags: ,