code that works

Thursday, June 20, 2013

In this short post I'll just explain my WebStorm configuration to run my Karma tests inside WebStrom. It's quite simple but can be useful.

These steps assume you can already use karma start at the command line to start watching your project and run your tests. If you don't and wish I'd write a post on that, just let me know in the comments...

1 - Create a new Run configuration for Node.js.

2 - Set the Working Directory to your project root.

3 - Set Path to Node App JS File to the Karma executable.

Type which karma (or where start in Windows) at the command prompt to find Karma's location.

Tuesday, May 29, 2012

Source code on GitHub

Introduction

In this tutorial I'll show you how to create responsive full height columns using the "faux columns" technique.
There are 3 main concepts in that:

Full/Equal height: When you float an element, its height is equal to its content; not to its "context". This causes a problem if you want a sidebar that has a different background-color than the main area because the background will not extend to the same height as the other column(s).

Faux column technique: This is a technique that uses a background-image to create an effect that looks like the column extends to the full height. This technique has been documented several times but this article is a bit different because of the following point.

Responsive: With responsive design, the width of the page set to a fixed size (such as 960px). Instead the content of the page adapts as your make your browser window wider or narrower.

So this tutorial is about using the faux column technique but with the necessary tweaks to make it work in a responsive layout.

The HTML:

The page has a header div, a main div and a footer div. The main div has an article div and a sidebar div on the right side.

2 - Define the two columns using a 70/30 ratio.

Setting the overflow to hidden is not mandatory but I think it looks better when you resize the browser so small that content cannot be wrapped.

3 - Add the faux column effect by setting a background image

This is the key part.

.main {
background: url(opaque-0.70-5000.png)
repeat-y
70%
top;
}

Note that:

The background image is set for the main div; not the sidebar div.

The background image is 5000px wide by 1px high.

The width of the image determines the maximum width that your page will support; beyond that point the faux column effect will break (you can use a larger image if you want but 5000px is really wide).

The height of the image does not matter. If you use an opaque color, then 1px is enough. If you want to use a pattern then you can use a taller image.

In the image, the column start at 70% of the width of the image, at pixel 3500 (5000 * 0.7 = 3500).

The 70% value in the css is the position of the image. Use the same value as the ratio.

This works with any image width. The only thing that matters is you have to start the column effect at the right pixel. For example, if you have a 3000 pixel wide image, your column effect should start at pixel 2100 (3000 * 0.7 = 2100). This example does not fill the right side; there is just 1 pixel at position 2100, which create a vertical line.

.main {
background: url(line-0.70-3000.png)
repeat-y
70%
top;
}

4 - Set a max width for page and add some spacing

As stated in the previous step, the width of the image determines the maximum width the page support. To ensure it will not break beyond that point I set a max-width on the page div. If you don't like the way your site looks when it is very wide, you can set a max-width of 1600px (that's what I usually do).

.page {
width:75%;
margin:auto;
max-width:5000px;
}

5 - Responsive with media queries

You can use css media queries to change the ratio of the columns based on the browser width and for the faux column to work, you will have to change the background image too. For example, if you want a 75/25 ratio when the page is narrower than 600px, you have to:

Create a background-image with a ratio of 75/25. For a 600px wide image, the column must start at pixel 450 (6000 * 0.75 = 450).

Conclusion

I learned a lot in the process of writing this post. I don't consider myself an expert on the matter. Don't hesitate to leave comments if you think the solution can be improved and I will update the post accordingly.

Tuesday, May 22, 2012

This post is written using these tools and libraries: Twitter Bootstrap 2.0.3 | nodejs version 0.6.18 | lessc nodejs module version 1.3.0 | uglifyjs nodejs module version 1.2.6.

Intro
In this very short post I explain how to build twitter bootstrap on windows.

1 - Get the source from github
If you go to the Twitter Bootstrap main page there are several download options. In this case you want to download the source code. Click the View project on GitHub button or visit https://github.com/twitter/bootstrap/ and download the latests version using the ZIP button (or clone the repo using git). Extract the ZIP.

3 - Create make.bat
Create make.bat at the root of the folder where you downloaded the source. Please note that the batch file deletes and recreates a "build" in your working folder. I know this version is not as complete as the real makefile but that is what I use now.

4 - Try it using one of the examples from the Twitter Bootstrap examples page

4.1 - Run make.bat
4.2 - Save one of the twitter bootstrap examples by right clicking on it and selecting "Save as link..." and save it to your source folder.
4.3 - Open the example file in your favorite text editor.
4.4 - Locate this line <link href="../assets/css/bootstrap.css" rel="stylesheet"> and replace it with <link href="/css/bootstrap.min.css" rel="stylesheet">
4.5 - Locate this line <link href="../assets/css/bootstrap-responsive.css" rel="stylesheet"> and replace it with <link href="/css/bootstrap-responsive.min.css" rel="stylesheet">

- Run the test: node hw.jsExpected output: Hello WorldCheck: If you see an error here, something is wrong with your nodejs installation. Check your path maybe...

- Enter npm install less to install the less module. It does not really matter what module you install, this just proves that the package manager called NPM works.Expected outcome: NPM downloading modulesCheck: If you see an error here, something is wrong with your nodejs installation or with NPM.

- Your working directory should have a folder node_modules and a sub folder less.Check: If you don't have those folders then something is wrong with where NPM installs modules.

- To test the module: node node_modules\less\bin\lessc -helpExpected output: a help message from lessCheck: If you get an error, something is wrong with where or how NPM installs modules.

Saturday, February 20, 2010

Note: This post is based on NHibernate version 2.1 with Fluent NHibernate version 1.0 RTM.

In my previous post about Fluent NHibernate, I explained how to use Fluent NHibernate to replace your NHibernate mapping files (.hbm.config) with c# code. In this post I'll show you how to also replace the NHibernate configuation file (.cfg.xml) with code.

This time you don't need to add references to any special library. Converting the config file to code is very, very easy. The config file is made up of a bunch of dictionary entries where each entry has a key (the NHibernate setting name) and a value (the actual value for that setting). The NHibernate has a configuration API that works the same way. So you can just take out the line that loads your config file (config.Configure("PocoLib.cfg.xml");) with a series of calls config.Properties.Add().

This tutorial is based on same project entities defined in my previous NHibernate tutorial. At end of this tutorial, you will have the exact same result but with entities configured using Fluent NHibernate instead of an XML configuration file.

1. Open you the Solution PocoLib.

2. Add a reference to FluentNHibernate in the PocoLibTests

3. Add a new class named CustomerMap.cs to the PocoLibTests project. The source code for CustomerMap.cs is in the left column in the table below. The code speaks for itself; it's almost identical in structure to the XML configuration file.

The Linq() method is an extension method defined in NHibernate.Linq.dll. It provides the entry point to execute Linq queries on your NHibernate entities. When you run that test, NHibernate generates the following statement:

SELECT count(*) as y0_ FROM Customer this_ WHERE this_.LastName like @p0;@p0 = 'St%'

In an upcoming post I will explore the capabilities and limitations of LINQ to NHibernate. For now, here is the full test class I used to discover LINQ to NHibernate:

using System.Diagnostics; using System.Linq; using NHibernate; using NHibernate.Cfg; using NHibernate.Linq; using NUnit.Framework; using PocoLib;

A database running on SQL Server 2005 (changing to another version of SQL server is very simple)

A NUnit test project

1 - Create a new class library project named PocoLib in a new solution. This project will contain your entity classes.

2 - In the same solution, create a new class library project called PocoLibTests

3 - In the PocoLibTests project add references to

PocoLib project

nunit.framework.dll

nhibernate.dll

LinFu.DynamicProxy

NHibernate.ByteCode.LinFu

Note: You do not have to add any references to nhibernate dlls in the PocoLib project. Your entity classes will not have any knowledge of NHibernate; they are real POCO. If you eventually use your entities in a Web app or Web Services project (most likely), it will be that app that will need those same references (except for Nunit of course).

Notice how we are using two classes (Customer and Address) but a single Customer table. It is much cleaner to use two classes at the class design level. But since it is a one-to-one relationship, saving the address in the same table as customer makes total sense (it's simpler, faster and feel more natural).

8 - In the PocoLib project, add an xml file named PocoLib.cfg.xml. That will be your main NHibernate configuration file. It's arguable whether this file belongs to the PocoLib class library or to the host application (the test project in this case), but for now let's put it in PocoLib.

If you are not on SQL Server 2005, you can change the other settings. For instance, set the dialect setting to Nibernate.Dialect.MsSql2008Dialect if your on SQL Server 2008.

9 - In the PocoLib project, add an xml file named Customer.hbm.xml. That will be mapping file used to tell NHibernate where to persist and load our entities. (The same question about where this file should reside applies here too).

The <id> element identifies the primary key column. The <generator class="native"> indicates that SQL Server will generate the primary key value; not NHibernate.

The Customer is defined as a <class> in the mapping. This is what NHibernate calls an entity.

The Address is declared inside the Customer as an<component> element. That basically means that the Address is a part of the Customer and it can't live without a customer. NHibernate components are also know as Value Object in Domain Driven Design.

10 - Copy the PocoLib.cfg.xml and Customer.hbm.xml to the test library \bin\debug\ folder.

11 - Add the missing _factory to the test class. Add this code at the top of the test class:

The 4th line create a factory that we will use to create NHibernate Sessions (a connection)

13 - Run the Insert() test. Go look in the database and be amazed (or not). Notice how SQL statements are written to the output window (If you are using Test Driven at least). You can turn that on or off by changing the <property name="show_sql">true</property> in the .cfg.xml file.

12 - Here are the other CRUD tests. I'm sorry but I don't feel like writing all the Asserts; this is just a test project to experiment with the CRUD operations.

using System.Collections.Generic; using NHibernate; using NHibernate.Cfg; using NUnit.Framework; using PocoLib;

BTW: I started learning NHibernate just a few days ago. I'm wrote this post to serialize what I have learned so far (and hopefully help people at the same time). I'm sure this approach is not ideal. If you have comments on how I could improve this tutorial, just let me know.

Why add an extra element instead of modifying the container div? Because in a real cases, the container div will probably be many levels above the element that you are trying to style. The wrapper div used to compensate should be the immediate parent of that element.

I wrote a jQuery plugin to automatically inject the wrapper div to elements. Here is how to use it:

$(function() { $("#div1").fixFullWidth(); })

The plug-in iterates through at all elements selected by the jQuery selector and wraps each of them in a div that has the correct padding-left value.

Here is the plug-in source. BTW, I'm not a javascript expert so if you come up with a better implementation just let me know and I will update this post.

Saturday, October 3, 2009

At the time of this post, there is a known issue with MonoDevelop's Code Completions feature. At some point, code completion stops working and you get "Gathering class information..." in the code completion drop down list.

Before you apply this workaround, ensure that you have the latest build of MonoDevelop.

Workaround: Manually clear the code completion cache

On a Mac:

Close MonoDevelop

Open the Terminal application

Run this command: rm -r ~/.config/MonoDevelop/CodeCompletionData

Restart MonoDevelop

Note: For some reason, it did not work on my first attempt. MonoDevelop was still "Gathering class information", I listed the content of the CodeCompletionData folder and no files would appear. I did the same procedure again and it worked. So you might have to do this more than once.

Tuesday, September 29, 2009

Two weeks ago Novell released MonoTouch (www.monotouch.net), a SDK to develop in .Net for the iPhone.

I started programming with MonoTouch two days ago. So far I must say I'm impressed. I had absolutely no experience on a Mac before.

Here is a summary of the experience with MonoTouch:

- You need a Mac on which you install:

iPhone SDK from Apple (iPhone Library and Interface Builder)

Mono Framework

MonoDevelop IDE

MonoTouch SDK

- You create user interfaces using Interface Builder, the standard User Interface designer program for Mac/iPhone apps that is part of the SDK.

- You code your logic in C# using an IDE called MonoDevelop which is somewhat similar to Visual Studio and includes code completion. You have access to the C# 3.0 (LINQ, Lambda, Generics) features, Garbage Collection (not offered in the native iPhone SDK) and most general purpose .net APIs. They have wrapped a large portion of the iPhone SDK with a C# friendly API style.

Overall, the experience is quite good. There is one important issue though; there is no debugger (no breakpoints, no watch window, no call stack). You must debug using Console.WriteLine(). I hope Novell will find a way to debug in an upcoming release.

Friday, November 28, 2008

This article explains how to get started with the Unity Application Block using a simple console application. Throughout this tutorial you will learn how to configure and use the "Inversion of Control" and "Dependency Injection" features of the Unity Application Block.

Assumptions

This article assumes that:

You know what DIP, IoC and DI are. You want to configure your type mappings using a configuration file; not using code.

Container

The "Container" or "Inversion of Control Container" is the main object that is used to create objects and inject dependencies into them. Whenever you want an object to be open to IoC, you have to use the container to create the instance using container.Resolve<T>() method instead of the "new" keyword.

IService service = unityContainer.Resolve< IService>();

Create the project and add references to the required assemblies

Create a new console project called UnityTest (if you use another name, you will have to change type names in configuration files so I recommend you stick to this name).

This is the smallest working configuration file you can have for Unity to work. There is one configSections element that describes how .Net should read the upcoming section. There is one, empty, container configuration nested in a containers, nested in a sections called "unity". With this configuration, your will be able to create and configure the container object and then use the container to create objects.

Create and configure the UnityContainer instance

In your project's Main() method, add the following code to create a container instance and configure it by reading the "unity" configuration section defined in the app.config file.

static void Main(string[] args)

{

IUnityContainer container = new UnityContainer();

UnityConfigurationSection section =

(UnityConfigurationSection)ConfigurationManager.GetSection("unity");

section.Containers.Default.Configure(container);

}

That's it. You can now create instances using container.Resolve<T>() for any type. As you will see, the container is able to Resolve any type, even if no type mapping exist in the configuration file. If you give it a concrete type, it will simply create an instance of that type and return it to you. You can later add a type mapping for that type and the real IoC benefits will be introduced automatically.

Create an instance and inject dependencies

Add these 3 types to your project.

public class InvoiceManager

{

private IInvoicingService _invoicingService;

public InvoiceManager(IInvoicingService invoicingService)

{

_invoicingService = invoicingService;

}

public void Manage()

{

Console.WriteLine(_invoicingService.GetCount());

}

}

public interface IInvoicingService

{

string GetCount();

}

public class InvoicingService : IInvoicingService

{

public InvoicingService()

{

}

public string GetCount()

{

return DateTime.Now.ToString();

}

}

Take a minute to study the dependencies: An InvoiceManager uses (depends on) an IInvoiceService. The class InvoicingService it the concrete implementation for IInvoiceService.

Add a type mapping in the App.config file. Change the content of the <unity> section this way:

<containers>

<container>

<types>

<type type ="UnityTest.IInvoicingService, UnityTest"

mapTo="UnityTest.InvoicingService, UnityTest">

</type>

</types>

</container>

</containers>

- Append these lines to your Main() function without changing the existing lines that create and configure the container.

IInvoicingService service = container.Resolve<IInvoicingService>();

console.WriteLine( service.GetCount());

- Run the project and see the result.

The container returns an InvoiceService when asked to resolve the type IInvoiceService.

- Delete the two new lines and replace them by the following two lines:

InvoiceManager manager = container.Resolve<InvoiceManager>();

manager.Manage();

- Run the project and see the result.

Although the InvoiceManager class is not configured in the App.config file, it is still participating in Dependency Injection. When asked to resolve the type InvoiceManager, the UnityContainer did not find any mapping to use to substitute InvoiceManager by something else. However, the UnityContainer analyzed the constructor of InvoiceManager and found that InvoiceManager has a dependency on IInvoicingService. So the UnityContainer resolved IInvoicingService into an InvoiceService and then passed it to the InvoiceManager constructor.

If you are curious, add breakpoints to the InvoiceService and InvoiceManager constructors and run the program. Notice in which order objects are created. Have a look at the call stack windows just to have an idea of what is happening under the hood.

Lifetime management

The UnityContainer is able to manage the lifetime of the objects it resolves. By default, the UnityContainer creates a new instance of any type it resolves. You can prove this with this unit test:

IInvoicingService service1 = container.Resolve<IInvoicingService>();

IInvoicingService service2 = container.Resolve<IInvoicingService>();

Assert.AreNotSame( service1, service2 );

There are 4 basic options for lifetime management:

No management: The container does not keep a reference on the objects it creates and therefore creates a new object each time Resolve<T>() is called. Singleton: The container always returns the same instance Singleton-per-thread: The container keeps one instance for each thread and return the instance based on the current thread. Externally controlled: You provide a class that will manage the instances. This option is not covered in this article.

Lifetime management configuration

The configuration of lifetime management is done at the <type> level. Each lifetime management option is supported by one type (class) in the unity application block library.

For example, the class ContainerControlledLifetimeManager is the class that implements the "singleton" lifetime management style.

- To resolve the IInvoicingService type using a singleton, change the <type> section this way:

Using the fully qualified name for the ContainerControlledLifetimeManager class can make files hard to read. The configuration section for unity supports defining aliases. The aliases can then be used anywhere a type name is expected. I recommend defining 3 aliases for the 3 types of lifetime management option.

- You can now simplify the <type> declaration for IInvoicingService this way:

<type type="UnityTest.IInvoicingService, UnityTest"

mapTo="UnityTest.InvoicingService, UnityTest">

<lifetime type="singleton" />

</type>

Tip: You can also define aliases the same way for your own types if you would like to simplify the type mapping for your own type.

Tip: You can also specify a lifetime for type that does not have a mapping. In this case, add a <type> section for that type but do not add a mapTo attribute. Then add the <lifetime> element to that type.

Other methods for injecting dependencies

So far, we have seen that the UnityContainer can inject dependencies by analyzing the constructor of a type and passing the necessary dependencies to it. In this section, we will see how dependencies can be injected using other mechanisms.

Dependency injection by property assignment

- Add these two classes to your project:

public interface ICustomerService

{

string GetCustomer();

}

public class CustomerService : ICustomerService

{

public string GetCustomer()

{

return "Sylvain Hamel";

}

}

- Add the following type mapping into the configuration file:

<type type="UnityTest.ICustomerService, UnityTest"

mapTo="UnityTest.CustomerService, UnityTest">

<lifetime type="singleton" />

</type>

- Change the InvoiceManager by adding a new Property of type ICustomerService:

private ICustomerService _customerService;

[Dependency]

public ICustomerService CustomerService

{

get { return _customerService; }

set { _customerService = value; }

}

Notice the use of the [Dependency] attribute. This will indicate to the UnityContainer that a dependency injection is required here.

- Change the Manage() method of the InvoiceManager this way

public void Manage()

{

Console.WriteLine(_invoicingService.GetCount());

Console.WriteLine(_customerService.GetCustomer());

}

- Run the project.

As you probably expected, the program did resolve ICustomerService and injected a CustomerService instance into the InvoiceManager.CustomerService property.

Dependency injection by method call

You can do pretty much the same thing using a method call instead of a property.

- Replace the CustomerService the property by a SetCustomerService() method:

[InjectionMethod]

public void SetCustomerService(ICustomerService service)

{

_customerService = service;

}

In the case of a method, use the [InjectionMethod] attribute to indicate to UnityContainer that a dependency injection is required.

- Run the project.

And of course, the program did resolve ICustomerService and injected a CustomerService instance by calling the InvoiceManager.SetCustomerService method.

Note on dependency injection by constructor

We have already seen dependency injection through the constructor but there is one important note about this: If your class has multiple constructors, your must annotate the constructor you want UnityContainer to use by adding the [InjectionConstructor] attribute on it.

Conclusion

Hopefully this tutorial will you get started with the Unity Application Block.