Sunday, 12 September 2010

Windsor Castle BuildUp

Good news, everyone! I've discovered a way to enhance a brilliant DI-container Castle Windsor with not so brilliant feature as BuildUp.

Saying that it is not that brilliant I mean that this feature is a beast, actually. It is an open door to violate DI principles, and there are more elegant ways to overcome a problem of having to resolve an external object through DI-container. After all, if Castle team considered this feature useful, they would roll it out long time ago, have no doubt!
However, in my case it is a matter of time, to have an opportunity of resolving existing object's dependencies through DI-container, built as fast as possible. That is why I turned to BuildUp feature that some other DI-frameworks have.

I was really amused with Windsor's degree of extendability and how trivial my solution appeared.

BuildUp functionality is closed up under ComponentActivator. Activators are called when LifetimeManager considers that a new object has to be created. And that logically brings us to restriction of this solution - it won't work with Singleton lifestyle. But it shouldn't actually! When you mark an object as a singleton - you effectively state that a container is going to be an owner of that object, thus it won't ever be built externally.



BuildUpComponentActivator extends DefaultComponentActivator and overrides a single method - Instantiate. This guy is a cheater, as you might guess, it never creates an object, but simply read it from context. All the dirty job of deriving dependencies is done by a parent class. Should BuildUpComponentActivator fail to find an object in context, it will simply delegate all work to parent, and a new object will be created. This is done to support resolving objects of the same type managed by container.

Context is a dictionary, created with BuildUp extension method:



In order to be able to build up an object, one have to modify it's registration and override ComponentActivator setting. CanBeBuiltUp is a neat extension method wrapping this call for Windsor fluent registration API.

There is only one shortcoming with this solution I came with - it doesn't provide you with any facilities to release this external object's dependencies. It has to be done manually somewhere.

Please note, that there are other solutions to this problem.

Good luck!

Monday, 30 August 2010

My two cents in OSS. Free VOIP .Net library.

Good news, everyone!

A brand new pure OOP VOIP open souce library has just entered the .Net realm - pjsip4net. This is my projection of plain "2D" procedural C library pjsip into "3D" world of objects. It is so trendy to go 3D nowadays that I just couldn't resist. =)

To be correct pjsip4net is a wrapper above high-level pjsua API. It provides you with readymade user agent capable to issue calls over SIP & (S)RTP protocols via UDP or TCP or even TLS from your .Net code.

Actually, this code is still under construction due to my constant need to improve. But keep your wig on, it is already usable and tested.

I have covered prety much everything in pjsua API, but still this is what you can do with it:

  • register at SIP server;
  • select a sound device;
  • select and prioritize codecs;
  • call another party;
  • auto answer;
  • auto conference (all calls will be marshalled to one big conference);
  • NAT traversal (STUN, TURN, ICE);
  • blah blah blah with other party.
Enter pjsip4net: http://code.google.com/p/pjsip4net/

Good luck!

Saturday, 2 January 2010

ORM-style Identity generator or impossible is nothing.

What the hell?! Isn't it a bit like even odds? Everybody knows that it is impossible to prevent NHibernate from breaking Unit of Work semantics, when your primary keys are generated by SQL Server Identity facility. To justify that, please read the following: generators revealed, and follow on with this story.

In short, the major problem of Identity generator is that it is a post insert generator, that is to say it can't produce new Id value without INSERT statement being executed by database engine. Furthermore NHibernate can't persist entity
without Id. That is why NHibernate will insert our object to the database the moment it was persisted without waiting for Flush() to be called. This causes huge problems should you try to implement long-running business transactions. The biggest trouble is that you won't be able to rollback changes made in business transaction.

In short, this is what I want to achieve:

  • insert values into Identity fields on my own;
  • acqiure correct Identity values that wouldn't cause troubles in database;
UPD: As it was fairly noticed, it looks like I work very hard to get something that is already in the box (HiLo). It really looks like that, but I have to prove that is not a waste of time. The point is that my case is constrained with existing database with defined schema. This database is filled with loads of records by other processes that I have no access to. That is why I can't use solutions like HiLo and have to invent my own.

In SQL Server one can disable autoincrement for Identity field and
insert its own values. But how would he get a correct value? The easiest way is to insert a dummy row in a local transaction and then perform a rollback. After transaction was cancelled, Identity value won't be reverted. Thus, by changing a table and reverting all changes made, we produce a gap in an Identity sequence, and the gap value can be inserted manually afterwards.

Having said that, I've drawn a following sequence diagram:

The solution, as it comes from a diagram above, consists of 3 parts:


  • Custom Id generator, which I've called ORMIdentityGenerator;
  • PreInsert listener, to disable Identity field autoincrement;
  • PostInsert listener, to enable Identity field autoincrement back;

ORMIdentityGenerator

This is an easiest possible implementation of what I was talking before. Agile principles say KISS - keep it simple, stupid! and that is what I do. This generator is merely an INSERT statement executor. One can configure it with the INSERT statement to perform safe (in terms of database integrity) operation that will change a table and force database to produce a new Identity value. This value will be returned with a next SELECT statement execution
.

PreInsert


PostInsert


That's it. Now I can edit my persistent objects with Id field generated by Identity in
a long-running session and rollback changes should I need it.

Good luck!

Thursday, 28 August 2008

Dependency Injection in xaml

I want to describe a solution I've found to inject dependencies of my objects right in Xaml. This solution is special because it is coupled with CAB that I use as a platform for my smartclient applications, but I sincerely hope that you will see the idea behind particular implementation that will let you abstract this solution away from particular IoC framework.

Quite often I create objects in Xaml, and I'd like to follow the main principles of my development. As a part of this I'd like to inject dependencies in objects, being created by WPF, like I
do it in code-behind.



So I need a solution that will fit following requirements:

  • ability to be used in Binding;
  • ability to be used with POCO.
My solution consists of the same number of parts as abovementioned requirements:
  • IoCProvider - custom DataSourceProvider (Binding "knows" about DataSourceProvider and works with it perfectly);
  • a set of MarkupExtensions to be used with POCO;
IoCProvider

IoCProvider is the core of my solution. It is the part that infers dependencies by means of standard CAB IoC container - WorkItem.



Since
this object is created mostly by WPF engine, there is no way to inject a container into IoCProvider, but here we can use a well-known registry object, such as an Application object in WPF. Considering that my Application always implements IRootApplication interface, that is bound to publish root WorkItem, this task is no more a matter of interest (see IoCProvider constructor).

Main job in inferring of dependencies is done in BeginQuery method. One can initiate a query by calling a base
DataSourceProvider class Refresh() method manually, or it will be done automatically by means of Binding system.



Now we can use this provider as a source of data in Binding, but
attempts to bind POCO's property or field to requested dependency will cause an InvalidOperationException to be thrown, informing us that binding can be used only with Dependency Property. How do we escape this?

Markup Extension.

This is the solution for the second part - markup extension. Markup extensions can be used
almost everywhere in xaml. ServiceDependencyMarkupExtension is my example implementation, which infers WorkItem's service dependencies.



Below follows the result - we
inject our dependencies right in Xaml! Isn't it awesome?



I hope now you see how simple the dependency injection in xaml is, and I also hope you'd be able to make a step further and abstract the whole solution away from concrete IoC framework. You can see an example of such solution in Prism - its IContainerFacade interface.

Here is a couple of articles that will help you in process:
creating-a-custom-datasourceprovider
Injecting Xaml with Unity Application Block using Markup Extensions

Good luck!

Wednesday, 6 August 2008

Kodama - a spirit of tree.

Some of you have probably read my post about Josh Smith and ViewModel coming to rescue people (WPF-addicted people, to be precise), just joking don't mind. In brief words, I wrote how ViewModel helped working with ComboBox or another Selector control to manage state of underlying CollectionView. After that I've generalized my thoughts, and there came a SelectorCollectionPresenter class, which made my sleep quiet. =) I'll publish code in the end as a bonus.


But now I want to write about the TreeView control, and how it can be united and simplified with ViewModel pattern. I was inspired a long time ago, when I read this article by Josh Smith, but had no time to work with WPF, solving other infrastructural problems, but I've got the idea stuck in my head.
And finally I got time to think about it and put it together in a reusable manner. As a result I've got a tree control with a spirit living in it. I named it Kodama, because kodama is a spirit from Japanese folklore, which is believed to live in trees. And the control itself was called KodamaView. As you might have already guessed, this spirit, which lives in my tree control, is nothing more than a ViewModel!

- he said ViewModel?

I want to warn everybody – I've just put together my thoughts on DM-V-VM pattern and Josh's fantastic ideas, so most of honors should go right to Josh!

KodamaView


KodamaView - is a UserControl, hosting a TreeView inside itself. In order to simulate TreeView's behavior, it inherits ITreeView interface, based on my IWPFView interface, and delegates all incoming calls to internal TreeView control.


TreeView simulating interface.


KodamaView control.


Control's xaml.

Kodama.

And now here are some words about Kodama.


Toriyama Sekien's illustration of a kodama appearing as an old man.

My Kodama (if it is allowed to say so) is an inheritor of ViewModel class, parameterized with ITreeView and IDataModelBase interfaces. The last one is made basic to be able to create Kodama with any derived DataModel class, because all of them embody this interface. DM is the source of data for the tree.



Every TreeViewItem gets its own ViewModel - a TreeViewItemViewModel.



TreeView is able to load child nodes "lazily", only when their parent node is expanded (I've borrowed the code from Josh's article, I hope he doesn't mind). All work on loading children is done in a LoadChildren method.



There is another one class in hierarchy - TreeViewItemViewModel`1. It has only one purpose to exist - to populate a typed Entity into the visual tree.



StructureTreeKodama is my example demonstrating this philosophy.




I remember, when I started the post, I've promised you a bonus. So here it is - SelectorCollectionPresenter class code. You can read some on details of it here.



Good luck!

Tuesday, 24 June 2008

WPF Presentation layer

I am about to stop blogging for next three weeks.

I'd like you to spend this time with pleasure and use so here is the candy: Presentation Layer.
This is a small framework to help develop desktop WPF applications. Mostly it is a DM-V-VM implementation with some other stuff I've blogged about.

And, finally, I am going to make a candy more yummy. I've included source codes for my WPF Wizard control as I've promissed some time ago.

Enjoy!

Friday, 6 June 2008

How Josh saved my day or the power of the Model side

May be I missed something but it was a challenge for me to maintain a following situation.

Imagine, for example, that you have an object with some property that can be chosen from some external list of values. How would you solve it? You'll, probably, put in UI some Selector control, say it would be a ComboBox, bound with list of available values. You would bind its SelectedItem property with underlying object's target property by means of OneWayToSource binding. Quite easy so far, isn't it? Just write ViewModel for this view that will publish this object and will keep all logic. Now let's make this example a little trickier. Imagine that you have to edit a list of said objects and you have to choose a unique value for every particular object. You see now that it is not so easy anymore? And to puzzle you completely picture yourself a Configuration Dialog that hosts your editing UI. This dialog has OK and cancel button and your objects' state must stay sync with what you do. Something like the following:

Don't be scared this UI is just for tests =).

I've written a number of posts about M-V-VM pattern, but in spite of was completely cumbered with this scenario. I do have an infrastructure to edit objects (I've written about it here), but in this case I was baffled. The problem was with this list of available values. To make it easier for understanding I'll introduce some classes.

The scenario is as follows: I have a number of visual addins (powered by Managed Add-Ins Framework) (I really should write about it, but I'll do it later) that I want to host in my UI. But they can be hosted only in the named Workspaces (a CAB's notion, it is not a WPF restriction it is my decision). You can see the model now. I've got AddInDescriptor objects that keep a name of containing workspace and addin token. This name can be set in Configuration Dialog by browsing and selecting one from available list. This dialog can commit or rollback changes and at next start it must show appropriate content.


descriptor class. just a DTO.


descriptor data template.


listbox item style.

The problem
looks like this: when I first set the name of containing workspace and then rollback and start again, combobox updates current item binding (AddInDescriptor.ContainingWorkspaceName property) with a valid empty workspace name and then explicitly sets the first item as current without update. This strange behavior violates all the logic written in a style's triggers. I tried to fix this broken behavior in a whole bunch of ways but neither of them worked.

And this is whe
n an idea dawned at me! I remembered a beautiful article written by WPF-rock star (of course it was Josh, who else?) about the simplest way to manage a TreeView in WPF. Here it is: http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx. I say this article is a MUST read.

And then I thought: "What is the difference? I have to do the same with ComboBox in my case.", and everything became clear.

I've created a AddInDescriptorPresenter class that held all the UI related logic. It is nothing more then a UI-proxy to the object and is intended to publish object- and UI-related properties. This class accepts a CollectionView (a built-in VM for collection) which a Combo is bound with.

AddIn descriptor presenter.

A list of these proxies is created and exposed by UI ViewModel that keeps a list of AddInDescriptors.

You might be interested what the TransactionalTune is.
TransactionalTune is a special data container, a volatile transaction manager based on Juval Lowy's fantastic article. You can read more here.
All this UI-proxy does is controlling the state of CollectionView that is synchronized with ComboBox.


AddInDescriptorPresenter code.

Template to render this presenter became a little bit easier.


AddInDescriptorPresenter data template.

I've spent a couple of days trying to solve this problem writing tons of different xamls and code-behinds, and it took me about an hour to make everything work correctly with the ViewModel!
You see now that it is powerful?

Good luck!