April 2010 - Posts

Short ones
Thu, Apr 29 2010 15:37

While everybody’s still talking (at least in Europe, that is) about how Mourinho managed to put Barça out of the Euro-Champs league final (here’s Il Speciale celebrating this tremendous achievement), I’ve stumbled across a post by Steve Jobs on why IXXX does not support Flash. It’s an interesting read…though I definitely don’t agree with everything he says…

by luisabreu | with no comments
Filed under:
Back to the basics: constants vs read-only fields
Sat, Apr 24 2010 12:23

Constants are (really!) different from read-only fields. Unfortunately, there are still many people which can’t tell the difference between them, so I thought about writing a small post on this topic.

A constant is a symbol (ie, an alias) for value that *never* changes. That’s why you can only define constant primitive types (wtf? Primitive types? Don’t we have only value vs reference types in .NET? Good question…I’ll return to this in a future post :)). When I say primitive type, I’m thinking about Boolean, Int32, Single, etc. Interestingly, there’s a small exception to this rule: the C# compiler does allow us to define a constant for a non-primitive type if we set that value to null (in my opinion, this is not that useful, but the truth is that you can do it!)

Whenever you use a constant, you’ll end up getting the value of the constant in the generated IL code. Suppose you’ve got assembly A with the following constant definition:

public sealed class Constants {
    public const String Message = "Hello!";
}
Whenever you write code like this:
Console.WriteLine(Constants.Message);

You’ll really end up with something like this:

Console.WriteLine("Hello"); //you get the idea :)

Now, embedding the constant value means that the compiler won’t allocate any memory for that constant because its value will be “embedded” in the code. There is, however, one thing which could “hurt” you. Suppose that the constant is defined in one assembly (let’s call it assembly A) and it’s used in another (say, B). Since constants are “copied” to the resulting IL, that means that if you change the value of the constant, you can’t simply recompile assembly A and redeploy it. With constants, you’re forced to recompile both assemblies.

The solution to the previous “problem” is to use read-only fields. A read-only field is declared with the C#’s readonly modifier and it can only be written to from within a constructor (type or instance, depending on the field being static or not). So, if we need to get better “versioning” support for a “constant” value, we should resort to static read-only fields. Here’s some code which re-writes the previous example with fields:

public sealed class Constants {
    public static readonly String Message = "Hello!";
}

And now you should be able to change the value of Message and get away with recompiling only assembly A (in this case, there’s no need to recompile assembly B!). Btw, if you don’t believe me, you can always use .NET Reflector to see the final result (just don’t forget to compare the IL – and not the C# or VB.NET - for both cases).

I’d say that most of us don’t really care about this subtle differences. However, you should consider them whenever you start writing components that get reused for others. And that’s it for now. Stay tuned for more posts on “basic” .NET features.

by luisabreu | 6 comment(s)
Filed under: , ,
My ASP.NET 4.0 book is available (and this time, it will also be sold in Brazil!)
Thu, Apr 22 2010 11:52

A few days ago I’ve mentioned that my ASP.NET 4.0 book was available for pre-order in the FCA site. It has finally been released during Techdays (Portuguese MS event), so you can order it from the web site or buy it in a book store.

As you can deduce from its title, this book covers ASP.NET 4.0  Web Forms in depth. A warning: don’t be fooled by the number of printed pages! When compared with the previous  3.5 editions, you’ll notice that it has less pages. But that only happened because we’ve (I’ve suggested and the editor agreed) decided to move some of the printed content into online appendixes in order to lower the price of the book. If you look at the contents, then you’ll notice that it covers more stuff than its previous editions (the main difference is that a couple of chapters which were printed are now available for download).

There’s also good news for my Brazilian readers: the book will be distributed in Brazil (and that should mean that its price should not be as high as it used to be in the past). So, if you live in Brazil and you’re interested in buying this book (or one of its previous releases), you should contact Zamboni Comércio de Livros and ask for a copy:

Zamboni Comércio de Livros Ltda.
Av.Parada Pinto, 1476
São Paulo – SP
Telf. / Fax: +55 11 2233-2333
E-mail: zambonibooks@terra.com.br

As always, feel free to contact me if you have any questions/suggestions about this book.

by luisabreu | 7 comment(s)
Filed under: ,
Book review: Irrationality
Sat, Apr 17 2010 16:38

Yesterday I’ve finally finished reading Stuart Sutherland’s Irrationality. I’ve found it really entertaining and I do recommend its reading to anyone that wants to better understand what (ir)rationality means. Stuart Sutherland makes his point (we all act irrationally sometimes) by presenting the results of several experiments that have been conducted along several years. Overconfidence and conformity are just 2 of the things that lead to wrong judgments and reasoning's…but besides these two topics, there are several others (each with its own dedicated chapter) which really turn this book into a wonderful reading experience. Overall, I’m giving it 8.5/10.

by luisabreu | with no comments
Filed under:
My ASP.NET 4.0 is already available on the FCA web site
Wed, Apr 14 2010 13:22

It’s still not for sale, but you can be notified when it’s out. Btw, here’s its cover:

aspnet40book

Back to the basics: Culture
Wed, Apr 14 2010 13:19

In a previous post about basic concepts, I’ve talked a little bit about the version number and about the different “types” of version you can find in an assembly. Today, I’ll proceed with the basics concepts series and we’ll take a quick detour into Cultures.

Cultures are identified by a string which can contain two parts, known as primary and secondary parts (I’ve seen them called tags too). Here’s an example: “en-GB”. The previous string identifies the current culture as British English. Notice that the secondary part isn’t really required (in that case, you’d end up with the string “en” and you could only infer that  the culture is English).

When building culture-aware applications, you should always have a culture neutral assembly (which contains code and the application’s default resources) and then create one or more separate assemblies which contains only culture specific resources (these assemblies are known as satellite assemblies). The only thing you need to keep in mind is that you must take some care when deploying your culture assemblies: by default, they must be put it in a subdirectory whose name matches the culture of the assembly (if your app is in a folder named Dumb and you’re deploying a British English assembly,  then you need to put that culture specific assembly in the Dumb\en-GB folder).

Before ending, don’t forget that the culture of the current assembly is also part of its identity! And I guess that’s it for now.

by luisabreu | with no comments
Filed under: , ,
What’s new in .NET 4.0 and VS 2010
Wed, Apr 14 2010 11:30

As always, Scott Guthrie describes the new features in his blog. Even though there’s lots of new cool stuff, one new feature caught my eye:

CLR 4 engine now runs side-by-side in-process with older versions of the CLR – allowing you to use two different versions of .NET within the same process.  It also includes improved COM interop support.

This is fantastic news! Thanks guys.

by luisabreu | with no comments
Filed under: ,
The ItemCount vs TotalItemCount gotcha
Tue, Apr 13 2010 10:12

If you’ve been following this blog, then you know that I’ve been updating an existing project to .NET 4.0 (btw, don’t forget to download VS 2010; it’s already available for MSDN subscribers). This upgrade has been a great way to start using several great new features in a real world project. One extra benefit has been using Silverlight (4.0 RC) for building the UIs of the apps.

Since I’ve finally been able to use Silverlight in a “real world project”, I’ve went ahead and tried several things (including the so called view model pattern – MVVM pattern, if you really must be picky :)). Now, one of the things I needed to do was add paging to a DataGrid control. If you’ve played with it, you’ll know that everything works just fine for auto-paging (ie, when you pass everything and set the page size to something smaller than the total number of items in the collection).

Unfortunately, this is something which isn’t really useful, right? In the real world, I do need to page data but I’m only returning a limited number of items from my server. After reading the docs and following some very good posts from Brad Abrams, I’ve noticed that I could do what I wanted by making my collection implement the IPagedCollectionView interface. As always, I’ve went with a hunch and implement the interface in a “logical” way. Now, the problem was that my pager was always returning page X of 1. WTF? 1? Why? Simple: ItemCount is supposed to return the *total* number of elements *before* pagination. Out of curiosity, I’ve went ahead and read the docs for TotalItemCount (notice that their definitions in the interface page are really similar). And that’s where I’ve found the difference: TotalItemCount is supposed to return –1 when the total number of items is unknown (btw, the DataPager does have a IsTotalItemCountFixed property which you can also set to configure the behavior of the pager when it reaches the last page of data).

Bottom line: whenever you’re implementing the IPagedCollectionView interface for “custom” paging, don’t forget that ItemCount is supposed to have the number of items before paging (and not the number of items maintained in the current collection). Lesson learnt…

by luisabreu | 2 comment(s)
Filed under:
Back to the basics: version numbers
Mon, Apr 12 2010 12:05

It still amazes me how so many people don’t understand (or even care about) the version number of an assembly. A version number is composed of four parts: major number, minor number, build number and revision number. For instance, here’s a valid version number:

4.10.800.1

The first two (major and minor) define what is know as the “public version” of an assembly (notice that this number is used whenever you export an assembly – ex.: COM Interop). The third number defines the build of an assembly. Suppose, for instance, that you work for a company which produces a daily build of an assembly. In this case, this number should be incremented for each day’s main build. Finally, the last part is called the revision number. You’ll change its value whenever you need to perform an “extra build” to solve a pending issue (ex.: a bug which has been found after the daily build).

Now, that we all understand version numbers, I guess I should mention that you’ll encounter several  “types” of version numbers. An assembly is always associated with three version numbers:

  • AssemblyFileVersion: used for information purposes only. It’s the number you see when you access the properties of an assembly in Windows Explorer;
  • AssemblyInformationalVersion: again, this is used for informational purposes. It indicates the version of the product that includes this assembly.
  • AssemblyVersion: this version number is stored on the metadata and it’s used by the CLR when binding to strongly named assemblies.

And I guess this sums it up for assembly versions…

by luisabreu | 4 comment(s)
Filed under: ,
Why RIA Services are great…but just not for me
Fri, Apr 9 2010 12:49

As I’ve said before, I’ve started porting an existing project to .NET 4.0. I’ve tried using the new features .NET 4.0 introduces (ex.: code contracts). One of the objectives I had was replacing the traditional WCF service calls with RIA services. Until now, I’ve watched a couple of presentations (for instance, Nikhil’s presentation on MIX 2010) and it really seemed great.

I must say that I was a little suspicious about it because all the presentations I had seen used EF (and if you know me, you know that I’m still not ready to say goodbye to NHibernate and I do really believe in hiding/abstracting my backend behind an OO domain model). Anyway, I’ve decided to go ahead and tried to reuse my domain model in a RIA Service after reading about presentation models in the RIA Services documentation. What a bad mistake…It did cost me a day and a hald…Unfortunately, RIA Service don’t really integrate well with “real world” objects. For instance, take a look at my DTO (which I was trying to expose to the SL client):

[Serializable]
[DataContract(Namespace = "http://sra.pt/Entidades")]
public class OcorrenciasPaginadas {
    [Key]//don’t like this, but can live with it
    [DataMember()]
    public Int32 TotalElementos { get; set; }
    
    [DataMember()]
    public IEnumerable<ResumoOcorrencia> Ocorrencias { 
get; set; } }

As you can see, I had to add annotate  the TotalElementos with the KeyAttribute (even though TotalElementos is not an ID; anyway, it seems like objects must always be annotated with a key). The worst of all is that the client proxy that is automatically generated in the client side doesn’t include the Ocorrencias property. After talking with Fredrik, he mentioned the IncludeAttribute. So, I’ve started by adding it. Unfortunately, it started complaining that the IncludeAttribute can only be used in association with the AssociationAttribute.

After reading the docs, it was really obvious that RIA Services considers each entity as a lightweight wrapper around a row of a table (that’s the only justification I can think of for making me add an Id property to ResumoOcorrencia that “points back” to the “main” OcorrenciasPaginadas object). In other words, RIA Services does some really cool things, but it’s just not for me because I’m not exposing my backend tables directly to my clients (I’m sorry, but I have a domain model which is responsible for everything and my clients only consume DTOs – which in most situations are really different from the tables that the domain uses to persist data).

I really expected much more from MS, especially because they’ve been presenting RIA Services as something which  can be used with any backend you have (if you don’t believe me, just watch any RIA Services presentation. I bet the guy that is presenting will always say something like “I’m using EF because this is quicker than building my own domain; don’t worry to much with this because you can expose any backend/model you’ve got with this wonderful technology”; this is not true, though I can confirm that if you’re using EF, then RIA Services do really rule).

Bottom line: goodbye RIA Services; Hello again “plain WCF”!

The OnDeserializingAttribute – part II
Wed, Apr 7 2010 9:44

Oh well…remember my last post…the happiness of getting everything working out…Well, unfortunately, things stopped working (read: code contract started generating exceptions) when you define more than one invariant. Here’s my initial code:

public class Dumb
{
    public String A { get; set; }
    public String B { get; set; }
    public Dumb()
    {
        Initialize();
    }
    [OnDeserializing]
    private void DeserializerHelper()
    {
        Initialize();
    }
    private void Initialize()
    {
        A = B = "";
    }
    [ContractInvariantMethod]
    private void Invariants()
    {
        Contract.Invariant( A != null);
        Contract.Invariant( B != null);
    }
}

When you use code contracts and configure it so that it’s also used at runtime, you’ll start getting exceptions when an instance of Dumb is deserialized. The problem here is that setting B to “” will end up checking the object’s invariants and that means that A is still null (and there you go: an exception). The only workaround for this is using backing fields for each property and changing the initialization code so that it uses those new backing fields (instead of going through the properties). I guess you could always dismiss code contracts on objects that are used by WCF services, but that seems worst than using backing fields…

The OnDeserializingAttribute
Tue, Apr 6 2010 12:47

Since I’m porting an existing project to .NET 4.0, I’ve thought about using code contracts in order to improve my code base (and yes, I can say that after some initial frustrations, code contracts is my pal now :)). And yes, it did improve…but since I’m using runtime exceptions, that also meant that I started getting unexpected runtime exceptions.

One of my DTOs had an invariant which specified that a specific object can never be null. To ensure that, I’ve introduced my own default constructor which was responsible for initializing that field into a valid (default) value. And everything run fine until I tried to recover an instance of that object through a WCF service. It was only then that I’ve recalled about an old problem that had bit me in the past: the constructor of a type isn’t called during deserialization!

Fortunately, there’s a solution for this problem: the OnDeserializingAttribute. That means that I’ll have to refactor the initialization code into a helper method so that it gets called during “normal” instantiation and during deserialization. A little more work, but at least I can still keep my invariants valid. Hurray!

Now, if I could only get NHibernate to play nicely with .NET HashSet

by luisabreu | 4 comment(s)
Filed under:
No more ObservableCollection for collections in Silverlight 4.0 RC?
Tue, Apr 6 2010 10:08

While migrating a simple project from Silverlight 3.0 to 4.0 RC, I’ve noticed that the my project no longer compiles. I’ve started getting errors which said that something like “Array does not have an Add method”. After looking at the proxy that was generated by the add reference dialog, I’ve noticed that the ObservableCollection option is no longer available on the Service Reference Dialog (as you can see from the following image):

servicereferencedialog

The good news is that this is a bug in the RC version and it should be fixed in the final release. Thank god for that!

by luisabreu | 1 comment(s)
Filed under:
The new String.IsNullOrWhiteSpace method
Fri, Apr 2 2010 21:56

It was only yesterday that I’ve noticed this new static method. As you probably expected from its name, the IsNullOrWhiteSpace method will only return true for a null string  or for a string which contains only white-space chars (ie, tabs, spaces, etc). Small but handy addition.

by luisabreu | 2 comment(s)
Filed under:
Silverlight: getting started with commands
Thu, Apr 1 2010 19:37

Silverlight 4.0 added the notion of command. In practice, a command is any object which implements the ICommand interface (btw, this is another of those interfaces which have been imported from WPF). Currently, the interface exposes the following members:

  • Execute: this method is responsible for executing the logic  associated with this command;
  • CanExecute: this method should return true if the command is enabled (that is, if the command can be executed);
  • CanExecuteChanged: this event is raised when the value of the CanExecute property changes.

Before going on, I’d like to poin out that, unlike WPF, Silverlight doesn’t really define any default commands (I’m just saying this because if you’re coming form WPF, you might expect to find some of the default commands that exist there; however, that is not the case).

It’s important to understand what commands give you. Before going on, I should say that you could (almost) get away without commands since you can always handle events and add your custom logic to them. However, commands give you superior support for encapsulating logic and reusing them in several places. This is especially true because several Silverlight control’s add logic for interacting with commands.

For instance, all Silverlight buttons (ie, all controls that inherit form ButtonBase) expose a Command (dependency) property which you can set to any object which implements the ICommand interface. As you might expect, the button will try to execute the command in response to any click that is performed over it. Besides that, it will also keep its IsEnabled property in sync with the command’s CanExecute property (this info is updated in response to the CanExecuteChanged event of the command). As you can see, there really is no reason for skipping commands, right?

Notice that you can reuse commands in several places. For instance, Fredrik Normen shows in this post how you can reuse the command concept to support the MVVM pattern. And that’s all for now. Stay tuned for more on Silverlight.

by luisabreu | with no comments
Filed under:

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover