Lucene2Objects roadmap

Since the release of Lucene2Objects I’ve seen a few people downloading it and some have left a couple comments, some have directly emailed me and others even found me on BitBucket and sent me a message over there. I think that is awesome, which is why I plan to devote a bit more of my time to get more cool stuff into Lucene2Objects, also there is the fact that I actively use it on a couple projects 🙂

So far, there is only one thing that comes to mind that we need to have released on L2O, which is the fact of self tracking objects, that is having the object been able to track any changes to it and update them on the Index. I’ve been devoting some time into this matter and I’ve come with a couple of ideas, but to get them, there is a couple of basic principles I need to keep in mind:

  • Lucene2Objects tracking system needs to be as unobtrusive as possible (And not because the word is trendy)
  • As it has been so far, getting the tracker up and running should be easy for anyone not interested in getting too deep
  • If somebody is indeed interested in going deep it needs to be also easier than going into Lucene .NET(which is not easy at all!!)

But, if you think of it, these are just basic design principles, the first one is basically YAGNI and KISS and the other two are just plain old Bertrand Meyer’s Open Closed Principle. Despite the fact that these should rule most development projects, the actual panorama is not like that. Anyways, I digress…

The other thing that so far I think that is necessary in order to have self-tracking entities (and collections, which are after all, entities) is that to be able to do some self-tracking, the entities to be tracked need to have some sort of primary key, or something that distinguishes them. Having said that, I can think only of forcing the use of a primary key on any entity to be tracked, for instance, using the [PrimaryKey] attribute. The alternative is generating a key somehow, but since you don’t always (actually almost never…) know which fields identify an entity, there is no way of warrantying that this is a safe or unique procedure.

There is an idea for Sharp Lite users which is using the [DomainSignature] attribute for auto generating the so called key. For those of you who don’t know what SharpLite is, is a really nice development framework made mostly by Billy McAfferty for developing .NET apps, and although it has a couple detractors it’s a really good way to start any small and mid-sized projects. So, for all of you developers reading this post and interested on how L2O progresses, Is there something you want to see on L2O? Feel free to comment or email me, I’m interested on hearing your thoughts.

Lucene2Objects goes public!

I’ve been asked a couple times to release the Lucene2Objects code out in the wild and it was the intention all the way, but I didn’t had the proper time to do it, not the proper bandwidth.
The new Lucene2Objects has a couple new changes and it’s more lightweight than the first versions since it doesn’t depends on Ninject anymore. Feel free to browse the code, leave issues or just email me with any problem you have.
If you are using Lucene2Objects, let me know as I want to know if it’s been useful out there.

All the best,

S#arpLite: “At least one ISessionFactory has not been registered with IoC”, Darn with the redirections…

Yesterday I installed ASP .NET MVC 4 beta so I can play with it for a couple days. To be honest, I haven’t built one simple app because I haven’t had the time to do it, but I popped up my Visual Studio 2010 today and booted a S#arp lite project from the template. As usual, I made my move to Fluent nHibernate but when I loaded the project:

After spending a couple hours digging my way into my machine and debugging I went into the S#arp Lite discussion group and found this post of somebody having the same issue, finally the last answer hit the nail:

Have you installed MVC4 on you machine? If yes, check reference in Init project, it references MVC4 whereas Web project references MVC3.

Mmmmm… I did… so I tried this…

 <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
 <bindingRedirect oldVersion="" newVersion="" />

Voilà! It works now… Darn with the redirections…

Introducing Lucene2Objects

I’ve been playing with Lucene .NET for over 2 years now. It all started as part of my incorporation to a NLP investigation group and my first task was to look into Lucene since nobody was using it. I was baffled with the strength that Lucene had, besides, the biggest players were using it! Now that I’ve get to know it a bit better I see why so many people use it, put simple: It’s awesome! However, Lucene does have a problem which is the learning curve. Wrapping your head around the concept of documents, queries, analyzers and how to get a pseudo efficient search working are a few of the issues with using Lucene on a project.

Enter Lucene2Objects, my basic idea is to make a simple interface into Lucene for those developers wanting to incorporate search annotations into the domain model. Now, let’s take an example of a system handling messages (of the “Hi! How do you do?” kind, not the WM_PAINT kind), is most probably that users would like to search for something inside their messages. A (very) basic approach gives us a simple class:

public class Message
 public int Id { get; set; }

 public string Text { get; set; }

 public string Title { get; set; }

 public DateTime Sent { get; set; }

This is neat, but if I want to implement search I can either use the services provided by my DB backend as Full Text Indexing from SQL Server (which is awesome by the way, but lacks some other cool stuff) but the biggest problem is that we would then be fixing (or tightly coupling, for the fan boys of OOP/IoC/SOLID) the data store to the solution of finding a text, which is almost definitely a bad thing.

Now, if we want to use Lucene, we need to make a few configuration stuff, learn some stuff about indexing, tokenizers, analyzers and a huge list of stuff that some folks (me included) find amusing, but others find really boring (not to mention those who find it daunting). But imagine a world where you could do something like this:

var iWriter = new IndexWriter(Environment.CurrentDirectory + @"index");
var message = new Message { Id = 12, Sent = DateTime.Now, 
                            Text = "Some text on the message!", 
                            Title = "This is the title" 

Cool uh? Just point a folder and save. Nice! Well, and how would I search for stuff on that folder? Easy piece

var iReader = new IndexReader(Environment.CurrentDirectory + @"index");
var messages = iReader.Search&lt;Message&gt;("text");

foreach (var message in messages) {
 Console.WriteLine("Message: {0}", message.Title);

Fine! And how does my model knows where to search? What to index? What not to index? Well, validations were a similar issue, so, why not give it a similar solution? Just annotate away!

[SearchableEntity(DefaultSearchProperty = "Text")]
public class Message
 public int Id { get; set; }

 public string Text { get; set; }

 public string Title { get; set; }

 public DateTime Sent { get; set; }

 public DateTime? Read { get; set; }

If you liked that way of handling things with Lucene, you’ll love Lucene2Objects. Keep in mind however, that I’m the only person working with this idea, so if you like it and want to put something into it, let me know! For now, I’ll leave the Lucene2Objects as a package in Nuget, so you can play with it. I’ll put it into my BitBucket repo this week along with my Scaffolders for SharpLite.

SharpLite scaffolding is out! (beta)

This simple post is to show how to gt started using s small Scaffolder I made for SharpLite projects. It takes as input a contoller name and generates the controller to use with a SharpLite repository and the views using the regular Mvc3 scaffolding from Steven Sanderson. As a disclaimer, my code is just some tweaks different from the actual scaffolder from Steven Sanderson, and I haven’t tested it too much so don’t take this as a final product. I will, however keep working on this as time goes by and hopefully we may add some more new stuff!

Ok, enough of that! Just install the package from the NuGet feed…

Install-Package SharpLite.Scaffolding

Fire up your Package Manager Console and assuming you have an entity called Product and you want to make your own controller to manage products, just type:

 Scaffold slController ProductsController 

That’s it! This is a quite quick and dirty Scaffolder, but as I said, I will keep doing some more stuff into it. If you have any doubts or issues, feel free to comment or just send me a mail.

EDIT: For those of you who want to check out the source code of the scaffolders and follow the project, the code is hosted here

Using Sharp Lite with Fluent nHibernate

One thing I didn’t liked too much when first met S#arp Lite was the fact that Billy McCafferty decided to drop Fluent nHibernate as the defacto mapper for entities. There was a big discussion on the matter of nHibernate making it’s own fluent (or was it Loquacious?) API to map entities on a lot of places, and finally James Gregory, the man who gave us Fluent nHibernate spoke on the matter of nHibernate making an API that looked a lot like his.

The conclusion is pretty simple, Fluent nHibernate is not dead, not even close, there are a lot of folks (me included) that like it and we are not willing to let it go. Having said that, I wanted to integrate my Fluent nHibernate into S#arp Lite, and just as Billy said, is a dead simple thing to do, still will share it here.

The first thing you need to do is to reference the Fluent nHibernate library from your NorthwindDemo.NHibernateProvider project, so you can use it there. After that, you can make your own mappings on the provider. If you don’t know what is a Fluent Mapping, you should read this wiki before you start here. Now that we have our mappings made, we need to change the nHibernate boot process found in NHibernateInitializer so we use Fluent nHibernate instead. Go to the NHibernateInitializer class and change the code for this:

public static Configuration Initialize()
 var cnf 
          = Fluently.Configure()
    x => x.Database("MyDb")
       .Mappings( m => m.FluentMappings.AddFromAssemblyOf&lt;CustomerMapping&gt;());

 var configuration 
          = cnf.BuildConfiguration()
        .Proxy( p => p.ProxyFactoryFactory&lt;DefaultProxyFactoryFactory&gt;() )

 return configuration;

Notice that I’m not using SQL Express like the default install uses, I’m using MySQL instead. The magic of the thing is on the line:

.Mappings( m => m.FluentMappings.AddFromAssemblyOf<customerMapping>()); 

Here, I’m telling FNH to load all the mappings specified in the assembly of CustomerMapping, which is one of my entities’ mappings. After that, we register the DefaultProxyFactoryFactory to manage the lazy loading, which basically gets rid of the old nHibernate.Castle so we don’t have to use an external loader for proxy classes. With this configuration, you should be on your way to use Fluent nHibernate with your S#arp Lite project.

Finally, there is one thing. I think, not so sure though, that there is a version of Fluent NH for nHibernate 3.2, however, if you are using an older one, like me!, I’m using v1.2 which looks for nHibernate 3.1, you will need to make an Assembly redirect, which is easy, just lk in your web.config file for this line:

 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
   <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
   <bindingRedirect oldVersion="" newVersion="" />

And change it for this one:

 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
   <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
   <bindingRedirect oldVersion="" newVersion="" />
   <assemblyIdentity name="NHibernate" publicKeyToken="aa95f207798dfdb4" culture="neutral" />
   <bindingRedirect oldVersion="" newVersion="" />

The basic idea is to tell the system that when someone (FNH) asks for nHibernate from version to the assembly to resolve is version, so the binding is done properly. This should be it, you should have your own S#arp Lite project running on Fluent nHibernate!!

Happy coding! And as usual, comenting is not forbidden 😉

Booting Sharp Lite and autogenerating Db with nHibernate

When facing a new project, there are many things to consider, but there is no doubt that the words most mentioned and given more buzz are how to accomplish a scalable and maintainable solution without builing the next Amazon for our first version. However, trying to make a solution that is able to grow over time and adapt to new requirements is not an easy task, it’s indeed very tricky business. That’s why there are frameworks, mainly because there are a bunch of guys willing to help those who can’t (or won’t) get into building their own foundation to make a project.

And here is where S#arpArchitecture enters. S#arpArchitecture is project started by Billy McCafferty, a developer/architect well versed on the matter how made a super duper framework to deploy ASP .NET applications. The framework was consistent with several best practices he wrote on a CodeProject article on how to accomplish a nice setup of a project using nHibernate. The thing with S#arpArchitecture is that it was somehow a bit coupled into nHibernate, altough this didn’t seemed to matter at that point because nHibernate was (and IMHO is, but won’t get into that) the best way to accomplish ORM with a .NET project. However, time has changed and EntityFramework is a strong project, not to mention that is handled by the man, we also have now the NoSql fever and there are other stuff that may be yet to come and S#arpArchitecture had to evolve to remove the direct dependencies from nHibernate but as any old project moving away from the original idea has been a difficult business and the most important thing is that to be able t setup a S#arpArchitecture install using other thing than nHibernate, you’ll have to be very versed on topics such as IoC, design patterns, nHibernate itself, so you know what to remove and what not to remove and many other dark stuff.

Because of all these nasty reasons, Billy McCafferty decided to start yet another framework called S#arp Lite. The intention here was to be able to make a decent framework available for a broader audience of developers who didn’t had to be very versed on deep matters of architecture.

So, if you want to make an ASP .NET MVC 3 app and looking for a nice development framework, you should make a run for S#arp Lite and try it out. The first thing you’ll need is to read the blog post where Billy explains why he had to make S#arp Lite despite the fact that we already had a S#arpArchitecture, once you’ve read that, you should also get the basics on S#arp Lite also explained by Billy in this post. If, however, you don’t want to read any of those and just want to jumpstart into S#arp Lite, then the idea would be to:

Before anything, the sample app is found inside the S#arp Lite file downloaded from Github, on the folder called Example, the project is named MyStore. Now, to set up your database for the sample app, you can make two things, one I like it, the other not so much. Before getting to that, make sure that you have a SQL Server database to play with and get your connection string. Mostly if your DB is the integrated SQL Server Express DB that comes with Visual Studio, your connection string will look like this one:

Data Source=localhostsqlexpress;Initial Catalog=SampleDb;Integrated Security=True

The only thing that may change is the Initial Catalog, which is basically up to your choosing. Now that we know the connection string, we need to tell S#arp Lite what is it, so open the web.config file found on MyStore.Web and look for the line where says:

   <add name="MyStoreConnectionString" connectionString="YOUR_CONNECTION_STRING" />

And yes, you guessed it, change where it says YOUR_CONNECTION_STRING for the actual connection string.

Now we just need to setup our DB, for which you have two ways. The first way is the simplest one, which is to use a SQL server administration tool, the Management Studio Express included with the Express version of SQL Server express 2008 is just fine, and run the sql file you can find inside the example project on the folder called “MyStore.DB” et voilà! The project can now be run.

As a side note, the last time I downloaded S#arp Lite (v0.42), when setting up the sample project and compiling, you’d get 11 errors regarding tests and test classes that cannot be found, don’t despair! Just go into MyStore.Tests and remove the reference to nunit.framework and add it again, the assembly should be in your lib folder outside of the project. Now you can run the demo without issues!

Now the other way, which I like a lot more is to use nHibernate to generate your database, which is so cool! And since nHibernate is also very cool, this is a very simple process. Just go into your project called “MyStore.NHibernateProvider” and look for the class called NHibernateInitializer. Just like the name indicates this fellow handles the initialization of nHibernate and we will also generate the DB with it. Go into the class and add the method that will handle DB initialization:

public static void CheckAndBuilDb(Configuration cfg)
 var schemaValidator = new SchemaValidator(cfg);

 try {
 catch (Exception) {
  var schemaBuilder = new SchemaExport(cfg);
  //drop in case of old one
  schemaBuilder.Drop(false, true);
  schemaBuilder.Create(false, true);

Without entering into unnecessary gory details, the idea is to check if the existent DB is up to date and if is not, drop it and regenerate a new one. This does bring a bad side effect, which is the issue of migrating from one version into another. That problem can be fixed doing some nHibernate-fu, but we won’t get into that for now. Build and run and your database will be automatically generating against the mapped entities! Cool uh?

This is pretty much just about it, I’ll make a follow up post with some more stuff on how to get going with S#arp Lite and Fluent nHibernate.

UISpringBoardButton to get started

For a while now, Apple has been delighted in defining the de facto standard for the look of most of the applications in the App store. Which takes me to my next point, when we create a UIButton, we get a look that is pretty much the same always, except when we specify a background image, but then again, we need to comply with several UI rules to be able to use all the buttons and images quite nicely.

There is one type of button that I always liked the way they look, and those are the welcome screen buttons or the SpringBoard. In one of my current projects, I had to mimic how these icons look, needless to say, I went down into Stack Overflow looking for ideas and I did found some nice ideas.

So, the main task was to create some sort of UIButton with a UILabel below placing some sort of caption and showing and also reproducing the shiny icon on the button. To accomplish this, we first need to subclass the UIButton class, which brings us all the basic interactions with a button. So, basically, we’d had something like this:

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "ImageHelpers.h"

@interface UISpringBoardButton : UIButton

//Name of the icon to load from the project
@property (nonatomic, retain) NSString * IconName;

//Title of the button
@property (nonatomic, retain) NSString * ButtonTitle;

//This is where the magic happens
- (id)initWithFrame:(CGRect)frame andIcon:(NSString*) iconName andText:(NSString*) ButtonText;
- (void)initButtonWithSize : (CGSize) buttonSize;
- (void) createButtonWithFrame: (CGRect) buttonFrame;


First, we have 2 properties that will retain the name of the Icon that will represent our button and the Title of the button, which will be displayed in the UILabel below it. For now, I will just focus on getting the job done, and for those of you enjoying “copy + paste” the code was made using XCode 4.2 in the ARC age, so you should remember that. If you are as newb as I was a few weeks ago and didn’t knew what the heck ARC was, then consider checking out this. Having said all that, Let’s go into the code! First, you should make yourself an extender method for resizing images, I made a class like this one:


//Sorry about the name, old C# habbits...
@interface UIImage (ImageHelpers)

- (UIImage *)getIconOfSize:(CGSize)size withOverlay:(UIImage *)overlayImage;
- (CGContextRef)createBitmapContextOfSize:(CGSize)size;
- (UIImage *)scaleImage:(UIImage *)image toResolution:(int)resolution;


With the exception of the first method, the other two I took them from Fulvio’s implementation in his answer this question. Thanks for that Fulvio! Without further ado, this is how the first method would be now:

- (UIImage *)getIconOfSize:(CGSize)size withOverlay:(UIImage *)overlayImage 
    UIImage *icon = [self scaleImage:self toResolution:size.width];
    CGRect iconBoundingBox = CGRectMake (0, 0, size.width, size.height);
    CGRect overlayBoundingBox = CGRectMake (0, 0, size.width, size.height);
    CGContextRef myBitmapContext = [self createBitmapContextOfSize:size];
    CGContextSetRGBFillColor (myBitmapContext, 1, 1, 1, 1);
    CGContextFillRect (myBitmapContext, iconBoundingBox);
    CGContextDrawImage(myBitmapContext, iconBoundingBox, icon.CGImage);
    if ( overlayImage != nil )
        CGContextDrawImage(myBitmapContext, overlayBoundingBox, overlayImage.CGImage);
    UIImage *result = [UIImage imageWithCGImage: CGBitmapContextCreateImage (myBitmapContext)];
    CGContextRelease (myBitmapContext);
    return result;

Now that we have our helper (refered in the #import “ImageHelpers.h” line as well) we can code the button at ease. First, we need to synthetize our properties, coming from a Visual Studio background, I’m still wondering why XCode can’t do this for me, but I’m hopeful to see some nice products soon. Sigh… anyways, here it goes:

@implementation UISpringBoardIcon

@synthesize IconName;
@synthesize ButtonTitle;

Good stuff starts now, we need to write a new init method much like the initWithFrame, but with some extra stuff and then we call to the guy that is going to take care of assembling the control:

- (id)initWithFrame:(CGRect)frame andIcon:(NSString*) iconName andText:(NSString*) ButtonText
    self = [super initWithFrame:frame];
    if (self) 
        self.IconName = iconName;
        self.ButtonTitle = ButtonText;
        [self createButtonWithFrame: frame];
    return self;

Once we build the button we call the createButtonWithFrame method that handles creating the UILabel, placing it in the according place, aligning the text in the center and placing the lineBreakMode so that the system handles breaking the text accordingly if is too big.

- (void) createButtonWithFrame: (CGRect) buttonFrame
    CGSize sz = [ButtonTitle sizeWithFont: [UIFont systemFontOfSize: 10]];
    float width = self.frame.size.width;
    float y = self.frame.size.height - sz.height;
    //Need to add some space between the button and the UILabel
    CGRect labelFrame = CGRectMake(0, y + 5, width, sz.height);
    UILabel * textLabel = [[UILabel alloc] initWithFrame: labelFrame];
    textLabel.text = ButtonTitle;
    textLabel.font = [UIFont systemFontOfSize:10];
    textLabel.textAlignment = UITextAlignmentCenter;
    textLabel.lineBreakMode = UILineBreakModeMiddleTruncation;
    [self addSubview:textLabel];
    CGSize buttonSize = CGSizeMake(buttonFrame.size.width, buttonFrame.size.height - sz.height - 5);
    [self initButtonWithSize: buttonSize];

Now, all we need is to create the button using the overlay provided by rpetrich on his answer to the same question stated above. Actually, using Fulvio’s code this is a pretty simple process:

- (void)initButtonWithSize : (CGSize) buttonSize
    UIImage *overlayImage = [UIImage imageNamed:@"AppIconOverlay.png"];
    UIImage *image = [UIImage imageNamed: IconName];
    UIImage *profileImage = [image getIconOfSize:CGSizeMake(50, 50) withOverlay:overlayImage];
    self.imageView.layer.masksToBounds = YES;
    self.imageView.layer.cornerRadius = 10.0;
    self.imageView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.imageView.layer.borderWidth = 1.0;
    [self setImage: profileImage forState: UIControlStateNormal];

This is it! Creating a new one is very easy, just one line of code:

  UISpringBoardIcon * button = [[UISpringBoardIcon alloc] 
                                      initWithFrame: frame 
                                            andIcon: @"tux-icon.png"
                                            andText: @"Going home"];

The result should look like this:

Hope this can help! As usual, comenting is not forbidden.

Edit The source code can be downloaded here from my dropbox.

Hello iOS!!!

I’ve been playing with the idea of doing some mobile development for some time now, but never had the time to do it. Guess what?? I’m really digging into iOS now! For the time being with a borrowed Macbook (they’re so expensive!!) but I should get my Mac Mini by the end of this year (Santa has been good to me!).

Does this mean that I’m done with PHP or C#? Nope, but I should be really busy with iOS for a while now. Hope I can write something cool soon!!!