First time here? You are looking at the most recent posts. You may also want to check out older archives or the tag cloud. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS. Thank you for visiting! (hide this)

December 2010 Blog Posts

Merry Christmas and Happy New Year

simo.jpg

This year has been an year of big changes for me (as you can also see from the photo above, which was taken in Bruxelles, where I relocated), but I'll come with the usual review of the year in a week or so.

For the moment I just want to wish all my 3000 readers

Merry Christmas and an Happy New Year

Best of 2010: top 5 most popular posts

top10post2010

This is the time of the year when people start looking back at the year that is about to end, and drawing conclusions.

I will come to my “personal” considerations in a future post, reviewing my 2010 resolutions, but for the moment I want to share with you my top posts of 2010.

The most popular post of 2010

1. Lucene.Net needs your help (or it will die) – Unfortunately it didn’t help Lucene.net get a new set of contributors (at the time of writing they didn’t comply to the conditions set by the ASF board and the project will most likely be shut down and put in the attic), but it raised the awareness of the problem, and was the inspiration for someone to immediately start forking and going on a more .NET path.

2. Is Silverlight becoming a niche technology? – This post stated my position regarding the whole Silverlight vs HTML5 debate. And I’m glad the official position of Microsoft, despite what most fanboys said, was pretty similar to my idea: Silverlight is for building applications for WP7, Silverlight is for cross-platform desktop applications, Silverlight is for niche media-rich web application and HTML5 is for building web applications.

3. Apple relaxing SDK license agreement: MonoTouch (and Flash?) officially allowed – Apparently not many people noticed when Apple announced it, but in the latest update of the iOS SDK license agreement, Apple opened the market to other development languages like MonoTouch and apparently also Flash. So no more excuses not to jump into the iOS world.

4. Tortoise SVN tip: Repair move – Apparently I was not the only one that didn’t know about this super-useful feature of Tortoise SVN, which “repairs” a file rename or a file move.

5. Lucene.net is powering Subtext 2.5 search – Subtext 2.5 introduced a new Lucene.net based search engine, and this post explains how it is implemented.

Unlike 2008 and 2009, when the top 5 posts were mainly about technologies, this year 3 out of 5 are opinion posts.

The 6-10 positions are occupied by my announcement of relocation from Italy to Belgium, another opinion post about the other hot debate of the last two years, WebForms vs ASP.NET MVC, the Subtext 2.5 release announcement and a list of .NET books to read.

The main figures of my 2010 blogging year

In 2010 I wrote 52 blog posts (53 with this one), which is half of what I wrote in 2009 (when I wrote 110 posts), but the traffic increased a little bit, going from 370k to a bit more then 400k page views. I blogged a little bit less frequently, and not as many technical posts as I would have liked. Probably due to the fact that I had some many things to do with the relocation (settling in a new country in Europe, despite what they say about the open borders, and all the e-government, is a long procedure that takes a lot of energy) that I didn’t have time to do write blogs.

What’s coming in 2011?

As you might have noticed, in the last months I went back to my usual blogging pace, and I hope I can keep the same pace in 2011. Lately I started working on FeedTso, a newsreader for WP7, and in 2011 I’ll probably blog also about my experiences and findings in WP7 development.

So stay tuned and subscribe to my RSS feed to get the latest post.

Just one last final thought, unlike the previous years, this time it was very easy to calculate the top 5 posts, thanks to the new dashboard that we released with Subtext 2.5 which included the famous Ayende’s formula for blog post popularity.

How to configure Windows Live Writer to link tags to your blog

Till last week I was linking the tags at the bottom of all my posts to Delicious. But now that Delicious is going to be shut down, I don’t want all my blogs to link to something that is not existent, so I decided to change the configuration of Windows Live Writer to link tags to my tags’ archive on my blog.

All you have to do is adding a new Tag Provider.

First you need to open the window to enter the new provider (down here is a slideshow with the steps)

Click_on_Tags Customize_Providers Add_New_Provider

Once in the “Create New Tag Provider” dialog you have to enter the correct template based on the structure of your blog:

  • Find the url for the tag page in your own blog engine, for example in Subtext it is: http://codeclimber.net.nz/tags/aspnetmvc/default.aspx
  • Then replace the tag with the placeholder {tag-encoded} and then paste this url inside the link in the HTML template field of the “Create Tag Provider” dialog as shown below.

Create_Tag_Provider

In Subtext the HTML template is:

<a href="http://example.com/tags/{tag-encoded}/default.aspx" rel="tag">{tag}</a>

Or if you have Wordpress, the HTML template would be:

<a href="http://example.com/tag/{tag-encoded}/" rel="tag">{tag}</a>

Easy, isn’t it?

Now the difficult part will be to update all the old posts to move the tags from delicious to your own blog: if you have not many posts you could also do it manually, otherwise you would need to write a small app to do the trick. Let’s see it this snowy Christmas holidays will allow me to write a quick tool to do the automatic update.

Actually Yahoo announced that they are not shutting it down before they find someone that is willing to buy it. But still, better to bring links back to your blog rather then sending them to someone else site.

Unboxing Samsung Omnia 7

A few days ago I finally got my Windows Phone 7 device: a Samsung Omnia 7.

Here in Belgium there are just 3 devices at the moment (LG, HTC HD7 and Samsung Omnia) which all cost more or less the same price (530€ for the least expensive and 570€ for the most expensive) so I decided for the Samsung Omnia 7 mainly because of its Super AMOLED display.

Unboxing the phone

Here is the “unboxing” gallery:

     

The packaging is really well done, all cardboard, all recyclable, which is good.

The content

The box has a very strong resemblance to the iPhone box, also the inside cover that hides all the cables and manuals under the actual phone.

Inside the box you find the manuals (here in Belgium, both in French and in Dutch), a quick start guide for WP7 and the cables:

  • in-hear headphones with volume control on the cable
  • USB cable to connect the device to the PC
  • USB cable that ends with a power socket to recharge the device

Here there something I would have done differently: why two USB cables? Why not just like the iPhone does, a power socket where you can plug in the other side of the USB cable? One cable less to loose.

The size

As you can see from the last pictures of my unboxing gallery, the Samsung Omina 7 is a just bit bigger in size then my iPhone 3G, but it has a 4” display instead of 3.5”. And also it is a bit thinner, and seems a little bit lighter.

The display

Probably it already well know, but seeing it in person was really shocking: the Super AMOLED is really super precise and the text, even the small one, is very clear. And the black is so black you can’t see the difference between the black on the display and the black of the frame.

My first days with WP7

At first sight WP7 looks really cool, but I’ll not change my iPhone yet, but for the moment I’ll use it just to test FeedTso, the WP7 feed reader I’m working on together with Daniela. Here are my comments after using the WP7 for a few weeks.

How to replace Delicious, aka Do not trust the cloud and always have an escape plan.

UPDATE: Actually Yahoo is not really going to shut it down, just trying to sell it to another company, but all the warnings about hosting in the cloud are still valid.

I just read that Yahoo is shutting down Delicious. Despite the fact that now I have to find another way to keep all my bookmarks online this raises another interest question:

Do you trust the Cloud?

Everyday there are services that are shut down, like it happened with Geocities and is probably going to happen with Google Wave, but when it happens with popular services the disappointment is even higher.

Everybody is using Twitter, Facebook, Evernote, Dropbox, Google Mail, Google Docs, Google Calendar, Flickr, Vimeo (and probably now a lot more will use Google Bookmarks), some just for fun, but some of these online free services are becoming are so deeply integrated with our life and work that will be difficult to replace them in case some their owner decide to shut them down.

To be cloud-shutdown proof we should make a list of all the “free” services we are using and that we really rely upon, and always have a backup plan to face the event one of them gets shut down or becomes unusable.

This is easier said than done, but if you sit down and plan ahead, this will save you a lot of time and panic when Google decide to shut down GMail (yes, it’s not a mistake, Google will shut down GMail, maybe in 10 year, but it will happen).

Moving away from Delicious

But now, how to solve the immediate problem of replacing Delicious? Here are some links I found that might help:

Probably the easiest way out now is to use Google Bookmarks or I might even try the all European (despite the name) Mister Wong bookmark sharing site.

19 February 2011: UGIALT.net Conference 6th edition

Since 2008 UGIALT.net, the Italian ALT.NET user group, organizes two conferences per year, and will do the same in 2011.

The first one will be next February 19th, in Milano, most likely in the same place were we had the conference last year: in the offices of Avanade Italy, near Milano Central Railway Station.

But unlike the other conferences, where we did a call for proposal and a public voting, this time it will be more like a BarCamp: we will have 2-3 rooms and people that want to discuss about something (obviously related to .NET development or methodologies) can just post their proposal on the site we will make available in January at the time of the registration.

The registration will open on 11/01/11 at 11:11 (we love binary and palindrome days and times) CET.

If you don’t want to wait for January to submit a proposal, you can do it even now, just by sending an email to cfp@ugialt.net.

Slides and code for my SOLID presentation at the .NET Bern User Group

Last Thursday I held a presentation about SOLID principles at the .NET User Group Bern. It was a real pleasure for me to go to Switzerland and speak to a very interested audience.

My talk was actually made of two parts:

  • An introduction to SOLID principles
  • A deep dive into Dependency Injection and IoC containers

In the IoC part I mainly showed samples using my favorite IoC, Ninject. But I also did one sample using Unity and one with Funq, the new super-fast IoC container developed by Daniel Cazzulino.

During the event one of the attendees, Frank Werner-Krippendorf, brought to my attention one of (many) IoC container I didn’t mention: LightCore, a totally Swiss-made IoC container. At first look it seems like it takes the “make your own factory” approach that is also used in Funq (and which avoid the performance problem of doing Reflection to auto discover dependencies). But I’ll have a look more deeply into it (and into Funq) in the next weeks.

Without further ado, here is my presentation.

You can also download the slide in powerpoint format, and all the samples. And online on the DNUG-Bern website you can find the pictures from the event.

If you attended and liked the presentation I’d love if you could take a minute to rate my talk on SpeakerRate.

Now it’s the part of the post where I have to say thank to everybody that attended the event, and especially to Kay Herzam and René Leupold that invited me to speak at the event and that paid for a great Cheese Fondue dinner in downtown Bern. And for supplying me with a good dose of Rivella for the speech.

Also thanks to Patrick Weibel (and the two other guys I don’t remember the name of) for joining us for the dinner, and giving us some tips about where to go XC skiing in Switzerland.

And last, but not least, I wanted to thank Derick Bailey for making available the slides from his awesome SOLID presentation (whose diagrams I used in my slides).

Logging all SQL statements done by Entity Framework

One of the disadvantages of using an ORM is that your application doesn’t know which SQL commands are being executed. In this post I’m going to show you how to log all the SQL statements that are executed by Entity Framework. This is very useful if you want to look at the query executed and the time take by each to catch some possible pitfalls, or to keep a log of all the commands executed if you have your own custom replication/synchronization strategy.

The need

I was exactly in that latter scenario: the backend acts on one DB, while the frontend reads data from another DB. And for many reasons we are not using standard SQL Server replication. Instead we have a custom replication in place: we log all the SQL UPDATE, INSERT, DELETE to a journal table and we have a scheduled script that gets all the statements from the source DB and executes them in the destination DB. Using standard data access technologies this is simple: when we create the SQL statement we also store it in the journal table: but with ORM we are not in control of that process anymore.

The solution

Unfortunately Entity Framework misses the Log property that Linq2Sql had so I needed to go a bit more inside the core. I knew that EF had some kind of interceptor because otherwise the EFProfiler would have not been possible, so a bit of googling brought me to the Tracing and Caching Provider Wrappers for Entity Framework, developed by Jaroslaw Kowalski. These providers, together with a small sample file you have to copy your application, gives you the possibility to get the Log property back, to inject a Cache or to do more advanced operations using the CommandExecuting, CommandFinished, CommandFailed events. You can read more about the API in the blog post where they announce it.

For my specific scenario I had to write an handler for the CommandFinished event that gets the DbCommand object and transforms it to the SQL statement.

How to do it

Let’s see how this is done.

1 - Get the providers

First thing you have to download the provider wrappers with the sample apps from the MSDN Gallery site. The latest version (v1.02) is for EF v4, but if you are like me and are still using EF v1 you have to get version 1.

The file you get is just a Visual Studio Solution, so you have to open it, change the configuration to Release and build it. You then open the EFProviderWrapperDemo project, go the Bin\Release folder and get the 3 DLLs: FCachingProvider.dll, EFTracingProvider.dll and EFProviderWrapperToolkit.dll.

2 – Setting up your application

You take the 3 DLLs mentioned above and you add them as references to you application: the EFProviderWrapperToolkit is always needed, and then the one that you need for your application: in my scenario I didn’t need caching, so I just added the EFTracingProvider one.

Then the tricky part comes: from the EFProviderWrapperDemo project you have to take the ExtendedNorthwindEntities.cs file, copy in the folder where you have your Entity Framework edmx file, and modify it to match your scenario (change the name of the class and the connection string). For example, my EDMX file was called PhotoLibEntities, so I renamed the file (and class) to ExtendedPhotoLibEntities, and modified the code as follows:

public partial class ExtendedPhotoLibEntities : PhotoLibEntities
{
    private TextWriter logOutput;

    public ExtendedPhotoLibEntities()
        : this("name=PhotoLibEntities")
    {
    }

    public ExtendedPhotoLibEntities(string connectionString)
        : base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
                connectionString,
                "EFTracingProvider"
        ))
    {
    }
...
}

Notice that if you need just one provider, you can remove the registration of the one you don’t need (as I did).

You also need to register the provider in you application putting some entries in the app.config (or web.config) file:

<system.data>
  <DbProviderFactories>
    <add name="EF Tracing Data Provider"
         invariant="EFTracingProvider"
         description="Tracing Provider Wrapper"
         type="EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
    <add name="EF Generic Provider Wrapper"
         invariant="EFProviderWrapper"
         description="Generic Provider Wrapper"
         type="EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
  </DbProviderFactories>
</system.data>

Here I added only the tracing provider, but if you needed the caching provider, you have to add it in the configuration file as well.

If you don’t want, or cannot change your code, you can also inject the provider by manually modifying the SSDL files. You can read more about this in the original blog post by Jaroslaw Kowalski.

3 – Using the Extended ObjectContext

Now that everything is correctly setup you can use the extended ObjectContext to have access to the logging and caching features provided by the wrapper.

using (ExtendedPhotoLibModel context = CreateExtendedPhotoLibModel())
{
    //Do stuff
    context.SaveChanges();
}

I use an helper method instead of instantiating the extended context directly because this way I can setup the event handler I need to store the statements to the journal table.

private ExtendedPhotoLibModel CreateExtendedPhotoLibModel()
{
    ExtendedPhotoLibModel context = new ExtendedPhotoLibModel();

    photoLibModel.CommandFinished += (sender, e) =>
    {
        if (e.Method.Equals("ExecuteNonQuery"))
        {
            string sqlStr = e.Command.CommandText;
            foreach (DbParameter parameter in e.Command.Parameters)
            {
                sqlStr = sqlStr.Replace(parameter.ParameterName,
                            ToDbFormattedString(parameter.Value));
            }
            sqlStr = sqlStr.Replace("\r\n", " ");
            PhotoJournalLogger.AddEntry(sqlStr);
        }
    };
    return context;
}

private static string ToDbFormattedString(object p)
{
    if (p is DateTime)
        return "CONVERT(datetime,'" + ((DateTime) p).ToShortDateStr() + "',103)";
    if (p is String)
        return "'" + (p as string).Replace("'", "''") + "'";
    return p.ToString();
}

My event handler gets the command text, cycles through the parameters and modifies the command text replacing the parameter’s names with their values.

Here is an example of how the CommandText looks like:

update [dbo].[NEWS_PHOTOGALLERY]
set [bookID] = @0,
    [date] = @1,
    [numPhoto] = @2,
    [picture] = null,
    [status] = @3,
    [titleID] = null
where ([id] = @4)

If you just need to log the statements you could also call the e.ToTraceString() method and you would have got the following text (with also all the values for the parameters):

update [dbo].[NEWS_PHOTOGALLERY]
    [date] = @1,
    [numPhoto] = @2,
    [picture] = null,
    [status] = @3,
    [titleID] = null
where ([id] = @4)

-- @0 (dbtype=Int32, size=0, direction=Input) = 34
-- @1 (dbtype=DateTime, size=0, direction=Input) = 08/12/2010 12.21.38
-- @2 (dbtype=Int32, size=0, direction=Input) = 0
-- @3 (dbtype=AnsiStringFixedLength, size=1, direction=Input) = "0"
-- @4 (dbtype=Int32, size=0, direction=Input) = 234

Further usages

This is just the basic usage, but if you want you can extend the logging to also include the duration of the command (very useful for performance tuning) or even the whole command tree.

I struggled a bit to find the solution, and I hope this helps.