RavenDB – Searching across multiple properties

January 18th, 2012 1 comment

Ayende recently posted about Orders Search in RavenDB which got me a little bit excited, since I was pondering how I would do searching in RavenDB without having Full Text Searching from SQL Server.

So digging into it I wanted to try it out for myself how to use it. Given the model:

    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public IEnumerable<string> Tags { get; set; }
        public DateTime DatePosted { get; set; }
    }

I’ve setup 10 posts (click here for the insert pastie) just with some really basic data.

So I’m going to detail here all the data that I’ve setup.

Tags

Tag Name # of Posts Containing Tag
html 3
c# 6
ravendb 4
nhibernate 3
javascript 1
coffeescript 2
less 3
search 6
closures 1
jquery 2
css 1
queryover 2
mapreduce 4

Titles

Nothing interesting, just ‘Test Post X’ for each one to identify them.

Description

Basically for this testing I’ve taken the blog post names of a few things from Google Reader, that some-way relate to the tags above. Take a look at the script mentioned above to see the data.

Creating the Index

So the first thing I want to do is create a Map with a Reduce Result, but we aren’t going to add the Reduce to the index, since we don’t need it to store that data or do anything with it. We purely want the Reduce Result that matches the map, so that we can query against it.

public class Post_Search : AbstractIndexCreationTask<Post, Post_Search.ReduceResult>
{
    public class ReduceResult
    {
        public object[] SearchQuery { get; set; }
        public DateTime DatePosted { get; set; }
    }

    public Post_Search()
    {
        Map = posts =>
            from post in posts
            select new
            {
                SearchQuery = post.Tags.Concat(new[]
                                                {
                                                    post.Description,
                                                    post.Title
                                                }),
                DatePosted = post.DatePosted
            };
    }
}

This index is a little bit funky, and differs from what Ayende showed in his example. I wanted to try something a little different.

In my scenario I have a collection of Tag’s that I wanted to include in the search, this the tags is already a collection, I concatenate the additional array of items I want to add into the map.

The SearchQuery is the property that we will search against, while the DatePosted wont be included in the Search, but is there to provide additional filtering on my search.

Querying

Querying threw me off at first, because in order to query against this index, we have to specify the ReduceResult class.

So we end up with the starting of our query looking like this:

var result = session.Query<Post_Search.ReduceResult, Post_Search>()

At first I thought “oh, that means we end up with a ReduceResult result type, this is pointless and useless”. But I commented on Ayende’s blog post and it turns out we can call ‘As<T>’ on the query.

Without filtering the results just yet, our query would look like the following:

var result = session.Query<Post_Search.ReduceResult, Post_Search>()
                    .As<Post>()
                    .ToList();

So if I run this up now, for a quick test, I should get 10 results back of type Post

image

Great!

So now I need to begin filtering out the results. To begin with I’m doing to use the .Where extension. Since we are looking an object array, we can’t directly compare it to a string, but if we explicitly cast it to an object we can look for:

coffeescript expecting 2 results:

var result = session.Query<Post_Search.ReduceResult, Post_Search>()
                    .Where(x => x.SearchQuery == (object)"coffeescript")
                    .As<Post>()
                    .ToList();

 

image

How about javascript expecting 2 (1 via Tag and 1 via the Description)

image

Oh, we didn’t get the desired result… This is because the search is only doing a search on an exact match. Since the search value is an exact match of the tag, the result is returned.

So to fix this we need to make the index analysed. Adding to the index:

Index(x => x.SearchQuery, FieldIndexing.Analyzed);

If we run the exact same query again:

image

Now we get 2 results.

Now to try something a little bit different, using ‘Search’, if we wanted to search for something like mvc which happens to only be in the description, rather than using ‘Where’ like shown above, we can use ‘Search’ like so:

var result = session.Query<Post_Search.ReduceResult, Post_Search>()
                    .Search(x => x.SearchQuery, "mvc")
                    .As<Post>()
                    .ToList();

This will give us the same result, except it looks much cleaner

image

Now there’s 1 catch I’ve found with this, which is searching is always an exact match. I’m not sure (no research done into lucene yet) if lucene has the ability to do a wild-card type search similar to SQL like: ‘%mvc%’, but you can get suggestions from this.

For example if I search for ‘coffee’ rather than ‘coffeescript’ I would expect all documents containing ‘coffee’ to be returned. This doesn’t happen. It does give you suggestions though.

Looking at the management studio for ‘coffee’ :

image

Side Comment: I think it would be cool if RavenDB provided the ability to have say include suggestions, like:

var result = session.Query<Post_Search.ReduceResult, Post_Search>()
                    .Search(x => x.SearchQuery, "coffee")
                    .IncludeAllSuggestions()
                    .As<Post>()
                    .ToList();

Or other variations such as:

.Suggestions.IncludeAll()

.Suggestions.IncludeTop(3)

.Suggestions.IncludeAll(WhenResults.AreEmpty)

.Suggestions.IncludeAll(WhenResults.AreLessThan, 10)

Hopefully you can work out where I’m going with this?

Ok continuing on. Why do we need to call ‘As<T>()’ on the query?

Well from my understanding of how RavenDB works is like this, when we create an index, it’s creating a sub-set of data that points to the document in RavenDB.

For example I have all those documents inserted (link for the lazy), and these are all stored like so:

image

When we created the index with the following Map:

Map = posts =>
    from post in posts
    select new
    {
        SearchQuery = post.Tags.Concat(new[]
                                        {
                                            post.Description,
                                            post.Title
                                        }),
        DatePosted = post.DatePosted
    };

It basically created an index that looks like this, for the data above:

posts/2 SearchQuery: ["c#", "nhibernate", "search", "queryover", "Benjamin Day slides us into "How to be a C# ninja in 10 easy steps"", "Test Post 2"
DatePosted: "2012-01-02T00:00:00.0000000"

So the index actually points directly to a Document in RavenDB, when we search against the index, if a match is found, the index returns the Id ‘posts/2’ back, and that knows to go to the posts collection and grab the document with Id 2.

The problem with the query is we need to specify an object to query against.

So we introduced the ReduceResult (not sure on this naming but I took it from Ayende’s blog), this allows us to specify the Properties we defined in our index, as search criteria, but now our query is expecting ReduceResult:

image

By specifying as we are telling the query that our result is going to be a type of ‘Post’:

image

Conclusion

This functionality is really cool, it allows us to easily search against multiple different properties without having to create messy conjunctions in our LINQ. If we were to attempt to do this without an index, we would probably end up writing something like:

var result = session.Query<Post>()
                    .Where(x =>
                            x.Description.Contains("c#")
                            ||
                            x.Tags.Any(y => y == "c#")
                            ||
                            x.Title.Contains("c#")
                        )
                    .ToList();

And really, that’s just nasty… Specially considering we get the same results for writing more readable code:

image

Categories: RavenDB Tags: , , ,

RavenDB – Map Reduce

December 22nd, 2011 No comments

So, learning Map Reduce in RavenDB I decided that to take what I learnt from the index created in my previous post. I think I picked something rather difficult to begin with, but I’ve succeeded Smile

Given a document Article which has a collection of Tags.

I want to get a Count of each Tag across all Articles.

public class Content
{
    public int Id { get; set; }
    public string Title { get; set; }

    public IEnumerable<Tag> Tags { get; set; }
}

public class Tag
{
    public string Name { get; set; }
}

Note: Tag is it’s own class because I added additional properties to it.

Now I insert some data:

using (var session = documentStore.OpenSession())
{
    session.Store(new Content
    {
        Title = "Test Title for a Video",
        Tags = new List<Tag>
        {
            new Tag() {Name = "c#"},
            new Tag() {Name = "autofac"},
            new Tag() {Name = "asp.net"},
        }
    });
    session.Store(new Content
    {
        Title = "Test Title for an Article",
        Tags = new List<Tag>
        {
            new Tag() {Name = "c#"},
            new Tag() {Name = "nhibernate"},
            new Tag() {Name = "fluent-nhibernate"},
            new Tag() {Name = "mvc"}
        }
    });
    session.Store(new Content
    {
        Title = "Test Title for an Article",
        Tags = new List<Tag>
        {
            new Tag() {Name = "ravendb"},
            new Tag() {Name = "asp.net"},
            new Tag() {Name = "autofac"},
            new Tag() {Name = "c#"}
        }
    });

    session.SaveChanges();
}

 

So I’m expecting a count of:

  • 3 x c#
  • 2 x autofac
  • 2 x asp.net
  • 1 x ravendb
  • 1 x mvc
  • 1 x nhibernate
  • 1 x fluent-nhibernate
  • I’m going to pull these out with a defined type rather than dynamic/object, so I’ve created a new class with Count and Name:

    public class TagResult
    {
        public int      Count   { get; set; }
        public string   Name    { get; set; }
    }

So creating a new Index:

public class All_Tags : AbstractMultiMapIndexCreationTask<TagResult>
{
    public All_Tags()
    {
    }
}

The first thing I need to do is map out ONLY the Tag’s, when I select out the Tag’s, I’m also going to include another field called Count, with a default value of 1. This is so I can re-use it to sum the total number of times the tag is used.

AddMap<Content>(contents => from content in contents
                            from tag in content.Tags
                            select new
                            {
                                Name = tag.Name,
                                Count = 1
                            });

This would give me a result that contains duplicates for the tags. Along the lines of:

c# 1
c# 1
c# 1
autofac 1
autofac 1
asp.net 1
asp.net 1
ravendb 1
mvc 1
nhibernate 1
fluent-nhibernate 1

So what I need to do in the Reduce, is group the tags together by their Name.

Reduce = results => from result in results
                    group result by result.Name into tag
                    select new
                    {
                        Count = tag.Sum(x => x.Count),
                        Name = tag.Key,
                    };

So here, I group all the tags together by their name, but I also sum the ‘count’ value together to get the total number of times the tag is used.

Now run up the app and view the index:

image

Now if I query the index:

image

Awesome. Now to query this, I have to use the TagResult class defined previously, and the All_Tags index just created.

using (var session = documentStore.OpenSession())
{
    var result = session.Query<TagResult, All_Tags>()
                        .ToList();

    foreach (var tag in result)
    {
        Console.WriteLine(tag.Count + " x " + tag.Name);
    }

    session.SaveChanges();
}

Running this I get the following result:

image

The results I expected previously.

So there you have it. Map Reduce.

Categories: RavenDB Tags:

RavenDB Inheritance–Revisited

December 14th, 2011 1 comment

So after my initial post on RavenDB Inheritance, and the issue I had with polymorphic queries, and seeking help from the guys in JabbR and the RavenDB Google Group, Ayende ended up doing a screen cast with me where he solved all my problems.

One of the things he asked me was what I was trying to achieve by having a polymorphic query, which was a very good question, something I hadn’t really thought about.

The problem I was trying to solve was actually displaying search results.

The Problem

So I’m working on a personal project, and I need to display a few things which are similar, but different. There’s 3 different types but I’ll use two to keep it simple. I’ve also cut out most of the properties.

So I have an abstract class Content, with two derived classes, Article and Video.

public abstract class Content
{
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime DatePublished { get; set; }
}

public class Article : Content
{
    public string HtmlContent { get; set; }
}

public class Video : Content
{
    public string Description { get; set; }
    public string VideoUrl { get; set; }
}

Then I initialize the DocumentStore and store a couple of documents.

var documentStore =
    (new DocumentStore()
            {
                Url = "http://localhost:8080"
            }).Initialize();

using (var session = documentStore.OpenSession())
{
    session.Store(new Video
    {
        DatePublished = DateTime.Now,
        Description = "Test Description for a Video",
        Title = "Test Title for a Video",
        VideoUrl = "http://www.youtube.com/watch?v=PGz9GokDkkg"
    });

    session.Store(new Article
    {
        DatePublished = DateTime.Now,
        Title = "Test Title for an Article",
        HtmlContent = "Some content for the article…"
    });

    session.SaveChanges();
}

This time I’m not using the Convention to store the two documents as ‘Content’, rather I’m allowing it to store them as what they are. This gives me a result in Raven like:

image

Now if I query for Video:

using (var session = documentStore.OpenSession())
{
    var result = session.Query<Video>().ToList();
    
    foreach (var content in result)
    {
        Console.WriteLine(content.Id);
        Console.WriteLine(content.Title);
    }
}

I get the output of the first Document.

image

Likewise if I select ‘Article’ I get the Article document that I previously stored.

So how do I get a list of Content?

The Solution

So, the solution is really, really easy, it’s an index.

The first thing Ayende showed me was creating the index in RavenDB Management Studio, then he showed me doing it in code. I’m just going to show it done in code.

I created a class called ‘All_Content’ (with an underscore) like so:

public class All_Content : AbstractMultiMapIndexCreationTask
{
    public All_Content()
    {
        AddMap<Article>(articles => from article in articles
                                    select new
                                                {
                                                    article.Id,
                                                    article.Title,
                                                    article.DatePublished
                                                });
        AddMap<Video>(videos => from video in videos
                                select new
                                            {
                                                video.Id,
                                                video.Title,
                                                video.DatePublished
                                            });
    }
}

It reminds me of writing a Union View in SQL Server in some ways. It basically maps to the Articles and Videos, but only selects the things I need. Those of which would actually be displayed to the screen or that are common between the two document types.

Then I create the index right after I initialize the DocumentStore:

IndexCreation.CreateIndexes(typeof(All_Content).Assembly, documentStore);

This creates the index in RavenDB for me.

image

As you can see, even tho I specified the class index with an underscore, it converts it to All/Content, that’s a really nice way of presenting it. I think it will go well for being able to create descriptive indexes in the future.

And the index itself:

image

Now I need to actually query against the index. That’s also really really easy. When I specify the type, I can specify the index with it:

using (var session = documentStore.OpenSession())
{
    var result = session.Query<Content, All_Content>().ToList();
    
    foreach (var content in result)
    {
        Console.WriteLine(content.Id);
        Console.WriteLine(content.Title);
    }
}

Now when I run this I get the output:

image

Awesome!

The really interesting thing I found is that if I look at what’s returned:

image

Are the correct CLR types that I originally defined. So I haven’t lost all the additional fields by not defining them. I’m still learning but for now I assume it allows those fields to be searchable.

Extras

One of the additional things Ayende showed me was that you can include other documents that don’t inherit from the base type. You can include those in the index map, and then rather than returning a concrete type, you can specify object, or dynamic.

var result = session.Query<dynamic, All_Content>().ToList();

RavenDB is really powerful. It’s truly amazing, and so much nicer to work with in .NET than other document databases like MongoDB.

Categories: RavenDB Tags:

RavenDB Inheritance

December 10th, 2011 1 comment

Edit: Updated solution: http://www.philliphaydon.com/2011/12/ravendb-inheritance-revisited/

Continuing my learning of RavenDB, I wanted to see how it handled Inheritance.

I found: http://ravendb.net/faq/polymorphic-indexes

Which showed what to do allow you to select over all types of ‘Animal’ for the example shown. So I wanted to see what happens before and after using this method.

So like the example shown I’ve created an Animal, with a Dog and Cat.

public abstract class Animal
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Dog : Animal { }
public class Cat : Animal { }

Now if I insert a Dog and Cat:

using (var session = documentStore.OpenSession())
{
    session.Store(new Dog() { Name = "Test Dog" });
    session.Store(new Cat() { Name = "Test Cat" });

    session.SaveChanges();
}

What’s stored in RavenDB is two separate documents, one for ‘dogs’ and one for ‘cats’.

image

If I include the Convention.

var documentConvention =
    new DocumentConvention()
        {
            FindTypeTagName =
                type =>
                    {
                        if (typeof (Animal).IsAssignableFrom(type))
                            return "animals";
                        return DocumentConvention.DefaultTypeTagName(type);
                    }
        };

Note: You can do the conversion when the DocumentStore is initialized, I broke the two up so that it would fit easier into my blog. Otherwise it’s too nested and yucky.

var documentStore =
    (new DocumentStore()
            {
                Url = "http://localhost:8080",
                Conventions = documentConvention
            }).Initialize();

Now when I insert a Dog and Cat I get:

image

Awesome. If we look at the document however:

image

There is no information about it being a cat or dog, I thought it would add some sort of discriminator similar to how NHibernate works.

However, if we look at the Metadata tab:

image

We can see the CLR type is stored in the metadata so RavenDB knows what type to create when we query it.

This means if we query for ‘Animal’ we get a list of Dogs and Cats.

using (var session = documentStore.OpenSession())
{
    var result = session.Query<Animal>();

    foreach (var animal in result)
    {
        Console.WriteLine(animal.Name);
    }
}

 

image

However, if you wanted to query for just Dogs, like so:

var result = session.Query<Dog>().ToList();

It doesn’t seem to work Sad smile

image

I’m probably just doing something wrong, either way, the more I play with RavenDB. The more I love it.

Categories: RavenDB Tags:

Post a collection of ViewModel’s to a MVC Action with jQuery

December 7th, 2011 No comments

Maybe I searched for the wrong thing, but I couldn’t find what I was looking for Sad smile My Bing and Google fu failed me.

Basically I wanted to post a collection of ViewModels to an MCV action. Turns out it’s rather simple.

Lets say I have a bunch of Products, and Products are managed in a WarehouseLocation. A product doesn’t have a warehouse location, since it could exist in multiple locations.

If I’m currently working in Location A, I want to post a collection of Products to an action, as well as the WarehouseLocationId.

So given a simple ViewModel, and an Action:

public class ProductViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

and

public JsonResult Update(int warehouseLocationId, IEnumerable<ProductViewModel> products)
{
    //Do something with the products…

    return Json(new {Staus = "success"});
}

I think usually when someone sends data from jQuery it’s usually a single parameter,so the JSON would look something like:

var data = { id: 1,name: ‘test name’, price: 15.95 };

This would populate an action that looked like:

public JsonResult Update(ProductViewModel product)

But what I was faced with was passing in two parameters, one of which is a collection…

MVC seems to pair up the posted result with the parameter name, in the same way they it does for Route parameters. So to the JSON needs to look like:

var data = {
    warehouseLocationId: 12,
    products: [{
        Id: 1,
        Name: "Product 1",
        Price: 15.95
    }, {
        Id: 3,
        Name: "Product 2",
        Price: 12.50
    }]
};

As you can see the key’s on the first level match the parameter names, while the array on products, match the ViewModel.

Taking this exact data and posting it to the action:

$.ajax({
        type: 'POST',
        url: '@Url.Action("Update", "Home")',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: function(result) {
            //Do something with result…
        },
        dataType: 'json'
    });

 

I submit that, and with a breakpoint on my action I see:

image

^ The warehouseLocationId…

image

^ 2 products with the values:

image

And:

image

The exact same data we defined in our JavaScript.

The really cool thing about this, is you can have nested collections also. Using the same scenario, but extending Product to have a collection of Categories like so:

public class ProductViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

    public IEnumerable<Category> Categories { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}

I can update the JSON object to include Category information on 1 of the two products:

var data = {
    warehouseLocationId: 12,
    products: [{
        Id: 1,
        Name: "Product 1",
        Price: 15.95
    }, {
        Id: 3,
        Name: "Product 2",
        Price: 12.50,
        Categories: [{
            Id: 1,
            Name: "Category 1"
        }, {
            Id: 1,
            Name: "Category 2"
        }]
    }]
};

And submit that in the same way as before, capturing the results in the Action we get the first product with null for the categories, since we didn’t define it as an empty array:

image

While the second Product has 2 items, the first item is Category 1, and the second item is Category 2.

image

image

And that’s it, easy peasy, sending a collection of ViewModels from jQuery to an MVC Action.

I <3 MVC Smile

Categories: MVC, jQuery Tags: , ,

Split Windows + Web Workbench = Win

November 27th, 2011 No comments

One of the cool features of the Web Workbench from Mindscape is the ability to generate the output files. Prior to using the Web Workbench I was using .LESS{} which uses an HTTP Handler to generate the output files for LESS.

The problem with this is sometimes I would write some CSS and not realise I missed something only to find my site doesn’t display anything, then I have to figure out what I did wrong.

With the Web Workbench, and it’s ability to generate the files every time I save, makes me less error prone.

But the most efficient way of working with it I found (when writing a lot of CSS in 1 sitting) is to split my windows so the first window has where I’m writing, and the second window has the generated CSS file.

image

If I make an error on the left side:

image

I see the error on the right.

If I make a change to the left, (added a background colour) i see the change on the right.

image

This makes it really handy when applying nested rules. Such as nesting a hover rule to an anchor tag. Sometimes I forget to include the colon.

image

Maybe in the next version of the Web Bench, Mindscape can include side-by-side windows that scroll with each other Open-mouthed smile Tho it would be difficult depending on how much CSS was generated. Would still be a nice feature.

Either way, the Web Workbench is a tool that can’t be missed.

Categories: General Tags: , ,

Optional Parameters with AttributeRouting

November 27th, 2011 3 comments

I found a little trick with using Optional Parameters with AttributeRouting, by using standard optional parameters in the action.

The documentation says you can add an attributes to specify the defaults, or add ‘=value’ to the parameter name, and I guess that’s a more correct way to generate routes, but you can achieve the same affect by making the parameter optional. Like so:

[GET("videos/{?page}")]
public ActionResult Videos(int page = 1)
{
    return View("Result");
}

If I browse to the URL:

image

It uses the default value of 1.

image

Now when appending a number to the end of the URL:

image

It captures the correct value:

image

I prefer this method, the optional parameter on the action is more quickly identified, than looking at the attribute to see the defaults. (in my opinion)

Ahh AttributeRouting, how I love you.

Unit of Work with WCF and Autofac

November 6th, 2011 No comments

I’ve just spent the last few days trying to find a way to have a Unit of Work with WCF, but it seems no one has a nice clean easy solution.

The first, and the only decent solution I found was here:

http://ianfnelson.com/archives/2010/04/09/wcf-nhibernate-unit-of-work-endpoint-behavior

The problem I found with this solution is that the ICallContextInitializer as well as the EndpointBehavior is only created once. So it would seem all calls to a service would share the same Unit of Work instance.

Maybe Castle Windsor does something fancy and injects a brand new EndpointBehavior every request to a service, but for me, it seemed the ServiceBehavior, EndpointBehavior, and ICallContextInitializer were all created once.

This caused my service to resolve a different instance of IUnitOfWork to what was in the ICallContextInitializer.

Interim Solution 1

The first solution I came up with was to use Autofac to call Commit on release:

builder.RegisterType(typeof (UnitOfWork))
        .As(typeof (IUnitOfWork))
        .InstancePerLifetimeScope()
        .OnRelease(x =>
                        {
                            ((IUnitOfWork) x).Commit();
                        });

It works… Smile but it seemed like a real hack, so I kept digging.

I posted on StackOverflow & Autofac Google Group, but so far I haven’t had anyone suggest a good solution.

Solution 2

The next took a while to come up with.

Note: I don’t know if this is an appropriate solution for utilizing a Unit of Work with WCF. It works for me but if there is a better solution I would like to hear it.

I started by giving all my classes an interface called IService.

public interface IService
{
    IUnitOfWork UnitOfWork { get; set; }
}

My Service implements this interface:

public class WasteInventoryQueryService : IWasteInventoryQueryService, IService
{
    public IUnitOfWork UnitOfWork { get; set; }
    public IWasteStockRepository WasteStockRepository { get; set; }

    public WasteInventoryQueryService(IUnitOfWork unitOfWork, IWasteStockRepository wasteStockRepository)
    {
        UnitOfWork = unitOfWork;
        WasteStockRepository = wasteStockRepository;
    }

    …
}

Next I created some behaviours similar to the linked article.

Since finding that the ServiceBehavior, EndpointBehavior and ICallContextInitializer all are created once, I started at the ServiceBehavior.

I created a class called EndpointResolverServiceBehavior, it’s purpose is to inject all the endpoint behaviours I create.

public class EndpointResolverServiceBehavior : IServiceBehavior
{
    protected IEnumerable<IEndpointBehavior> EndpointBehaviors { get; set; }

    public EndpointResolverServiceBehavior(IEnumerable<IEndpointBehavior> endpointBehaviors)
    {
        EndpointBehaviors = endpointBehaviors;
    }

    #region Implementation of IServiceBehavior

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }

    public void AddBindingParameters(ServiceDescription serviceDescription,
        ServiceHostBase serviceHostBase,
        Collection<ServiceEndpoint> endpoints,
        BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (var endpoint in serviceDescription.Endpoints)
        {
            foreach (var endpointBehavior in EndpointBehaviors)
            {
                endpoint.Behaviors.Add(endpointBehavior);
            }
        }
    }

    #endregion
}

Next I created an EndpointBehavior called UnitOfWorkEndpointBehavior, it’s purpose is to add the ICallContextInitializer instance.

public class UnitOfWorkEndpointBehavior : IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        foreach (DispatchOperation operation in endpointDispatcher.DispatchRuntime.Operations)
        {
            operation.CallContextInitializers.Add(new UnitOfWorkCallContextInitializer());
        }
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}

And then is the ICallContextInitializer.

public class UnitOfWorkCallContextInitializer : ICallContextInitializer
{
    private PropertyInfo _userObjectInfo;
    private readonly BindingFlags _flags = BindingFlags.NonPublic | BindingFlags.Instance;

    public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
    {
        if (_userObjectInfo == null)
            _userObjectInfo = instanceContext.GetType()
                                                .GetProperty("UserObject", _flags);
            
        return _userObjectInfo.GetValue(instanceContext, null) as IService;
    }

    public void AfterInvoke(object correlationState)
    {
        var uow = correlationState as IService;

        if (uow != null)
            uow.UnitOfWork.Commit();
    }
}

While debugging I found out that the InstanceContext has a private property which has the current service attached to it:

image

image

(click the image for a larger view)

So I reflected the property and casted it to an IService, and return the result. When the service has been invoked, the result passed out of the ‘BeforeInvoke’ method, is passed into the ‘AfterInvoke’.

image

So basically I return the result from the BeforeInvoke which is passed into the AfterInvoke. Then I attempt to cast it to an IService again.

If the cast is successful, then I can call Commit on my UnitOfWork.

The last piece is to wire up the Behavior with Autofac.

builder.RegisterType(typeof(UnitOfWorkEndpointBehavior)).As(typeof(IEndpointBehavior));
builder.RegisterType(typeof(EndpointResolverServiceBehavior)).As(typeof(IServiceBehavior));

Container = builder.Build();

AutofacHostFactory.Container = Container;
AutofacHostFactory.HostConfigurationAction =
    host =>
    {
        host.Description.Behaviors.Add(Container.Resolve<IServiceBehavior>());
    };

And it’s done. I have a working Unit of Work, that is injected into my Service and Committed after the service has been invoked.

The only down-side I see to all of this, is that if an exception is thrown that I don’t capture, then the UoW will still be committed regardless.

If anyone has any better solutions, let me know! Smile

Categories: WCF Tags: , ,

Windows Phone, Windows Live and MSN

November 2nd, 2011 1 comment

Windows Phone 7.5 has been getting some awesome reviews, and rightly so. The thing is amazing. I really think Microsoft has begun leading the way for the mobile platform.

But I’m highly pissed off with the Windows Phone team. Why? Because to use MSN, your msn contacts must be associated with the first live account you register to the phone.

I don’t even know what to say about this, it’s so silly. I understand that it might get confusing to allow multiple Facebook accounts, multiple Windows Live accounts, etc.

But could they not allow you to choose which account MSN contacts are associated to?

When I first setup my phone I didn’t use the Windows Live account I use for MSN (my Hotmail) since it’s existed since 1997, it’s got 100′s of contacts I don’t want in my phone-book, a lot of MSN contacts exist from work, or playing online games, or from forums etc. So I used the Windows Live account that I use for MSDN. I added all my contacts and everything was great, (after I imported all my contacts from outlook into Windows Live Contacts)

I attached my Facebook account, went to People > Settings > Filter Contacts, and turned off Facebook so they do not show in my normal contacts list. This allows me to have normal phone users, but see the Facebook users on the Messaging list.

Now I want to show MSN contacts, so I load up the next Windows Live account, it loads all my contacts, but when I go to messaging, I get NOTHING. No MSN users at all.

On my second Windows Phone (yes I have two) I reformatted it, and signed it up on my Hotmail Windows Live account, and what do I see? All my MSN contacts.

Ok so the team didn’t give us the option to select which Live account we can use for MSN… So I went to download IM+

DEAD END

ATTENTION MSN/WLM users! MSN/WLM is not supported in 1.7 version of IM+ due to Microsoft Marketplace request. If you would like to continue using MSN/WLM in IM+, do not update to 1.7 version from version 1.2. We will continue working on this situation with Microsoft.

WTF… So not only can I not use MSN on my phone natively. The team has blocked anyone else from providing the feature in their own applications…

That’s not fair at all.

Microsoft should be ashamed.

So as it stands, if you don’t use your MSN account as your Windows Phone account, you can’t use MSN.

Microsoft is definitely leading the way in Mobile platform, but they massively screwed up MSN for many users.

Categories: Rant, Windows Phone 7 Tags:

RavenDB – Changing the Lo on the HiLo Generator

October 24th, 2011 No comments

Well I’m currently learning RavenDB, it’s awesome! But I noticed when I put data in, all the Id’s generated every time I ran up my application to test were:

1, 2, 3, 4, 5…

1024, 1025, 1026, 1027, 1028…

2048, 2049, 2050, 2051, 2052…

This would be fine after the app is deployed since I wouldn’t be restarting it over and over and over, but during development I personally find it annoying that the numbers jump so high.

Fortunately I figured out a way. (which about an hour later I found on Google Groups, granted I had to use a different keyword to find it)

Basically you just need to create a new instance of the MultiTypeHiLoKeyGenerator class, passing in the arguments and assigning it to the document store:

var documentStore = new DocumentStore { Url = "http://localhost:12321/" };
documentStore.Initialize();

var generator = new MultiTypeHiLoKeyGenerator(documentStore, 10);
documentStore.Conventions.DocumentKeyGenerator =
    entity => generator.GenerateDocumentKey(documentStore.Conventions, entity);

using (var session = documentStore.OpenSession())
{
    session.Store(new Project() { Title = "Hello World" });
    session.SaveChanges();
}

So running up my app once:

image

And again:

image

Now the identity only increases every time the app restarts. And to show it generates more than 1 number…

image

It took a while of hunting on the net, but it turns out Googling & Binging, or searching(StackOverflow/Google Groups) for the keyword ‘Lo’ doesn’t work, the argument is ‘capacity’ and searching for that on Google Groups lead me here:

http://groups.google.com/group/ravendb/…..q=capacity

Hopefully someone else finds this useful Smile

Categories: RavenDB Tags: , , , ,