Finally, the move is over!

Finally! After a few days my new blog is alive.

I've been using Mephisto for a long time but I felt it was time to change. Mephisto is writen in Ruby On Rails and while I really like Rails I really needed an Blog engine writen in ASP.NET. There were many excelent options like:

Subtext

dasBlog

BlogEngine.Net

All of the above are great blog engines. They are used by most of the community. So which one did I chose? None!

I decided to create my own blog engine. I know, I know...  Why?? Am I crazy? Do I want to take over the blog market? Nope!!! All I really wanted was a pet project that I could really use while allowing me to keep trying new stuff. A blog engine is something simple enough that I don't need to worry about the business rules. It's been done over and over and we use it everyday. It is also small enough that if I ever decide to throw all my code in the trash and start over with a different approach I easily could.

For this adventure I created a project at Codeplex: SpeakOutBlog. From now on SpeakOut is my sandbox, the place I'm going to try ideas and technologies that interest me. The good thing is that at the same time I'll have do something that works, otherwise my blog will go offline. I don't want to let my fans (my wife, dad and mom) down.

On my next post I'll talk about the difficulties I had with URL Rewriting on my shared hosting. I hope that this project keeps giving me material for the blog.

Oh, before I forget... I really want to thanks the guys that develop Subtext, dasBlog and BlogEngine.Net. Their code is really fun to play with and gave me many ideas to use in SpeakOut. I hope someday someone could look at my code and learn something interesting as I have learned from these guys code.

MVC Storefront: Migrating to the Entity Framework

The title of the post is actually misleading. A better title (although too long) would be: Migrating the Repository concept used in the MVC Storefront to the Entity Framework.

Lately I’ve been playing more with the Entity Framework. The other day I was trying to replicate the way Rob Conery used the Repository Pattern in the MVC Storefront sample application and I was surprised to learn that the Entity Framework has some differences from LINQ to SQL that I did not expect.

My first test was very simple. I wanted to get an IQueryable of Posts with it’s respective Comments attached. The StoreFront did this in a really clever and simple manner. The following code was supposed to work:

class BlogRepository
{
    SOEntities ctx = new SOEntities();

    public IQueryable<Comment> GetComments()
    {
        return from comment in ctx.Comments.Include("Post")
               select new Comment()
               {
                   CommentId = comment.CommentId,
                   Author = comment.Author,
                   Body = comment.Body,
                   PostId = comment.Post.PostId
               };
    }

    public IQueryable<Post> GetPosts()
    {
        var posts = from post in ctx.Posts
                    let comments = GetComments()
                    select new Post()
                           {
                               PostId = post.PostId,
                               Title = post.Title,
                               Body = post.Body,
                               Comments = comments.Where(x => x.PostId == post.PostId)
                           };
        return posts;
    }
}

class Post
{
    public Guid PostId { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }

    public IList<Comment> Comments { get; set; }
}

class Comment
{
    public Guid CommentId { get; set; }

    public Guid PostId { get; set; }

    public string Author { get; set; }

    public string Body { get; set; }

}

class Program 
{
static void Main(string[] args)
{
    BlogRepository rep = new BlogRepository();
    var posts = rep.GetPosts();
    posts = posts.Where(x => x.Title.Contains("MVC"));
    List<Post> postList = posts.ToList();
}
}

I get an error saying that Linq to Entities does not recognize the method GetComments().

It’s not a bug, it’s is just the way the EF works. The method GetComments can’t be translated to anything in the provider. But why does it work with Linq to Sql you ask? Because it converts the Linq expression in a different way. Sorry but the post would be too long if I got into this subject.

The way recommended by the EF team is you use the AsEnumerable() extension method, forcing the initial query to be executed and then you would be working with objects. Here is how I needed to change my code for this to work:

public IQueryable<Post> GetPosts()
{
    var posts = from post in ctx.Posts.AsEnumerable()
                let comments = GetComments()
                select new Post()
                       {
                           PostId = post.PostId,
                           Title = post.Title,
                           Body = post.Body,
                           Comments = comments.Where(x => x.PostId == post.PostId)
                       };
    return posts.AsQueryable();
}

This does work, but when ToList() method is called in the posts object, instead of filtering the posts in the sql code, all the posts are brought from the database and then they are filtered as objects. This is a work around but it’s not ideal.

I have another work around, it also isn’t the ideal but it does work in the sense that it will apply the filter in the database.

public IQueryable<Post> GetPosts()
{
    var comments = GetComments();
    var posts = from post in ctx.Posts
                select new Post()
                       {
                           PostId = post.PostId,
                           Title = post.Title,
                           Body = post.Body,
                           CommentsQry = comments.Where(x => x.PostId == post.PostId)
                       };
    return posts;
}

class Post
{
    public Guid PostId { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }

    public IList<Comment> Comments { get; set; }

    public IQueryable<Comment> CommentsQry
    {
        set { Comments = new LazyList<Comment>(value); }
    }
}

The trick is that I introduced a IQueryable property in the Post class. This property receives an IQueryable and under the hood converts it to a LazyList and sets the Comments property. Doing this overcomes the limitation that the EF has in not letting you use constructors that take parameters in the EF code. It only allows parameterless constructors on the select projection.

If you run this code you will see that the records are filtered in the database. The reason I still don’t consider this solution ideal is that I had to make a change to my model class and created a property that is not related to the business but rather to a limitation imposed by the framework. I still don’t see a way around this. If anyone has any suggestions please do leave them as comments.

A very interesting post was written by Muhammad Mosa a while ago. It’s worth visiting his blog to checkout his idea.

Find and Replace using Regular Expressions within Visual Studio

Regular expressions can be a great addition to the Find and Replace functionality within Visual Studio, specially when you want do do some transformation on the text you are looking up. Lately I’m working on a simple conversion class to transform some HTML into RTF. I got a list of special characters in HTML that I had to convert to the RTF equivalent and for that I needed to create a dictionary. The values where listed in a text document like this:

\'b0 \tab &deg;\par
\'b1 \tab &plusmn;\par
\'b2 \tab &sup2;\par
\'b3 \tab &sup3;\par
\'b4 \tab &acute;\par
\'b5 \tab &micro;\par
\'b6 \tab &para;\par
\'b7 \tab &middot;\par
\'b8 \tab &cedil;\par
\'b9 \tab &sup1;\par
\'ba \tab &ordm;\par
\'bb \tab &raquo;\par
\'bc \tab &frac14;\par
\'bd \tab &frac12;\par
\'be \tab &frac34;\par

And I needed to create a dictionary with the key being the HTML code (third column) and the RTF code (first column) the value. Like this:

Dictionary<string, string> charsMapping = 
    new Dictionary<string, string>();
charsMapping.Add("&euro;", @"\'80");

Here is the expression to find the matches within Visual Studio: __ {\\’:a:a}{.}{&:a;}{\\par}

Each pair of { } is a group to be matched. The difference is that the usual \w (letters or numbers) is :a. In my expression I have four groups the fist is the match for the RTF character and the third is the match for the HTML code. Knowing that the Replace expression is as follows: __charsMapping.Add(”\3”, @”\1”);

Here is how it would look like in VS:

Doing this is much easier then creating the dictionary by hand of even writing a console app to do the replace. Sure I could have used some other text tool to do the same but it wouldn’t be as much fun as figuring out how to do it in VS.

Here is the final output:

Dictionary<string, string> charsMapping = 
    new Dictionary<string, string>();
charsMapping.Add("&deg;", @"\'b0");
charsMapping.Add("&plusmn;", @"\'b1");
charsMapping.Add("&sup2;", @"\'b2");
charsMapping.Add("&sup3;", @"\'b3");
charsMapping.Add("&acute;", @"\'b4");
charsMapping.Add("&micro;", @"\'b5");
charsMapping.Add("&para;", @"\'b6");
charsMapping.Add("&middot;", @"\'b7");
charsMapping.Add("&cedil;", @"\'b8");
charsMapping.Add("&sup1;", @"\'b9");
charsMapping.Add("&ordm;", @"\'ba");
charsMapping.Add("&raquo;", @"\'bb");
charsMapping.Add("&frac14;", @"\'bc");
charsMapping.Add("&frac12;", @"\'bd");
charsMapping.Add("&frac34;", @"\'be");
charsMapping.Add("&iquest;", @"\'bf");

Of course the number of characters was much bigger but it doesn’t matter here. If you need more info on regular expressions you might want to check out the Regular-Expressions.info site, they have a lot of good info on the subject. There are some specifics to using regular expressions on VS so you need to make sure to visit MSDN Reference.