TeamCity Remote Runs / Personal Builds

3. July 2009

This is a killer feature of TeamCity against other CI servers, I believe.

TC allows you to test your changes before committing them to the Source Control Repository, which means that you don’t have to worry about breaking the build, because you won’t :)

I needed this in order to try a fix that I had for an issue in NH, it worked on my machine but  not sure if it works on another one.

Krzysztof Kozmic told me in the same evening that he’s going to try a fix against DP with personal build, and I thought it was a great idea!

image

 

Then it runs your changes on one of the build agents.

image

There we go! Patch didn’t break anything (even though it may not be how it should be)

Keep up the good work, JetBrains!

, ,

Ignoring files/folders when committing to SVN repository

2. July 2009

This feature of SVN is very handy. After you build your projects, there will be dlls in bin folders etc which you don’t want to commit.

Using svn:ignore property of SVN, you can eliminate the possibility of committing those files!

image

As many other things, I learnt this from NH :)

Fluent Interface for NH Facility – Take 1

27. June 2009

We’ve been getting many requests on having fluent configuration for NHibernate Integration Facility, and as I like programmatic configuration more than XML configuration (did I mention that I hate XML?), I decided to work on it. After 2-3 hours, I got the below more or less working

container.Register(
Fluently.ConfigureFacility()
    .Id("nhibernateFacility")
    .DefaultConfigurationBuilder<DefaultConfigurationBuilder>()
    .DefaultConfigurationPersister<DefaultConfigurationPersister>()
    .AddFactory(
                    Fluently.ConfigureFactory()
                        .Alias("myAlias")
                        .Id("myId")
                        .UsingConfiguration(
                        FactoryConfigurator.DefaultBuilder()
                            .ConnectionProvider("…………………………")
                            .ConnectionDriver("…………………………")
                            .ConnectionString("…………………………")
                            .Dialect("…………………………")
                            .ProxyFactory("…………………………")
                            .Assemblies("…………………………")))
    .AddFactory(
                    Fluently.ConfigureFactory()
                        .Alias("myAlias")
                        .Id("myId")
                        .UsingConfiguration(
                        FactoryConfigurator.XmlBuilder().File("myFile.xml"))));

The pieces in Italic are not necessary to write as they have their defaults, also we have some generic overloads for things like Dialect, ProxyFactory and ConnectionProvider.

What the above interface does is that it actually converts all the above configuration to IConfiguration and add them to the container as Facility Configuration, this is actually what is done behind the scenes when you use XML configuration.

I asked for a review over the syntax from several tweeps (@kkozmic, @dagda1, @mikehadlow, @chriscanal) and from one other NH Facility user, German Schuager, and got great feedback.

One of the issues that they pointed out with the above interface is that it is less discoverable. You have to find Fluently class, and then FactoryConfigurator class. Another issue is that it feels less natural to configure the facility like this. Instead, they prefer the configuration take place right on the facility.

This one is what German Schuager has suggested

container.AddFacility<NHibernateFacility>("nhibernateFacility", cfg => cfg
        .DefaultConfigurationBuilder<DefaultConfigurationBuilder>()
        .DefaultConfigurationPersister<DefaultConfigurationPersister>()
        .AddFactory("id1", f => f
                .Alias("myAlias")
                .UsingConfiguration<DefaultBuilder>(c => c
                        .ConnectionProvider("………")
                        .ConnectionDriver("………")
                        .ConnectionString("………")
                        .Dialect("………")
                        .ProxyFactory("………")
                        .Assemblies("………")
                ))
        .AddFactory("id2", f => f
                .Alias("alias")
                .UsingConfiguration<XmlBuilder>(c => c
                        .ReadFrom("myfile.xml")
                ))
 });

and similar one from Krzysztof Kozmic.

Looks like i was the only one that is fan of Castle Microkernel style Fluent Interface.

Let’s see what I’ll come up for the second take, If I ever do it.

Two VANs on Castle Project

27. June 2009

I like VAN meetings, and I believe I am gaining a lot from them. Due to some time zone problem, I remember waiting 1 hour in front of the PC :) I had even plans for presenting something on those VANs but nah things don’t go like the way I want. Zachariah Young informed me that there are 2 VANs in the following two weeks that cover some topic on Castle. I believe it would be a good idea to join to those meetings, even if you’re using some other framework or don’t use anything at all.

Ryan will be doing a two part series on the Castle Project.  Mark your calendar for some Castle Project fun.

A little information on Ryan Svihla
Ryan Svihla has been working as a C# developer Farm Bureau Bank in San Antonio since September 2007. Before that he worked as  a Consultant in Lincoln, NE for 3 years, where he had working experience with Php, some Perl, Python and of course C#.  Attemping Agile since early 2008 as an eager student with a focus on making programming more useful and relevant for the end user.


IoC and Dip through Castle Windsor
I assume readers have some familiarity with IoC and DI, so I skip description
Central Daylight Time
Start Time: Web, July 1, 2009 8:00 PM UTC/GMT -5 hours
End Time: Web, July 1, 2009 10:00 PM UTC/GMT -5 hours
Attendee URL: http://snipr.com/virtualaltnet (Live Meeting)


Web Development with Castle Monorail, Active Record and Brail view engine
Have a look at the first popular MVC  .Net based web framework. Also will be covering persistance with ActiveRecord, and view templates using Brail.  Bonus, will demo a plugin framework for building CMS like applications.
Central Daylight Time
Start Time: Web, July 8, 2009 8:00 PM UTC/GMT -5 hours
End Time: Web, July 8, 2009 10:00 PM UTC/GMT -5 hours
Attendee URL: http://snipr.com/virtualaltnet (Live Meeting)


For more info on VAN go to www.virtualaltnet.com

I’ll try to join those, see you there!

VS Addin: Fast Add Reference Dialog - No more Coffee Break, Steve!

18. June 2009
UPDATE 2: Now solution folders and some other stuff are done, thanks to Huseyin Tufekcilerli

UPDATE: I updated the dlls and the source in the link, now it doesn't crash VS. Hopefully the only problem left is that solutions with multiple solution folders won't be reflected in Projects tab.

I have spent a couple of days on implementing a fast add reference dialog box for Visual Studio(with some help from an existing addin). The time of adding a reference has been a great time to have some coffee, to have lunch, or even a way to save economy (remember, developer time costs money!). If you don’t believe me, take a look at what tweeps say.

It is actually easy once you find some of the extension points of Visual Studio.

In my case, I had to implement IDTExtensibility2 which contains method signatures to be called when a plugin is loaded, unloaded etc.

As first step, I had added “Add Quick Reference” item to the context menu when a project is right clicked. This is the most tricky part as there is almost no documentation on that.

The method that we should implement for this is:

public void OnConnection(object application, ext_ConnectMode connectMode, 
object addInInst, ref Array custom)

The type of the application parameter implements DTE2 interface and the addInInst parameter implements AddIn interface, which has all we need.

The DTE2 interface has CommandBars property which gives us access to various VS stuff. The matter is to find the right one. After for-looping all CommandBar item, i found that the place I should add my custom item is “Context Menus”->”Project and Solution Context Menus”->”Reference Root”. Man this is hard to locate! Looking forward to MEF in 2010!

applicationObject = (DTE2)application;
addInInstance = (AddIn)addInInst;
CommandBars cb = applicationObject.CommandBars as CommandBars;
CommandBar bar = cb["Context Menus"];
CommandBarPopup cbarControl = bar.Controls["Project and Solution Context Menus"] 
as CommandBarPopup; var commandBarControls = cbarControl.Controls; this.referenceRoots = commandBarControls["Reference Root"] as CommandBarPopup;

button = this.referenceRoots.Controls.Add(MsoControlType.msoControlButton, System.Reflection.Missing.Value, System.Reflection.Missing.Value, 1, true)
as CommandBarButton; button.Caption = "Add Quick Reference"; button.Click += oControl_Click;

There is one thing to be careful about: If you want to handle events of a button, for example, you should hold a reference in your class. Local method variables wouldn’t work. This situation is better told here

Now, I am done. I should now design the dialog itself that looks very similar to the original one. There is another problem: There is no "Windows Explorer Like” control for Windows Forms. There is OpenFileDialog but it is a dialog, not a control. I found the most similar one at GongShell Project which is licensed under GPL.

My current screen looks like the one below:

image

Very similar, even if I say so myself.

One thing to notice here is that the first tab is browse(.NET in original dialog), second is .net (Browse in original dialog) and third one is Projects. I haven’t written “Recent” part as I don’t want to deal with I/O really.

I believe that Browse window is more frequently used than .NET tab. There can be more improvements on that screen, such as having “common” tab which does the copying of commonly used references to a new project but hey this is a demonstration only ! :)

The items in the .NET tab are loaded in the background, and once it is loaded, it will be cached during the lifetime of the application.

I won’t comment more on the code, go grab it and try it. I wont continue developing this little addin, so you are free to do it on your own. Just drop me an email when you do it, though.

I just warn you: Com stuff is like walking on a mine field, and I am not taking any responsibility in case you loose data.

Download the code and the binaries here and put the binaries into Documents\Visual Studio 2008\Addins folder. Have fun!

Id Generation for db4o

18. May 2009

Disclaimer: This will be another post on events and extensibility points of a framework, but I can’t resist!

Recently, on one of my pet projects, I wanted to use db4o, and the problem was I should have explicit POIDs on my objects. Db4o has two mechanisms for Id stuff, one is GetId function, which is the physical address of the object on the disk and the second was the UUID that is used for replication purposes. The first one is fast but you can’t rely on it because the physical address may change after defragmentation, and the other is not very readable. This is the time I started to think of Id Generators for db4o. My friend Dario Quintana from NHibernate definitely had same needs(who doesn’t?) and as one having the right spirit, he implemented similar feature for db4o but this time with touching the codebase. My feature will use db4o Extensibility Point and will allow you to have several different Id Generators. I will use ideas from NHibernate POID generators specifically HiLo algorithm.

What is HiLo algorithm?

It is a nice algorithm that allows you to have ids without putting locks, thus slowing down the things. The algorithm works as follows.

Each Generator requests a Hi value from database and with every request, this value is incremented. The generator then uses a magic formula (Hi-1)*Capacity+(++Lo) value. Lo values are generated by the generator and incremented with every new object saved into database. Hi value is stored in database while Lo value is stored in a variable in the client. When Lo becomes larger than Capacity (that is Lo values are exhausted), the generator requests a new Hi value from the database. As you see, we don’t issue many requests for Hi values thus there is practically no overhead on the database side. The larger the capacity, the less there is need to request for new id thus the less overhead. However, Hi Capacity means there will be ranges that will never ever be used, and people dislike it (why does it bother them is a question for me, too). Practically Int32 can handle values up to 2,147,483,647 while Int64 can handle up to 9,223,372,036,854,775,807 (no I could not say this number in spoken English but learnt that is is nine quantillion). Having Capacity=32767 will allow you to have 281483566907400 Hi values and assuming you have 100 servers… wait it is obvious that you cannot consume all those in several million years?

How can we integrate it into db4o?

Well, this is easy. Db4o provides us an event mechanism that can be used for such stuff. It has several events namely Creating, Created, Updating, Updated etc. All we have to do is to catch this event on the server side, and increment Hi values there. There is one thing to be careful about: Db4o events may fool you. In case of Client/Server mode you should call the below code on ServerContainer, otherwise you may have to use another ObjectClient as each object container runs in its own transaction. If you are using it as embedded database, then you won’t have any problem with it.

Now, I define a contract called IIdGenerator

public interface IIdGenerator
{
    object Generate();
}
public interface IIdGenerator<T>:IIdGenerator
{
    new T Generate();
}

Pretty self explanatory, isnt’ it? Now it comes to persistent id generator, which is for now the increment generator

 

public class IncrementGenerator:BaseIdGenerator<long>
{
    private readonly Type type;
    private readonly IObjectContainer container;
    private readonly string semaphoreName;
    public IncrementGenerator(Type type,IObjectContainer container)
    {
        this.type = type;
        this.container = container;
        this.semaphoreName = string.Format("id_gen_{0}", this.type.Name);
    }

    public override long Generate()
    {
        long valueToBeReturned;
        while (!container.Ext().SetSemaphore(semaphoreName, 1000)) ;//Do some busy wait
        IObjectSet set=this.container.QueryByExample(new IncrementTypeValuePair{Type=type});
        IncrementTypeValuePair pair;

        if (set.Count == 0)
            pair = new IncrementTypeValuePair {Type = type};
        else
            pair = set[0] as IncrementTypeValuePair;
        valueToBeReturned = ++pair.Value;
        container.Store(pair);
        container.Ext().ReleaseSemaphore(semaphoreName);
        return valueToBeReturned;
    }
}

There we used Semaphore in order not to have concurrency issue, otherwise we could give very same id to different objects. This id generator will go to db everytime an id is requested, and it will create some bottleneck in case several hundreds of entities are inserted in a second. As an enhancement to this generator, we’ll inherit from this generator and create HiLoGenerator.

[MethodImpl(MethodImplOptions.Synchronized)]
public override long Generate()
{
    if(currentLo>=capacity)
    {
        currentHi=base.Generate();
        currentLo = 0;
    }

    return (currentHi - 1)*capacity + (++currentLo);
}

Exactly what I told in oral.

As the last step, I designed an ugly fluent interface for this, which looks like the following

var serverContainer = this.server.Ext().ObjectContainer();
serverContainer.IdMap(Map<Person>.On(x => x.Id).SetGenerator(new HiLoGenerator(3, typeof(Person),serverContainer)));
var person = new Person();
container.Store(person);

The event wiring stuff is done a bit ugly too.

void registry_Creating(object sender, CancellableObjectEventArgs args)
{
    object item = args.Object;
    foreach (var map in idMaps)
    {
        if(map.EntityType.IsAssignableFrom(item.GetType()))
        {
            MemberExpression member = ((LambdaExpression)map.Expression).Body as MemberExpression;
            ((PropertyInfo) member.Member).SetValue(item, map.Generator.Generate(),null);
            break;
        }
    }
}

Whole code can be found if you follow this link

,

DELL Fail – Once more

27. April 2009

Do you see the difference between two pictures? If not, I think I am going mad.

image 

The time difference between those two screenshots is not more than 30 mins.

DELL, I liked you at the first sight, but now you are changing my mind. The online support agents are so helpful that I _may_ consider buying DELL again, but you suck at customer care.

 

,

UserVoice for Castle Project

27. April 2009

One of the most active members of Castle Community, Krzysztof Kozmic, has opened a user voice page for Castle, and you can be sure that this page is followed by Castle Committers. We are waiting for your suggestions on any piece of the Castle Stack. In addition, if we reach enough number, Ayende told that he may release Windsor :)

Go ahead and put your voice.

Thank you very much Xtoff!

Castle NHibernate Facility – Configuration

6. April 2009

Castle’s extensibility points provide you many ways to make your life easier. One and most widely used extensibility point is the facilities. By using facilities, you can integrate various other frameworks and technologies easily.

I am going to talk about NHibernate Integration Facility, which is currently lead by me. It was originally written by Hamilton Verissimo, and its current shape is more or less the same as what he wrote.

The purpose of this post is to get feedback and shape the documentation accordingly.

Now, after an historical introduction, lets talk about the facility’s purpose, and in as the first part of the documentation, the configuration.

The purpose
The purpose of this facility to provide an easy way to integrate NHibernate into MicroKernel backed applications. The facility provides a nice way to manage multiple session factories, a good way to manage sessions and it also provides some other structures that can be used to further integrate other frameworks such as Fluent NHibernate. It also plays nicely with other Castle services such as Transaction Management.


The Configuration

Currently, the facility can only be configured via XML, but it provides some extension points that can be used to configure it programmatically. The traditional way of configuring it is as given below. 

<configuration>
    <facilities>
        <facility
          id="nhibernatefacility"
          type="Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration"
          [optional: configurationBuilder="Your custom configuration builder"] [optional: isWeb="Your custom configuration builder"]>
            <factory id="sessionFactory1">
                <settings>
                    <item key="connection.provider">NHibernate.Connection.DriverConnectionProvider</item>
                    <item key="connection.driver_class">NHibernate.Driver.SqlClientDriver</item>
                    <item key="connection.connection_string">Data Source=.;Initial Catalog=test;Integrated Security=SSPI</item>
                    <item key="dialect">NHibernate.Dialect.MsSql2000Dialect</item>
                    <item key="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</item>
                </settings>
                <assemblies>
                    <assembly>YourAssembly.Name.Here</assembly>
                </assemblies>
            </factory>
        </facility>
    </facilities>
</configuration>
isWeb: In case of web application, you should set this to true, implement IContainerAccessor in your HttpApplication (the global.asax) also add following lines to your <httpModules> section. 

<httpModules>
    <add name="NHibernateSessionWebModule"
             type="Castle.Facilities.NHibernateIntegration.Components.SessionWebModule, Castle.Facilities.NHibernateIntegration"/>
</httpModules>


As it can bee seen here, it is not very much different from the way we configure NHibernate. What happens behind the scenes are that: Facility creates an NHibernate Configuration, registers the SessionManager, and make those ready to be resolved.

The facility provides you some way to modify the Configuration that is created behind the scenes. The point is called IConfigurationContributor. By implementing classes that derive from that interface and registering them to container, you’ll be able to modify the NHibernate Configuration, just before the SessionFactory is resolved. The interface is simple

public interface IConfigurationContributor
{
    void Process(string name,Configuration config);
}


The name corresponds to the id in the configuration.

You can also Configure NHibernate Configuration via the IConfigurationBuilder interface. Currently, there are 2 built in ConfigurationBuilders, namely DefaultConfigurationBuilder and XmlConfigurationBuilder.
The default one is the one that parses the thing you see above while XmlConfigurationBuilder uses NH’s native xmls.

In the next post, I will hopefully show to integrate FluentNHibernate using custom ConfigurationBuilder

, ,

Lost Generation – Will come true unless we choose to reverse it

21. March 2009

This is off-topic but I do care about it.