Testing S#arp Lite Repositories with Moq

1 comments

One pending matter I've always had is to improve my testing skills, there I said it. I test, but not as much as I should. When I say test, I mean Unit Test, not just test the application by launching it and starting to poke it. One thing that I found to be a really outstanding idea with S#arp Lite is that repositories eliminated many complications. If you had a repository and needed to run a query against it, just call GetAll and throw some Linq at. Grated, it assumed that the Linq provider for the underlaying data model was mature, but with NHibernate and EntityFramework being the two ORM of my choice always, that seems like a fair assumption.

However, this has a downside, I tried to test the repositories and had a really rough time getting to test a repo that was using an underlying IQueryable item. However, this became quite clear with time, and now I can test my repos. Let's make a fairly simple test scenario. Let's assume I have a user class, with a few standard properties, pretty much like this one:

public class User : Entity
{
 public virtual string Password { get; set; }

 public virtual string Email { get; set; }

 public virtual bool Blocked { get; set; }

 public virtual int LoginCount { get; set; }
} 

Now, I have a class called Membership that handles my Membership logic, that is, logging users, blocking them after a couple of bad logins, etc. That class should look like this:

public class Membership
{
 IRepository<User> _usersRepository;

 public Membership( IRepository<User> usersRepository )
 {
  _usersRepository = usersRepository;
 }
 
 public bool IsValidUser( string email, string password )
 {
  //create test first!
  return false;
 }
} 

Now, we need to create a test case. Let's call it, MembershipTests

[TestFixture]
public class MembershipTests
{
 [TestFixtureSetUp]
 public void SetupTestEnvironment()
 {
 
 }
}

Now, I want to create a Mock repository to pass it along to my test Membership class, but I need to do it so that it simulates the data backed without touching my actual data nor getting too slow. Obviously we need a list, but not just any list, we need a list that can pose for a Repository or at least fake it. That's why we need to create this sort of list, a QueryableList:

public class QueryableList<T, TId> : List<T>, IQueryable<T> where T : EntityWithTypedId<TId>
{
 #region Constructors
 public QueryableList()
 { }

 public QueryableList(IEnumerable<T> source)
  : base(source)
 { } 
 #endregion

 #region IQueryable<T> implementation
 public Expression Expression
 {
  get { return ToArray().AsQueryable().Expression; }
 }

 public Type ElementType
 {
  get { return typeof(T); }
 }

 public IQueryProvider Provider
 {
  get { return ToArray().AsQueryable().Provider; }
 }
 #endregion

 public void UpdateEntity(T entity)
 {
  var index = -1;

  for (var i = 0; i < Count; i++)
   if (this[i].Equals(entity))
    index = i;

  if (index == -1)
   Add(entity);
  else
   this[index] = entity;
 }
} 

Voila! We have a List that directly implements IQueryable, which is a good thing, not a hard thing to do, but it will help us a lot. We need to get the entity of the List and the Id that is going to be used on the list to keep it as generic as possible, so when we need to test a repo of entities with typed id's, we won't have to rewrite much. The UpdateEntity method will mimic the SaveOrUpdate method we have on our repo using the Equals method to invoke the Equality comparer provided by S#arp Lite. Now, we need to setup our Mocks. We go back to the TestSetup and let's setup our environment:

[TestFixture]
public class MembershipTests
{
 private Membership _membership;
 
 [TestFixtureSetUp]
 public void SetupTestEnvironment()
 {
  var usersMockedRepo = new Mock<IRepository<User>>();
  
  var users = new List<User> { new User{ Blocked = false, Email = "david@someplace.com", Password = "a password" } };
  var list = new QueryableList<T, int>(users);
  
  //Mock GetAll
  usersMockedRepo.Setup(x => x.GetAll()).Returns(list);
  
  //Mock the Get
  usersMockedRepo.Setup( x => x.Get( It.IsAny<int>() ))
      .Returns( (int id) => list.AsQueryable()
      .SingleOrDefault(x => x.Id.Equals(id)));
  
  //Mock the SaveOrUpdate using our own
  usersMockedRepo.Setup(x => x.SaveOrUpdate(It.IsAny<T>()))
      .Callback((T entity) => list.UpdateEntity(entity));
      
  //Mock the delete
  usersMockedRepo.Setup(x => x.Delete(It.IsAny<T>())).Callback((T entity) => list.Remove(entity));
  _membership = new Membership(usersMockedRepo.Object);
 }
}

Now, we have setup our very own mocked repository. We need to make a test now for the IsValidUser method we left before. Let's write a simple test case:

[TestCase]
public void CheckBasicAuthentication()
{
 var checkValidUser = Membership.Instance.IsValidUser("david.conde@gmail.com", "a password");
 var checkInvalidUser = Membership.Instance.IsValidUser("david.conde@gmail.com", "another password");

 Assert.AreEqual(checkInvalidUser, false);
 Assert.AreEqual(checkValidUser, true);
}

And that's it! We have our own test and we can now create as many test cases as we want all relying on a simple structure like a list. There is one final thought here, which came to mind while reading this StackOverflow post. The idea is to put the setup into a helper method, so we can reuse it with different test scenarios:

Please note that the following code can induce headaches :)

public static class MockExtensions
{
 public static void SetupIQueryableTypedRepository<T, TId>
  (this Mock<IRepositoryWithTypedId<T, TId>> mockObject, IEnumerable<T> source)
  where T : EntityWithTypedId<TId> where TId : IComparable
 {
  var list = new QueryableList<T, TId>(source);

  mockObject.Setup(x => x.GetAll()).Returns(list);
  mockObject.Setup(x => x.Get(It.IsAny<TId>())).Returns((TId id) => list.AsQueryable().SingleOrDefault(x => x.Id.Equals(id)));

  mockObject.Setup(x => x.SaveOrUpdate(It.IsAny<T>())).Callback((T entity) => list.UpdateEntity(entity));
  mockObject.Setup(x => x.Delete(It.IsAny<T>())).Callback((T entity) => list.Remove(entity));
 }

 public static void SetupIQueryableRepository<T>(this Mock<IRepository<T>> mockObject, IEnumerable<T> source)
  where T : Entity
 {
  var list = new QueryableList<T, int>(source);

  mockObject.Setup(x => x.GetAll()).Returns(list);
  mockObject.Setup(x => x.Get(It.IsAny<int>())).Returns( (int id) => list[id] );
  
  mockObject.Setup(x => x.SaveOrUpdate(It.IsAny<T>())).Callback( (T entity) => list.UpdateEntity(entity) );
  mockObject.Setup(x => x.Delete(It.IsAny<T>())).Callback((T entity) => list.Remove(entity));
 }
}

Now, we can reduce our Setup method to this:

[TestFixtureSetUp]
public void SetupTestEnvironment()
{
 var usersMockedRepo = new Mock<IRepository<User>>();
 var users = new List<User> { new User{ Blocked = false, Email = "david@someplace.com", Password = "a password" } };
 
 usersMockedRepo.SetupIQueryableRepository(users);
 _membership = new Membership(usersMockedRepo.Object);
}

If you just want to be able to test your S#arp Lite repositories using this, then just get this extension to your code, set your mocked repositories using this idea and done! If you have any other thoughts, let me know on the comments!

Lucene2Objects roadmap

2 comments

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 v1.2 released!

0 comments
I've just uploaded Lucene2Objects 1.2 into Nuget, so if you haven't had the time to play with it, this is a good moment to start! If you want to share something, ask for help or just scream, let me know in a comment

Lucene2Objects goes public!

0 comments
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, David

S#arpLite: "At least one ISessionFactory has not been registered with IoC", Darn with the redirections...

4 comments

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...

<dependentAssembly>
 <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
 <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
 

VoilĂ ! It works now... Darn with the redirections...

Introducing Lucene2Objects

6 comments

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" 
              };
iWriter.AddEntity(message);
iWriter.Close();

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<Message>("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; }

 [Indexed]
 public string Text { get; set; }

 [Indexed]
 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)

2 comments

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

2 comments

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()
      .Database(MySQLConfiguration.Standard.ConnectionString( 
    x => x.Database("MyDb")
          .Username("MyUserName")
          .Password("MyPassword")
          .Server("MyServer"))
   )
       .Mappings( m => m.FluentMappings.AddFromAssemblyOf<CustomerMapping>());

 var configuration 
          = cnf.BuildConfiguration()
        .Proxy( p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>() )
        .CurrentSessionContext<LazySessionContext>();

 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()); 
 

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:

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

And change it for this one:

<runtime>
 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
   <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
   <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
   <assemblyIdentity name="NHibernate" publicKeyToken="aa95f207798dfdb4" culture="neutral" />
   <bindingRedirect oldVersion="0.0.0.0-3.1.0.4000" newVersion="3.2.0.4000" />
  </dependentAssembly>
 </assemblyBinding>
</runtime>
 

The basic idea is to tell the system that when someone (FNH) asks for nHibernate from version 0.0.0.0 to 3.1.0.4000 the assembly to resolve is version 3.2.0.4000, 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

1 comments

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=localhost\sqlexpress;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:

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

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 {
  schemaValidator.Validate();
 }
 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.