Saturday, September 4, 2010

Git on Windows with Console and PowerShell

Windows people like to do everything on their computers using GUI tools and WYSIWYG editors. And nothing is wrong with that. Personally, I like this approach – it conserves time while giving fast access to the most used options of a given tool (at least usually). Consider the SVN version control system. Initially, it was a console-based tool, but thanks to the great TortoiseSVN project, people may now forget about the command line. However, working with Git is different. Git was designed to be used from the command line, and using it in that way is a pure pleasure! Git commands are well crafted and easy to remember. If you are holding out on Git because it doesn’t give you the right GUI tools, you are holding out for a wrong reason.

Git comes with a bash like prompt which is very powerful. However, there is one problem. The bash prompt is launched within the standard Windows command line, and as probably anyone knows, the command prompt on Windows is one, big misery. So in this post I’m going to address this issue by showing how to set up a convenient command line environment for Git on Windows.

Installing Git

Git can easily be installed on Windows. Head over to http://code.google.com/p/msysgit/ and download Git-1.7.0.2-preview20100309.exe which is the latest version of Git as of this writing. When the installer asks about [Adjusting the PATH environment], select [Run Git from the Windows Command Prompt] as shown on the following screen.

clip_image001

Selecting this option allows to use Git from different shells, like PowerShell. Now that Git is installed, we can open a command line and verify it’s there.

clip_image003

We can also right click any folder in the Windows Explorer and select Git Bash Here – this will launch Git’s default bash shell.

clip_image005

Installing Console

Now it’s time to get rid of the ugly prompts shown above. Head over to the http://sourceforge.net/projects/console/ and download the latest version of the Console project. Launch it, and go to Edit->Settings, select Console from the tree on the left and pick up a new shell – the PoweShell. Under Windows 7/2008, it is located at %Windows_Dir%\System32\WindowsPowerShell\v1.0\powershell.exe. On previous versions of Windows, I believe it must be downloaded separately. Click OK and close the Console. Now launch it again, but this time with Administrator privileges, and issue the following command: [Set-ExecutionPolicy Unrestricted]. This command will allow running custom PowerShell scripts, which is needed for Git integration. Now you have a working PowerShell within nice, tabbed environment. We’re almost there!

Installing PoshGit

It’s time to enable PowerShell-Git integration. To do that, download Posh-Git latest sources available at http://github.com/dahlbyk/posh-git and unpack them to %Sys_Drive%:\Users\%Login%\Documents\WindowsPowerShell. Change profile.example.ps1 to profile.ps1. Hurray! You have enabled Git integration! What does it give? When you are inside Git repository, the command prompt changes to show on which branch you are, and whether there are any modifications, and if there are any untracked files (via exclamation mark). To enable output coloring, issue the [git config –global color.ui auto] command.

clip_image007

Enjoy your cool, command line interface for Git!

Thursday, September 2, 2010

Sharp3D – The Beginning

Back when I was on holidays, I’ve read a post by Maciej Aniserowicz about the “Daj się poznać” contest. The aim of the contest is to write an open source project of any kind in any technology, and blog about it at least twice a week, for ten weeks period. There’s also pretty nice collection of software to win. And because a crazy idea is floating in my head for a while, I thought – why don’t give it a try?

So what am I going to create? I’m going to build a research application for manipulating 3D objects, perhaps with the ability to define materials for them, modify existing objects, add new objects to the scene, and render them using custom crafted raytracing algorithm. As if this were not enough, application will fully support multi-touch displays.

Currently, I have a basic skeleton of the application, with my own scene objects (I want to abstract from WPF elements). Here’s the screenshot from the initial drop.

Sharp3D

Motivation

There are a couple of reasons I’m writing this project. By no means, the most important thing for me is to learn strong basics of 3D programming. Triangles, tessellation, normals, materials, lightning, raytracing and more – there is a whole bunch of 3D stuff to master. I also want to learn this in context of WPF 3D – hope this will help me in building better looking apps in the future. I also want to see if the WPF 3D is suitable for project which does more than displaying 3D cubes with buttons on the sides. And last but not least – 3D programming is fun!

Goals

I want Sharp3D to be an extensible foundation for writing 3D applications by others. Thus, the main goal is the extensibility and component design. The application will span several components which can be used in standalone manner – this will support others in developing their own 3D applications! I want to provide many ways of interacting with the 3D model. So besides the standard mouse and keyboard, I will utilize multi-touch capabilities of today’s monitors, and the Wiimote. Because editing capabilities, if any, will be very limited, an important part is to write a loader which will take existing scene and import it to the program. I plan to implement 3ds file importer, because this is de facto the standard in the 3D industry – all known modeling applications support it. Having that, another cool feature will be XAML exporter.

Tools

Because this is a research project, I’m going to use the latest and greatest tools available J This includes:

· .NET Framework 4.0

· Visual Studio 2010

· WPF 4.0

· Blend 4.0

· Git

· Multi-touch / Wiimote

Sources

I decided to use Git which is a fast, distributed version control system. The distributed means that the code repository lives not only on the server (which by the way is not a requirement) but on the user’s computer. This allows committing changes locally, and then pushing them back to the server. When using Git, the natural choice for open source repository is GitHub. The Sharp3D sources can be found at http://github.com/pwlodek/Sharp3D.

There are two important branches. The most important is the master branch. It will contain, latest, stable version. The development will be done on the dev branch. Besides, I will try to use the branch-per-feature approach, which I presume is self-explanatory. After I decide a feature is complete, it will be merged into dev branch, and then into master.

Contribution

If you are interested in contributing to the project – you are more than welcome! Just drop me an email so we can discuss the details. To begin your contribution, register on GitHub and fork the main repo and work on your part. Once ready, issue a pull request – and I will do the rest ;) The one thing is that I won’t pull till the end of the contest as the participants are supposed to work on their own.

Thursday, May 13, 2010

Lazy<T> and IEnumerable<Lazy<T>> support comes to Unity

If you are familiar with .NET Framework 4.0 or Managed Extensibility Framework, you probably know that there's a type called Lazy<T> which enables lazy instantiation. This type comes in handy when used with any form of dependency injection. Instead of injecting a concrete instance of a service or whatever you want, you can inject instance which wraps the requested type and instantiates it only when the program really needs to use it. Consider the following code which uses - guess what - MEF =)
[Export]
public class Account
{
[Import]
public Lazy<ILogger> Logger { get; set; }

public void Deposit(decimal amount)
{
if (amount < 0)
{
Logger.Value.Log("Amount is less than 0.");
}
}
}
Here you can see a fragment of an Account class implementation which has an ILogger instance injected in lazy manner. As long as the Deposit method is not invoked with a value less than 0, the logger instance is not used, thus, it is actually not created at all! Lazy instantiation is particularly usefull when you are dealing with objects which are expensive to create.

There are some IoC containers which support Lazy<T> out of the box, namely Autofac 2, or Managed Extensibility Framework to name a few (I don't like calling MEF an IoC container, it's rather a composition engine since it is not constrained to inject types, but methods, fields and properties as well - sorry for that). Unfortunately, Unity IoC (even the latest Unity 2.0) is not on that list. Yes, I know. Unity 2.0 has a support for a concept known as automatic factories (you can read more on that here). Basically speaking, automatic factories allow to pull Func<T> - which is a delegate to a function which returns the concrete instance of the requested component when called. The idea is to fire this delegate when the instance is really needed. So you can say this serves the same purpose as Lazy<T>. Yeah, but it is not Lazy<T> ;) Besides, having the ability to pull Lazy<T> enables even better usage of the Unity+MEF integration layer, which is a part of MEF Contrib initiative. You can always find lates sources hosted on github.

OK. How to leverage the Lazy<T> and IEnumerable<Lazy<T>> ? This is a piece of cake. There are three ways of using the extension. If you want to pull a single component, here's how to do that:
unityContainer.RegisterType<IComponent, Component1>();
var lazyComponent = unityContainer.Resolve<Lazy<IComponent>>();
If you want to pull all components registered under a common type, you can do the following:
unityContainer.RegisterType<IComponent, Component1>("component1");
unityContainer.RegisterType<IComponent, Component2>("component2");
unityContainer.RegisterType<IComponent, Component3>();

// A collection of non-lazy components
var collectionOComponents = unityContainer.Resolve<IEnumerable<IComponent>>();

// Lazy collection of components, once resolved, all the components get resolved
var lazyCollectionOfComponents = unityContainer.Resolve<Lazy<IEnumerable<IComponent>>>();

// Concrete collection of lazy loaded components
var collectionOfLazyComponents = unityContainer.Resolve<IEnumerable<Lazy<IComponent>>>();;
One thing to note. Resolving an IEnumerable is not the same as calling ResolveAll! ResolveAll returns only named types, whereas IEnumerable returns everything!
Either way, before you can use anything presented so far, you have to add the extension the the container. It is as simple as calling:
unityContainer.AddNewExtension<LazySupportExtension>();

An important, and nice thing as well, is that the presented stuff is already the part of MEF Contrib. If you use MEF+Unity integration layer, you automatically get this behavior out of the box!
The code sample can be downloaded, as always, from my code gallery here. Enjoy!


kick it on DotNetKicks.com

Tuesday, November 24, 2009

MEF Contrib for Silverlight 3 (Unofficial)

I’m happy to announce that I’ve completed porting the most recent MEF Contrib (0.7) project to SL3. The project has also been updated to use the most recent MEF release which is beta 2 (Preview 8) as of this writing. All the unit tests from the project pass in the SL environment, here are the screenshots:

image image image

Before I dig into the changes I had to make in order to make it work on SL3, I will focus on NUnit for SL.

As all of you probably know, it is possible to run NUnit tests in SL environment. Microsoft has released a library called Microsoft.Silverlight.Testing which enables developers to execute tests on SL’s CLR. This library ships out of the box with the implementation of MS Tests. However, its extensibility allows to write custom providers for other testing frameworks. Jeff Wilcox wrote a post about running NUnit tests in the SL environment here. He did two things: ported a subset of NUnit to SL, and wrote a provider which enables running NUnit tests using Microsoft.Silverlight.Testing framework. However, his NUnit implementation is very limited, so I googled a little and found a guy who ported NUnit 2.5.1 to SL (you can find his post here). So, for the testing purposes I used mentioned NUnit 2.5.1 SL port together with a provider developed by Jeff. I must admit here, that I’m not sure whether all the features from NU 2.5.1 work correctly in the SL environment. Hopefully, it seems that all the Assert methods including Assert.That and Throws work as expected.

As far as MEFContrib project is concerted, I didn’t have to introduce many modifications. MefContrib.Extensions.Generic project runs without any changes. MefContrib.Integration.Unity project didn’t need to be changed in terms of its implementation. However, all stubs used in unit tests were declared as internal, and it seems MEF for SL has some troubles while instantiating non public members (or SL policy doesn’t allow this?) so most tests were failing. Fortunately, changing access to public repaired everything :) The story is a bit different for the MefContrib.Models.Provider project. This project adds to MEF custom provider model with three programming models built on top of it. These three programming models are

  • Attributed – as it name suggest, parts are registered using attributes,
  • Configurable – parts get registered via App.config,
  • Fluent – parts are registered through method invocation.

The problem lays in the Configurable programming model, because it is implemented using System.Configuration namespace, which is not available to SL programmers. Thus, MefContrib.SIlverlight does not support this model.

The last trouble I had was with two test, which reside in MemberInfoServicesTests test fixture, namely

  • GetMemberInfoShouldReturnMemberIfMemberNameIsSupplied,
  • GetMemberInfoShouldReturnTypeIfMemberNameNotIsSupplied.

Both unit tests test MemberInfoServices class. Both were throwing an exception telling that the test assembly (MefContrib.Models.Provider.Tests) cannot be loaded or the assembly has already been loaded but the versions doesn’t match. To cut the long story short, it turned out that the following code was the root cause (code like the presented below is executed in MemberInfoServices.GetMemberInfo method in both tests) :

Type.GetType("MefContrib.Models.Provider.Tests.FakePropertyPart, MefContrib.Models.Provider.Testsl", false, true)
Don’t know why this doesn’t work. However, a simple modification like follows did the job :)

Type.GetType("MefContrib.Models.Provider.Tests.FakePropertyPart, MefContrib.Models.Provider.Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", false, true)
To maintain separate versions of both tests for regular CLR and SL, I used SILVERLIGHT compiler flag.

Please note that this version is an unofficial release, not available through codeplex.com site. However, I will put an effort to make this an official release or make next MefContrib release based on this one.

Full source code is available on my code gallery here.

Saturday, November 21, 2009

Watermark effect for WPF’s TextBox and ComboBox controls

Update

I have updated this sample to contain the watermark effect for the ComboBox control too. Its implementation is almost identical to the TextBox’s one. Here are the screens showing the effect being applied to the ComboBox control:

image image

And here comes the original post.

In this post I’m going to show a nice watermark effect for WPF’s TextBox control. Sample application (link to the sources at the end of this post) looks as follows:

image image

As you can see, non focused text box containing no text, displays a useful clue to the user informing what kind of information should be entered. Focusing a textbox immediately removes that clue.

There are probably as many ways to introduce such a behavior as there are developers all over the world :) However, one particular solution is to be considered in this case. The above effect has been achieved using adorners. The adorner used for the effect contains a single TextBlock with optional style applied to it. A good introduction to adorners is available here.

The effect has been implemented using attached behavior pattern, so no inheritance was introduced.

Using the behavior is a piece of cake. Here’s how to apply the behavior to a TextBox control:

<TextBox Height="25" Margin="0,5,0,5"
Behaviors:WatermarkTextBoxBehavior.EnableWatermark="True"
Behaviors:WatermarkTextBoxBehavior.Label="Label"
Behaviors:WatermarkTextBoxBehavior.LabelStyle="{StaticResource watermarkLabelStyle2}" />

The first property, EnableWatermark, as its name suggests, enables the effect ;) The Label property holds the text to be displayed as a watermark. Finally, the LabelStyle property contains the style to be applied to the label. And the style, defined in Window’s Resources collection, might look as follows:


<Style x:Key="watermarkLabelStyle">
<Setter Property="TextBlock.Foreground" Value="{x:Static SystemColors.ControlDarkBrush}" />
<Setter Property="FrameworkElement.Opacity" Value="0.8" />
<Setter Property="TextBlock.FontSize" Value="12" />
<Setter Property="TextBlock.FontStyle" Value="Italic" />
<Setter Property="TextBlock.Margin" Value="8,4,4,4" />
</Style>

I’m not going to discuss any implementation details here since the adorner itself is trivial, and the behavior is quite easy as well. Maybe I will tell you that the watermark is displayed when the TextBox fires its Loaded event. Why is that important to know? Keep reading… ;P Besides, skim the code and you immediately know how stuff works :)

Finally, one thing, which deserves to give attention to, is control loading and the adorner layer (adorner layer is a place always rendered over the control where all adorners for that control get displayed). When a control is contained within a portion of UI that is being displayed, but the control itself is not visible, it normally fires Loaded event, but because it is not visible, it has no adorner layer! So don’t assume that call to AdornerLayer.GetAdornerLayer(Visual) always returns the adorner layer! This is why the sample shown above contains a TabControl – the second tab, named Tab 2, contains a TextBox with the watermark effect applied to it, and this still works :)


As always, code sample is available through my Code Gallery here.

Saturday, August 22, 2009

Improved MEF + Unity Integration Layer

In my last post about Managed Extensibility Framework and Unity DI container I proposed a solution to make both frameworks work together in tandem, which in turn lets the developer leverage all the features from them at the same time. Now, the improved version is out, and it's a part of the MEFContrib project!

Having learned from developing the previous version, I decided to reimplement the integration layer from the ground up. The API changed very little, though ;)

The "biggest" change since the initial version is that you no longer need to provide boolean parameter during component registration in Unity to say that you want the component to be available to MEF. Now, this is done automatically using Unity container extension. So, the initialization of the layer now is super easy as it requires only single line of code :) Consider this:

// Setup
var unityContainer = new UnityContainer();
var aggregateCatalog = new AggregateCatalog();

// Register catalog and types
unityContainer.RegisterCatalog(aggregateCatalog); // this call initializes the layer
unityContainer.RegisterType<IUnityOnlyComponent, UnityOnlyComponent1>();


The first call to RegisterCatalog method does the initialization - under the hoods, ComposiotionContainer is created, and a link between it and Unity is established. Pretty easy, huh ? :)

Next, all the types are public, so for example, if the standard RegisterCatalog method doesn't fit your needs, you can easily create your own using all the provided types as building blocks. The one concrete use case that comes to my mind is that the current implementation of the RegisterCatalog method does not allow you to attach any additional export providers (your own root CompositionContainer for instance) to the underlying CompositionContainer. In such a case, you can easily create separate method which accepts export providers and initializes the layer. Investigating RegisterCatalog method might be beneficial :)

One neat implication of having all types public is that you can now establish one-way synchronization, being MEF to Unity, in which Unity container knows about MEF parts and can resolve them, and Unity to MEF, in which MEF can pull Unity's components.

Finally, I've added support for closed generics, i.e. you can pull components from Unity and MEF using generics.

The usage of this layer is quite well described on MEFContrib wiki page.

kick it on DotNetKicks.com

Friday, July 10, 2009

Statically Typed Dependency Properties

Recently, I found a nice post written by a friend of mine, regarding statically typed property names. His post can be found here. What I simply did was to put his concept into WPF world :)

Problem

Typical registration of a WPF's dependency property looks like follows:

public int MyInteger1
{
get { return (int)GetValue(MyInteger1Property); }
set { SetValue(MyInteger1Property, value); }
}

public static readonly DependencyProperty MyInteger1Property =
DependencyProperty.Register("MyInteger1", typeof(int), typeof(Window1));

Hmm, what's wrong with it ? It "breakes" the DRY (Don't Repeat Yourself) principle. Given code defines a property named MyInteger of type int, but this information is coded twice, in the property itself and during its registration. If you want to change the name or type of a single property, you have to update the code in two places.

Solution

Now consider the following code:

public int MyInteger2
{
get { return (int)GetValue(MyInteger2Property); }
set { SetValue(MyInteger2Property, value); }
}

public static readonly DependencyProperty MyInteger2Property =
DependencyPropertyHelper.Register<Window1>(t => t.MyInteger2);

What has changed here is the way the property is registered. Now, changing the name or the type of a property is done through its getter. Nice, isn't it ? This approach works with both regular and read only properties but does not with attached properties, because the latter does not use property to access its value but uses methods instead. Implementation behind the Register<TOwner> method used above is fairly simple and looks like this:

public static class DependencyPropertyHelper
{
public static DependencyProperty Register<TOwner>(
Expression<Func<TOwner, object>> property)
{
return DependencyProperty.Register(typeof(TOwner).GetPropertyName(property),
typeof(TOwner).GetPropertyType(property),
typeof(TOwner));
}
}

GetPropertyName and GetPropertyType methods come from the post I've mention at the beginning.

Full code can be downloaded from my code gallery.