Oren Eini

CEO of RavenDB

a NoSQL Open Source Document Database

Get in touch with me:

oren@ravendb.net +972 52-548-6969

Posts: 7,592
|
Comments: 51,223
Privacy Policy · Terms
filter by tags archive
time to read 1 min | 197 words

So I had to do it today, I had two pages, in two unrelated domains (foo.com and bar.com) and I had to open a page from one and interact with it. Security constraints disallow this, unfortantely. There are all sorts of ways around it, mostly focusing on proxies, but I didn't want to get into that for a simple page, so I decided to write my own stupid method to do it.

From foo.com, the calling page:

var url = "http://www.bar.com/someImportantPage.castle?id=15"&onCloseRedirectTo=" + 
		encodeURIComponent(window.location.href + 
"&returnUrl="+ encodeURIComponent(window.location.href) ); window.open(url);

And using JS injection for the called page (I have some limited control there), I put:

if(window.opener)
{
	var oldClose = window.close;
	window.close = function()
	{
		if(window.opener && window.returnValue )
		{
			var url = decodeURIComponent($.getURLParam('onCloseRedirectTo')) + 
							"&idToAdd=" + window.returnValue;
			window.opener.location.href = url;
		}
		oldClose();
	};
}

And voila, it works. I'll leave the how as an excersize for the reader. Suffice to say that if you want to add a local iframe to the mix you can even get it to work in an "ajaxian" fashion.

time to read 1 min | 103 words

imageI need to express the same logic over two different types. The code is literally the same in 90% of the cases, with minor modifications for each type. Seeking to avoid copy & paste programming, I decide to use some

public class BaseSpecificationController
<TSpecification, TSpecificationResult, TEntity> : BaseController where TSpecification : BaseSpecification<TEntity,TSpecificationResult> where TSpecificationResult : BaseSavedResult

The problem is that I got there, and it is really saving a lot of duplicated code. But still, I can't help but dislike such code, it seems like it is cheating. 

 

.

time to read 1 min | 88 words

I have been working on .NET 2.0 for a long time now, generics still manage to trip me.

Consider this piece of code:

public interface IFoo<TFromInterface> { }

public class Foo<TFromClass> : IFoo<T> { }

[Test]
public void More_Generics_Gotcha()
{
	Assert.AreEqual(typeof(IFoo<>), 
		typeof(Foo<>).GetInterfaces()[0]);
}

This test fails. the returned System.Type instance is a IFoo<TFromClass>, which is  an unbounded generic parameter, but not the same as IFoo<> itself. Now I need to apologize for Windsor, it wasn't its fault all along.

time to read 3 min | 484 words

imageSpecification:  An explicit statement of the required characteristics for a matching entity / object.

Specifications are very useful concepts when you need to think about searches. They are useful because they seperate what you are searching from how you are searching.

In the example to the right, we have a specification for a job opening. We can use it to search for matching job openings. But couldn't we do it directly? Yes we could, but then we would dealing with both what and how at the same time.

Let us say that we want to search for an opening matching a male candidate, age 28, shall we? How do we handle that?

Pretty simple, actually:

OpeningSpecification spec = new OpeningSpecification();
spec.Age = 28;
spec.Gender = Gender.Male;
spec.FindAll(openingRepository);

The specification is responsible for translating that to a query that would return the correct result, which this translation can be wildly different than the specification itself. For example, let us take the age. We want opening that match a person whose age is 28, but the opening doesn't have a DesiredAge property, they have min / max ages that they allow.

That fact means that we search for a male doesn't mean that we need to exclude every opening where the max/min age reject someone with age of 28 years. But we don't care about that when we use the speficiation, we just want to find the matching opening.

From an implementation perspective, we use the property setters as a way to incremently build the query, here is how I built the Age property:

[Property]
public virtual int? Age
{
	get { return age; }
	set
	{
		age = value;
		if (value == null)
			return;
		criteria
			.Add(Expression.Le("MaxAge", age) || Expression.IsNull("MaxAge"))
			.Add(Expression.Ge("MinAge", age) || Expression.IsNull("MinAge"));
	}
}

As an aside, consider the usage of the operator overloading there, I completely forgot to use that before, and that is a shame, since I was the one that added that to NHibernate. Andrew Davey reminded me how useful this is.

You may notice that I have a [Property] on the specification Age property, and that it carries some unusual properties such as Id, Name and Username. Those are used to persist the specification, so I can save it and then load it again, extremely useful if I want to save a search for "Males over 30", and re-run it later.

Another advantage here is that I have the possibility to construct a specification easily from another object. You can see the FromCandidate() method on the specification above, it build a specification from the candidate that matches job opening that the candidate is eligable for.

All in all, a very useful concept, and it gets even nicer if you throw MonoRail into the mix, but this is a matter for another post.

time to read 1 min | 169 words

When it comes to building search screens, there really isn't something that I would rather use over NHibernate. I am just astounded at how I can slice a very complex scenario into very narrow & clear fashion:

criteria.Add(Expression.Disjunction()
		.Add(Expression.Disjunction()
					.Add(Expression.Eq("City1.id", value))
					.Add(Expression.Eq("City2.id", value))
					.Add(Expression.Eq("City3.id", value))
					.Add(Expression.Eq("City4.id", value))
				)
		.Add(Expression.Conjunction()
					.Add(Expression.IsNull("City1.id"))
					.Add(Expression.IsNull("City2.id"))
					.Add(Expression.IsNull("City3.id"))
					.Add(Expression.IsNull("City4.id"))
			)
	);
cloned.Add(Expression.Disjunction()
			.Add(Expression.In("PreferredArea1", ToArray(Areas)))
			.Add(Expression.IsNull("PreferredArea1"))
	);
cloned.Add(Expression.Disjunction()
			.Add(Expression.In("PreferredArea2", ToArray(Areas)))
			.Add(Expression.IsNull("PreferredArea2"))
	);

Now imagine roughly 20 such cases, all of them can be added/removed dynamically... I am going to write a far longer post about the specification pattern and how it useful it is.

Update: Andrew reminded me that there are easier ways to do this, using operator overloading, let us take the first example and see how it goes:

criteria.Add(
	(
		Expression.Eq("City1.id", value) ||
		Expression.Eq("City2.id", value) ||
		Expression.Eq("City3.id", value) ||
		Expression.Eq("City4.id", value) ||
	) || (
		Expression.IsNull("City1.id") &&
		Expression.IsNull("City2.id") &&
		Expression.IsNull("City3.id") &&
		Expression.IsNull("City4.id") &&
	)
);
time to read 3 min | 406 words

I think that I mentioned that I believe that having a good IoC container at your disposable can make you really shift the way you are structuring your code and architects solutions.

Let us take for instance Validation as an example. The two examples that jump to mind are Castle.Components.Validation and the Validation Application Block. They both have the same general approach, you put an attribute on a property, and then you use another class to validate that the object meet its validation spec.

This approach work, and it is really nice approach, for very simple input validation. Required fields, length of a string, etc. Being able to declaratively specify that is so very nice. But it breaks down when you have more complex scenarios. What do I mean by that? After all, both libraries offers extensibility points to plug your own validators...

Well, as it turn out, when we go beyond the realm of simple input validation, we reach into the shark filled waters of business rules validation. Those rules are almost never applied across the board. Usually, they are very targeted.

Business rule: A customer may only open a service call for products that the customer has purchased

Expressing this rule in code is not very hard, but it doesn't benefit much from the above mentioned libraries.*

Nevertheless, you want to have some sort of a structure in your validation code. You want to be able to add new validation easily. Here is the back of the envelope solution for this. Hopefully it will make it clearer why I think that having IoC makes it so very easy to handle things.

public interface IValidatorOf<T>
{
   void Validate(T instance, ErrorSummary errorSummary);
}

public class Validator
{
	IKernel kernel;//ctor injection, not shown
	
	public ErrorSummary Validate<T>(T instance)
	{
		ErrorSummary es = new ErrorSummary();
		foreach(IHandler handler in kernel.GetHandlers(typeof(IValidatorOf<T>)))
		{
			((IValidatorOf<T>)handler.Resolve(CreationContext.Empty)).Validate(instance, es);
		}
		return es;
	}
}

And yes, that is the entire thing. Come to think about it, I think that we need to add GetAllComponentsFor<T>() to Windsor, but that is another matter. Now, if I want to add a new validation, I inherit IValidatorOf<T> with the right T, and that is it. It gets picked up by the container automatically, and the rest of your code just need to call Validator.Validate(myServiceCall); and handle the validation errors.

* Actually, a standard way to report validation errors is very nice.

time to read 4 min | 742 words

So, I showed how you can write an IoC container in 15 lines of code, obviously this means that containers such as Windsor, at ~52,000 lines of code are tremendously bloated and not worth using, right?

Well, no. And the reason is that DI is now just one of the core functions of a container, it is the other things that it does that make it so useful. Since the discussion started from why you don't need IoC in Ruby, I decided to also explore the ideas in the Ruby frameworks. It seems like a typical Ruby IoC code is this:

registry.register( :component ) do |reg| 
  c = Component.new
  c.service = reg.some_other_service
  c
end

This is very similar to the idea of the demo container that I build. Basically, it is using the block (anonymous delegate) to defer the creation to some other time. On the surface, it is a viable approach, but it breaks down as soon as you start dealing with even moderately complex applications.

I will get back to it in a minute, but let us walk through the core things that an IoC container should provide.

  • Dependency Injection
  • No required dependency on the container from the services
  • Life style management
  • Aspect Oriented Programming

The above is what I consider the core minimum to be an IoC container. It is not really that hard to build, and using Dynamic Proxy I can probably get this all working in about three hours. But it wouldn't be very usable. (And yes, it will have facilities :-) )

The reason that I use IoC is not to encourage testing, it is not to break dependencies, it is not to get separation of concerns. Those are well and good, but if I had to use a container that behaved like the one listed above, I would go crazy.

I am using IoC because it makes all of the above so easy. It make it harder to create a manual dependency than to do the wiring through Windsor. As a matter of fact, I went crazy about a year ago just having to deal with just specifying service declarations. That is why I have Binsor in place. That took care of all the complexity.

Now testability, separation of concerns and no dependencies are no longer things that I have to work toward, they are already there, right out of the box.

My current project has well over 250 components that are managed through Windsor. I have no clue as to their dependencies, and I don't really care about that. Other people on my team keep adding components, and they aren't even aware that they have IoC there. They just know that if they put the IFooService in the ctor, they will get it when the code is running. And if they add IBarService and BarServiceImpl, they will be available to any component that uses them.

image Can you imagine trying to deal with 250+ dependencies resolving blocks (or anonymous delegates) ? Just writing them down would be a chore, and then they would have to be maintained, and adding something is becoming fragile. I can't imagine having something break because I added a parameter to the constructor, or a settable property that I need.  I can't imagine having to do something beyond just creating a class to get it to register in the container.

Well, I can imagine those, I can't imagine me suffering through that. It would be like trying to pull a particular fish from the image on the right, possible, but very painful.

Auto wiring is what makes IoC a mandatory part of my application, because it means that I don't need to manage the dependency cloud at all. I let the container do it for me. It means that once is has been setup, you no longer need to think or be aware of it. I have forgotten that I am using an IoC container for three months, while using it each and every day.

Then you get to the AoP concepts, of which I particularly like automatic transaction support and cross thread synchronization.

To conclude, I think that if you are using an IoC merely for dependency injection, you are missing a lot of the benefits there. Having the ability to just throw the complexity at a tool and have it manage it for you is a key factory in how you design your applications.

FUTURE POSTS

  1. Semantic image search in RavenDB - 2 days from now

There are posts all the way to Jul 28, 2025

RECENT SERIES

  1. RavenDB 7.1 (7):
    11 Jul 2025 - The Gen AI release
  2. Production postmorterm (2):
    11 Jun 2025 - The rookie server's untimely promotion
  3. Webinar (7):
    05 Jun 2025 - Think inside the database
  4. Recording (16):
    29 May 2025 - RavenDB's Upcoming Optimizations Deep Dive
  5. RavenDB News (2):
    02 May 2025 - May 2025
View all series

Syndication

Main feed ... ...
Comments feed   ... ...
}