Jan 27

Blog moved…

Posted in Uncategorized           Comments Off on Blog moved…

This time, to the official wordpress site. You can follow it here or (if you’re following it by RSS feed, no need to change it if you’re using my feedburner feed).

Jan 16

My Windows 8 books is out

Posted in Books           Comments Off on My Windows 8 books is out


First post of the year. I hope it’s not too late to wish everyone a Happy New Year Smile

After some technical problems (unforeseen at the time), I’m pleased to announce that my latest book is out. This time, I’ve moved away from the web and I’ve went into the “wild” and decided to write a couple of pages about how you can leverage your web skills into build Windows Store Apps. It was a fun ride. I just hope that you, the reader, enjoy it as much as I did.

Dec 19

Book review: Programming C# 5.0

Posted in Books           Comments Off on Book review: Programming C# 5.0

[Disclaimer: I’ve received a free copy of this book from O’Reilly]

I’ve finally managed to finish reading Ian Griffiths’ last book (yep, it’s a big book!) and I can tell you that it’s a great piece of work. In a similar vein with Jeffrey’s CLR via C# (I’ll be writing a review about this in the next couple of days), but with a different approach to the topics, Ian uses the C# 5.0 language to explore the CLR. It covers a lot of ground and that means it won’t be as deep as deserved in some areas (ex.: I think that Reactive Extensions deserved a little more love than it got). Oh, and yes, even though there’s a chapter on XAML and another on ASP.NET, don’t expect to see a lot of stuff covered about those platforms. Yes, they do cover some ground and they might be enough if you’ve got some experienced and just need the basics to get started. However, they’re far from enough if you’re looking for specific in depth coverage in each of those areas.

The text is clear and the prose is pleasant (at least, for about 95% of time) and I think this book would be a good addition to the bookshelf of any C# developer. Overall, I’d give it an 8/10.

Nov 15

Quick tip: measuring the performance of your JS code? Don’t hit F5 from VS!

Posted in Javascript           Comments Off on Quick tip: measuring the performance of your JS code? Don’t hit F5 from VS!

Today’s post presents a quick tip: if you’re interesting in measuring the performance of your web app (also applicable to Windows Store apps written in JS), then don’t start it by hitting F5 in VS. IF you start your app in debug mode, your JS code won’t be JITed and the results will be different from the ones you get when you load your app directly in the browser.

Nov 13

Overflow and checked contexts

Posted in C#           Comments Off on Overflow and checked contexts

I’ve ended the previous post on numeric conversions talking about overflow and how it might surprise you from time to time. For instance, here’s an example that might get you off guard:

uint a = uint.MaxValue;
int b = (int)a;
Console.WriteLine("{0} – {1}", a,b);//-1

Running the previous snippet ends up printing the following:

4294967295 – -1

Now, even though this might be ok in several scenarios, there might some times when you want to get an exception if the value is “too big” for the variable. In these cases, you can resort to the checked keyword, which can be applied to a statement or expression, making it run in a checked context:

uint a = uint.MaxValue;
int b = checked((int)a); // throws OverflowException

In the previous snippet, the cast from the uint value into a int is perfomed in a checked context. Since the uint number is way “too big” to be stored in an int, we’ll end up getting a OverflowException. Besides casts, you can also use the checked keyword when performing arithmetic operations. Notice also that the checked keyword can be used to run an entire block of code in the checked context:

checked {
    uint a = uint.MaxValue;
    int b = (int) a; // throws OverflowException

In fact, and if that is your desire, you can also configure the C# compiler so that everything is run into a checked context by default. You can do this by passing the /checked flag from the command line or by going to the VS build tab on the project’s options windows and setting the  “Check for arithmetic overflow/underflow checkbox” on the dialog that is shown when you hit the advanced button.

In practice, you probably shouldn’t use checked contexts in all your arithmetic operations because checking contexts can make them really slow. If this is negligible or not, it will depend on the operations performed by your program. However, you should keep in mind that it might have some negative impacts in the performance of your app. Bottom line, if you decide to go crazy and run everything in the checked context, don’t forget to measure the impacts in the performance of the app.

And that’s it for now. Stay tuned for more.

Nov 12

Fixing the blog: my winning combination

Posted in Trivia           Comments Off on Fixing the blog: my winning combination

If you’re a regular reader of this blog, you’ve probably noticed the problems I’ve been getting recently when I insert code snippets in my posts:


When I write technical posts, I use Windows Live Writer because it’s free and it has lots of plugins. To be honest, it simply rocks! Now, I’ve used several formatting plugins in these last couple of years without any problems until now. However, I must confess that I haven’t really played a lot of attention to the plugins I’ve used in the past and since I tend to format my machine often, that means I typically won’t end using the same plugin again.

After looking more carefully at the HTML shown in the blog, it’s easy to see what’s going on: it seems like something is happening between the time I hit the publish button and the time the post gets published in my site. By all means, we’re not talking about magic here Smile What’s happening is that WordPress is stripping my style tags from within the post’s body. Even though embedding the stylesheet is normally an option for many of the available formatting plugins, the truth is that Code snippet and Insert Code plugins I installed kept generating style tags for setting the styles of the code snippets (which, as you can see from the previous picture, ended up being discarded by WordPress). Since I can’t access the source code of my blog (it’s kindly being hosted by, I couldn’t try one of the available fixes. That left me with one option (in order to keep using WordPress for my blog, that is): I had to keep looking for a plugin for code insertions that played well with WordPress.

And sure enough, after some time I’ve managed to find my old and faithful Paste as Visual Studio Plugin which inserts the styles in the tags instead of inserting style tags. And that, my friends, makes me a happy person. And it also makes my readers happy because they can finally read the code I’ve written. Overall, it’s a win-win situation. Having solved this problem, I’ve also played a little bit with VS color schemes so that the code snippets play well with the blog theme. This wasn’t easy because 1.) I’m not a designer and 2.) I really like the black layout IDE (though I must confess that it doesn’t really helps when reading technical blogs). Anyways, I’ve ended up downloading the Clean Metro style and I really think the end result was not bad. what are you thoughts on this? Do you think the blog is readable now? Can I go  back and focus on content again?

Nov 12

C#: more details on numeric conversions

Posted in C# Uncategorized           Comments Off on C#: more details on numeric conversions

Conversions…such a boring topic and I’m positive that you already know everything there is to know about numeric conversions in C#. That’s all good, but I think there might be some small details that might bite you if you’re not careful. Ok, let’s start with the basics, shall we?

Everyone knows that whenever you need to perform an arithmetic calculation that involves mixing numeric types, C# will pick the one that has the largest range and it will promote all the other types with a narrower range to that type before performing the calculation. Here’s an example:

int b = 10.5; int a = 10; Console.WriteLine(a / 2); //5, int
Console.WriteLine(a / 4.0); //5.0, double

As you can  see, C# will convert a into a double before performing the division because 4.0 is a double and doubles have a “wider range” than an integer. In other words, a double can represent any value that int can. In other words, this conversion is performed implicitly because it’s considered a promotion (since the target type has a wider range than the original type, then there’s no loss in the conversion from int to double). The same does not happen when you try to perform a conversion in the opposite direction (aka as narrowing conversion):

int b = 10.5;

It’s still possible to get a narrowing conversion, but you need to be explicit about it and use a cast:

int b = (int)10.5;

Whenever you use a cast, you’re saying something like “hey, I really want to perform this cast and I can live with the eventual loss of data”. And now the compiler is able to convert it because you said “hey, it’s ok. Just go ahead and convert it”.  Now, what happens when you combine types that aren’t more expressive than the other? For instance, what happens when you mix int, uint and floats in an expression?

Unlike the double example, all of these types are 32 bits in size, so none of them can hold more than 2^32 distinct values, right? They do, however, have different ranges. For instance, 30000000001 in a uint is simply too large to be put in a int (and it can only be approximated in a float). What about –1? Yes, you can put it in an int, but since it’s a negative number, you can’t really put it in a uint. So that the “float lover” isn’t upset, it’s also true that there are very large numbers that float can represent which are out of range for int and uint.

C# will allow some implicit conversions in these scenarios where there is the potential to loose precision. Since C# cares about range (and not precision), it will allow implicit conversions whenever the target type has a wider range than the source type. In practice, this means that you can convert implicitly from int and uint to float. Although float is unable to represent some values exactly, there are no int or uint values it cannot represent (at least, approximately). Unfortunately, this also means that there’s no implicit conversion from float to int or uint. Here’s an example that tries to illustrate the point of lost precision:

uint a = 3000000001;
float b = a;
uint c = (uint)b;
Console.WriteLine("{0} – {1}", a, c);

Running the previous snippet ends up printing the following:

3000000001 – 3000000000
Press any key to continue . . .

As you can see, I’ve forced the conversion from the float to an uint and we ended up getting a different number. Before ending, it’s also interesting to understand what happens when we try to perform a narrowing conversion to an int when we have an out of range number. Well, it all depends on the type of the value being casted. When we’re talking about integer casts, the spec does a good job of specifying what should happen. If the types are of different sizes, then the binary will be truncated or padded with zeros so that it ends up with the right size for the target type. Here’s an example of what I mean:

uint a = 3000000001;
int b = (int)a;

Sometimes, this is useful, but it can also end up giving some surprising results. And this leads us into checked and unchecked operations. However, since this is a really big post, we’ll leave it for a future post.

Nov 05

Images are probably the most used media type in a page. Here are some simple suggestions for improving the performance of a page that uses images:

  • include images in its native size. Do not resize the image by using the width and height attributes of the img tag (or its equivalent CSS properties). If needed, the image should always be resized in a graphical editor before being used in the site. This will at least save your client’s browser some CPU time which might be better used in other important operations;
  • try to avoid making several image requests in a page. When possible, you should use image sprites because they will typically minimize the bandwidth for getting the images and you’ll only need one request to get all the images. Btw, it’s also a good idea to check the results of the sprites before publishing them (the current tools do a good job when the images share the same dimensions, but they tend to do a less than stellar job when you’re joining images of different sizes);
  • when available, go with the png format. A possible exception to this rule is showing images which are categorized as photos (in that case, jpeg might be a better option);
  • use the data URI protocol for small images. Notice that small is the key feature here. Getting the base 64 encoding string that represents the image can be done through one of the free tools available on the web (here’s one);
  • when possible, use svg instead of bitmap images. At the same time, try to avoid complex svg paths because they do take some time to process;

And that’s it for now. Stay tuned for more.

Oct 31

The Windows Phone 8 experience: ended before starting

Posted in WP8           Comments Off on The Windows Phone 8 experience: ended before starting

Ok, so here’s the deal: I’ve just finished up installing the windows phone 8 SDK. Now, the deal killer: in order to run it, the BIOS needs to support hardware assisted virtualization, second level address translation (SLAT, aka EPT in Intel processors) and hardware based data execution prevention. And of course, you must be running Windows 8.

Now, let me see…Windows 8 installed: checked. how about support for the hyper-V? Nothing like running the coreinfo utility:

PS E:\box\tools\Coreinfo> .\Coreinfo.exe -v

Coreinfo v3.1 – Dump information on system CPU and memory topology
Copyright (C) 2008-2012 Mark Russinovich
Sysinternals –

Intel(R) Core(TM)2 CPU          6400  @ 2.13GHz
Intel64 Family 6 Model 15 Stepping 6, GenuineIntel
HYPERVISOR      -       Hypervisor is present
VMX             *       Supports Intel hardware-assisted virtualization
EPT             -       Supports Intel extended page tables (SLAT)
PS E:\box\tools\Coreinfo>

hum…oops…no EPT? Oh no! But what does this mean? Let me see: in order to test WP8 SDK, I’ll have to 1.) update my CPU or 2.) buy a windows phone 8. I’ll go with option 3: whenever I’m in the mood to check the mobile dev space, I’ll get the android SDK and I’ll make the extra effort of writing Java code again. And guess what: this extra effort of writing Java does not cost a thing (except, of course, some mental pain associated with the process of writing Java code :)).

And this really sums up my dev experience with WP8: it’s definitely a fail.

Oct 28

Undefined? Didn’t you mean undefined?

Posted in Javascript           Comments Off on Undefined? Didn’t you mean undefined?

After publishing my latest post, I’ve received a couple of emails from fellow readers asking me if I didn’t mess up things when I’ve mentioned Undefined. Shouldn’t it be undefined? And the answer is no, I didn’t make an error because I was talking about types (and not about values). This kind of detail is important if you intend to become a proficient JavaScript developer (which means reading the spec). So, if you read the spec, you’ll see that it talks about the Undefined type and about the undefined value.

Undefined is a type whose sole value is undefined (notice the lower case u). The undefined (lower case u again!) value is a primitive value (recall that Undefined is one of the primitive types) that is used when a variable hasn’t been assigned a value. Here’s an example:

var aux;
//aux === undefined is true

To sum up, whenever you declare a variable and don’t initialize it, it will end up with an undefined value. Notice that the existence of undefined value lets you distinguish between declared variables that have been initialized or not. Take a look at the following example:

var aux;
//aux ===  undefined is true
var aux2 = null;
//aux2 === undefined is false

As you can see, you can initialize a variable to null. When this happens, the value no longer returns undefined, but null. null is also a primitive value and it was introduced in the language to represent the intentional absence of any value (notice that a variable initialized or set to null has been initialized and that means it’s not undefined). Since we’re talking about null, I’m going to take this opportunity to mention that null is the only value of the primitive Null type (yes, we have those nasty case differences between type and value again Smile).

And I guess that it’s all for now. Stay tuned for more!

Oct 21

Contas de mercearia: 101 do cálculo do IRS para 2013 e a fábula do subsído do 13º mês da função pública…

Posted in Uncategorized           Comments Off on Contas de mercearia: 101 do cálculo do IRS para 2013 e a fábula do subsído do 13º mês da função pública…

[This is an opinion article about taxes in Portugal for 2013 and that’s why it’s entirely written in Portuguese. If you’re not living in Portugal, then it’s safe to carry on reading other stuff]

Durante este fim de semana, tive a oportunidade de me aperceber que ainda há pessoas que acreditam no pai natal (ou então, e se assim o preferirem, que ainda acreditam no coelho da páscoa). Só assim se percebe como ainda existem pessoas que pensam que 1.) vão *apenas* receber um pouco menos de rendimento líquido no próximo ano e que 2.) os funcionários públicos não serão tão prejudicados como os restantes trabalhadores, já que terão o “benefício” de receberem o 13º mês em 2013.

Neste post, o meu objetivo não é dissertar acerca do trabalho desses funcionários ou sobre a necessidade da sua existência (se alguém estiver interessado em começar essa discussão, é só dizer), mas sim mostrar como o aumento de impostos no próximo ano é brutal e vai atingir todas as famílias cujos rendimentos provêm do trabalho por conta de outrem.

Para não complicar as contas, vamos supor que estamos perante um casal sem filhos, em que ambos trabalham para a função pública e auferem mensalmente 1500 euros cada (este valor permite-nos ignorar a redução proveniente da sobretaxa variável entre 3.5% e 10% aplicada a todos os trabalhadores do público que auferem mais do que 1500 euros mensais). Na prática, isto quer dizer que estamos perante um rendimento bruto mensal de 3000 euros. Antes de avançarmos, devo alertar para o facto de não ser um expert na matéria e dos cálculos apresentados serem feitos com base no que eu li e vi em vários artigos. Vejamos, então os cálculos de pagamento de IRS para 2012 deste casal:

Rendimento bruto anual (12 meses x 3000)


Coeficiente conjugal (/2)


Taxa média 12,348% x 7410


Taxa normal 24,5% x (18000-7410)


Caixa geral de aposentações (11%)


ADSE (1,5%)


Total rendimento líquido

2 x ( 18000-915-2595-1980-270) = 24480

Antes de avançar, é importante notar que os cálculos apresentados são anuais (com base nesta tabela). Não me venham falar de tabelas mensais porque essas são sempre aproximadas e tentam “advinhar” o que o contribuinte deve pagar mensalmente. Ao usarmos as tabelas anuais, temos a certeza de termos os valores finais “corretos”. Neste exemplo, também não entrei em linha de conta com eventuais deduções à coleta relativas a despesas de saúde, etc.

A forma de cálculo é relativamente simples: procuramos o intervalo onde se inclui o valor bruto e obtemos o limite superior do escalão imediatamente anterior. Esse valor (limite superior da linha anterior) é multiplicado pela taxa média dessa linha anterior. Em seguida, efetuamos a diferença entre o valor bruto anual e esse limite superior do intervalo usado no primeiro cálculo. Esse novo valor é multiplicado pela taxa normal do escalão onde o rendimento bruto foi incluído.

Portanto, do valor bruto de 36000, o casal de funcionários públicos termina o ano de 2012 com 68% desse rendimento (isto, claro, depois de efetuar todos os descontos obrigatórios por lei e que incluem IRS, CGA e ADSE). Este cenário, na minha opinião, já é mau.

Agora, vejamos o que reserva o ano de 2013 para este casal:

Rendimento bruto anual (13 x 3000)


Coeficiente conjugal (/2)


Taxa média 14,5% x 7000


Taxa normal 28,5% x (19500-7000)


Taxa extra 4%


Caixa geral de aposentações (11%)


ADSE (1,5%)


Total rendimento líquido

2 x ( 19500-1015-3563-760-2145-293) = 23448

Ora, os resultados estão a vista de toda a gente: apesar de o valor bruto do casal ter passado de 36000 para 39000, a realidade é que o rendimento líquido passou a ser apenas de ~60% (em vez dos 68% de um valor bruto inferior para 2012!). Para além disso, esta é a primeira vez que me lembro de ver um aumento do rendimento bruto ser traduzido numa efetiva redução do valor líquido a receber no final do ano. Para isso, contribuem várias coisas. Note-se como os limites inferiores dos escalões (em 2013, temos um escalão mais baixo com limite superior de 7000 enquanto que o valor 7410 usado na primeira tabela de 2012 identifica o limite superior do segundo escalão da tabela!) e respetivas percentagens aumentam em 2013 (logo no primeiro escalão de 2013, temos uma taxa de 14,5%!).

Na prática, o casal vai chegar ao final do ano com menos 1032 euros, apesar de supostamente receber mais um mês de salário. Como se isto não fosse mau, vamos ter aumentos dos preços de todos os produtos (ex.: eletricidade vai aumentar 2.8%!).

Então, enganei-me nas contas? Espero bem que sim. É que se o cenário não é bonito para este rendimento (que eu considero baixo!), as coisas tendem a piorar para rendimentos mais altos (claro que os desgraçados que ganham menos vão ter dificuldade em se alimentarem, mas que não fiquem dúvidas: quanto maior o rendimento, mais será descontado em valor absoluto).

Para terminar, duas notas:

  1. pagamento do 13 mês na função pública? A sério? Não me digam…é que pelas contas anteriores nem um cêntimo desse valor chega aos bolsos (ao contrário do q o sr. Primeiro ministro tentou passar na sua comunicação). Aliás, até sou capaz de dizer q tiram cerca de meio mês de salário se compararmos com o ano de 2012…
  2. srs. polítcos, será possível pedir-vos que deixem de me chamar de burro? Justificar este brutal aumento de impostos da função pública com o pagamento do 13º mês? E ainda por cima dizer que só nos salários mais altos é que não vão receber esse 13º mês?

Comentário final: para quando é que temos medidas concretas que melhorem o país? Para melhorar a justiça, não precisamos assim de tanto dinheiro, pois não?

Oct 21

So, what is an object in JavaScript?–part I

Posted in Javascript           Comments Off on So, what is an object in JavaScript?–part I

After publishing my previous post, I’ve received some questions from friends which make me believe that I probably need to elaborate further on my “what is an object in JavaScript thesis”. So be it. If you’ve read the previous post, you probably remember me writing this:

“In JavaScript, you can think of objects as being containers for key/value pairs.”

Well, it’s not completely wrong, but the truth is that there’s a little more to an object than that and ECMAScript5 has made those little things more visible than ever. So, here’s a better definition of what an object is in JavaScript (taken from the ECMAScript 6 draft):

“An ECMAScript object is a collection of properties each with zero or more attributes that determine how each property can be used—for example, when the Writable attribute for a property is set to false, any attempt by executed ECMAScript code to change the value of the property fails.”

Did you notice the attribute part that is applied to each property? Yes, that’s the part I’ve omitted from my initial definition and that is an important part of how you can create objects from ECMAScript5 onwards. In practice, ECMAScript5 introduces several methods which allow us to influence the way a property is created and we’ll come back to them in a future post.

Notice that properties of an object will always hold other objects which will also have its own properties, primitive values or functions. Currently, ECMAScript defines primitive type as a value of one of the following types: Undefined, Null, Boolean, Number and String. If a value doesn’t belong to one of the previous types, then it is an Object. “What about functions?”, you ask. Well, functions are special types of objects which can be “called” (ie, you can use them with the () operator in order to get a result back). Besides Object and primitive values, the spec introduces several predefined types (aka ECMAScript entities or objects) that we can use in a program (ex: Date, RegExp, etc.) and some predefined operators.

And I’d say that this is a better (though still formal) definition of an object. In the next post, we’ll dig a little deeper and see how the spec “lays” objects in memory.

Oct 18

By now, I think there’s no doubt about how important JavaScript is. And that’s why I thought it would probably be a good idea to write a little bit more about it. By doing it, I’ll refresh my memory and I’m also hoping to learn one or two new things that I might have missed before. To get things started, I’ve decided it would probably be a good idea to talk about object construction in JavaScript.

In JavaScript, it’s common to create an object by writing code like this:

//option 1: literal
var obj1 = {};
//option 2: construtor -> bad
var obj2 = new Object();
//option 3: so ECMAScript 5
var obj3 = Object.create(Object.prototype);

In practice, you’ll probably see option 1 used often. Option 2 is really a bad practice and you shouldn’t use it (I’m not sure if I can remember seeing option 2 used in the real world…). Option 3 is only available if your runtime is compatible with ECMAScript5 (I’ll return to it in a future post). Notice that all of these options produce the same result: an empty object.

In JavaScript, you can think of objects as being containers for key/value pairs. After creating an instance, you can use the . notation for adding a new property or changing the value of an existing property. Alternatively, you can resort to the [] notation for accessing a property. Here’s an example: = 'Luis';
obj2['name'] = 'Luis';

Once again, the previous instructions end up generating similar results. In both cases, you’ll end up with an object that has a name property and whose value is set to Luis. If you’re creating a new object with the literal syntax, then you can do it all at once:

var obj1 = { name: 'Luis' };

By now, you’ve probably noticed why the literal syntax is used so often. There’s still an alternative way of creating properties which is more powerful, but only compatible with ECMAScript5 (we’ll leave it for a future post). Going back to object creation, there’s still a final approach: we can create a function and use it as a “constructor”. A function is “transformed” into a “constructor” when it’s prefixed with the new keyword during its invocation. Here’s a quick example of how you can build a simple object by using a constructor:

function Person(name) { = name;
var p = new Person("Luis");

In this case, you’ll also end up with an object which has a single property name, whose value is also set to Luis. Even thought the results  are similar, there are some important differences between the objects created. For instance, if you check the constructor property, you’ll notice that p returns a reference to Person while obj1 returns a reference to Object. As we’ll see, this difference might be important, but for now, we don’t have to worry about it because we’re simply interested in creating objects.

If you’re coming from a strongly typed language like C# or Java, you might be thinking that our last approach (where we created a function that is used as a constructor) is the way to go when you need to create objects in JavaScript. Well, it might be a viable option, but as you’ll see, it typically isn’t the way to go when you’re working in JavaScript.

And that’s it for now. Stay tuned for more.

PS: does anyone have any suggestion on how to format the code  before pasting it in Windows Live Writer? I’m using code snippet for  now, but I’d prefer to have a dark scheme for my code…

Oct 09

While I was catching up on my blog roll, I’ve noticed that my friend Alberto ended up being surprised by another nitpick difference between C# and VB.NET which does not help the programmer which needs to be proficient in both languages. Here’s the culprit code (in VB.NET and then in C#):

Dim x as Integer = 5 / 20 * 100

int x = 5 / 20 * 100;

At first, they do look the same, don’t they? But nop, they’re not the same. Unfortunately, VB.NET has 2 operators for division: / and \. In practice, / will run the division and return a float (don’t ask me why!), while \ returns the integer result (discarding the remainder).

Now, I really don’t want to start bad mouthing VB.NET, but in this case, we’re dividing two integers, so I’d expect to get an integer. Now, this probably won’t make sense to the long time VB.NET programmer, but the truth is that C# will only allow you to perform three “division types”: integer, floating point and decimal.

I really don’t agree with my friend Alberto, which classifies C#’s behavior as wrong. In fact, I think it’s correct and it does help to achieve type safety. but hey, that’s me, a C# lover (and also a VB.NET critic Smile)

Oct 03

IIS 8: application initialization with static content

Posted in IIS           Comments Off on IIS 8: application initialization with static content

IIS 8 introduces a new feature known as application initialization which allows you to present static content (ex.: an HTML page) while the application is completing its initialization tasks. In other words, with IIS 8, you can set an HTML page which is returned to the user while the application is “warming up”.

To use this feature in IIS 8, we need to make sure that the Application Initialization option is installed.


After insuring that, we need to configure the site’s application pool so that it gets started before IIS receives the first request for that site. In order to do that, we can fire up the application pool’s advanced property dialog and change its start mode property so that the AlwaysRunning option is set.


Now, we need to update the site’s preload behavior by changing the value of its Preload enabled property to true:


Now that the warming up is set up, we can still take this a little further and specify some static content which will be shown to the unlucky user that hits the site before it ends up its initialization tasks. To do that, we need to add the applitationInitialization element to the system.web section:

<applicationInitialization remapManagedRequestsTo="warmingup.html" skipManagedModules="true">
<add initializationPage="/default.aspx" />

With the previous entry, we’re saying that while the application is being initialized, IIS should return the contents of the warmingup.html file back to any client that tries to access the site. If the user sees this static page, he’ll be redirected to the default.aspx page when the warm up ends.  Notice that we can only serve static content during this phase (you can’t return an ASP.NET page because the app is still being initialized!).

And that’s it for now. Stay tuned for more.

Oct 01

I’ve just noticed that MS has presented me again with an ASP.NET MVP award. I really wasn’t expecting this…thanks MS!

Oct 01

Book review: Regular Expressions Cookbook

Posted in Books           Comments Off on Book review: Regular Expressions Cookbook

[Disclaimer: I’ve received a review copy of this book from O’Reilly]

I’ve been searching for a good regular expression book for some time and I think I’ve finally found one which fits my requirements. Regular Expressions Cookbook is really a great book and you can use it as a reference for quickly picking up one or two regular expressions or as learning guide that can help you understand all the details associated with the way regular expressions work.

The book starts by introducing the topic of regular expressions and explains its “basic blocks” and how you can use them to build the most basic expressions you can think of. From there, it takes a detailed look at some common problems which you’ll be facing in the “real world”.

Being a cookbook, it’s not a surprise to see that the topics are presented in the typical problem/solution fashion. What I must point out though, is that you’ll be finding clear and long explanations about why things work the way they do and you won’t be limited to only one or two variations of regular expressions since the book presents the variations associated with several languages (.NET, Java, JavaScript, Perl, PHP, etc.). Note that rather long is not the same as boring and if you’re only interested in getting info about a specific language, you can always skim the parts which are of no interest to you. Interestingly, and even though I was only interested in getting info about using regular expresions in .NET and JavaScript, I’ve found myself reading the complete explanation section several times (which you can probably think of as a way of measuring the quality of writing that the authors have put into their work!)

Overall, I’m giving this a 9/10 and I really recommend it to those guys which are looking to learn more about regular expressions or that need to buy a good reference book on the topic.

Sep 27

RhinoMocks: the Int32 vs Int64 conundrum

Posted in .NET C# RhinoMocks           Comments Off on RhinoMocks: the Int32 vs Int64 conundrum
In these last couple of days I’ve been busy trying to refactor some apps which are starting to show their age. It hasn’t been fun because unfortunately I didn’t have a high enough code coverage to perform the refactoring safely (oh well, life sucks sometime!). Even though it’s not the most pleasant thing to do in the world (hell, I can remember quite a lot of way more interesting things to do Smile), doing this kind of work has been…how shall I put it…interesting.

Today I got stuck for at least an hour trying to understand why a RhinoMock stub wasn’t being called as it should. In order to illustrate the problem, let me present you with the code being tested (this is only for illustration purposes):

public class StudentService {
    private readonly ISession _session;
    public StudentService(ISession session) {
        _session = session;
    public Student GetStudent(Int64 studentId) {
        using(var tran = _session.BeginTransaction()) {
                return _session.Get<Student>(studentId);

In the real world, this service would implement an existing IStudentService contract and I’d be using code contracts to ensure that _session would always be a valid reference. In my real world example, I had lots of other things going on too, but the previous snippet is more than enough for me to make my point. Now, being a conscious developer, I knew I had to update the existing tests. I was already using RhinoMocks, so I’ve added structuremap’s RhinoAutoMocker to simplify the testing code.

After refactoring the code, I’ve ended up with something that resembled the following snippet:

public class StudentServiceReturnsExistingStudent {
    private readonly RhinoAutoMocker<StudentService> _autoMocker;
    private readonly  ISession _session;
    private readonly ITransaction _tran;
    private readonly Student _std;
    private const Int32 _id = 1;
    public StudentServiceReturnsExistingStudent() {
        _autoMocker = new RhinoAutoMocker<StudentService>();
        _session = _autoMocker.Get<ISession>();
        _tran = _autoMocker.Get<ITransaction>();
        _std = new Student {Id = 1};

    public void Test() {
        var std = _autoMocker.ClassUnderTest.GetStudent(_id);
        Assert.AreEqual(_std, std);

    private void Arrange() {
        _session.Expect(s => s.BeginTransaction())
        _session.Expect(s => s.Get<Student>(_id))

Ah, now let’s run the test. What? not working?


Not possible…what the hell is going on here? After looking several times and checking the types were correct (in my case, I had Dto.Student and Student, so I double checked if the types being expected were of the correct type), I’ve decided to ignore the arguments being passed into Get:

_session.Expect(s => s.Get<Student>(_id))

This small change was enough for making the test pass. In practice, this meant that there was something wrong with the setup of arguments in the Expect call. And sure, that was the problem! If you look carefully at GetStudent, you’ll notice that it expects an Int64. However, my test code was configured so that Get would receive an integer (Int32). Interestingly, calling GetStudent with an integer works without a problem (since going from int to long is considered to be a safe conversion). However, that does not happen when you’re building “RhinoMock expectations”. Moral of the story: if you think you’ve set up the expectations correctly and your test is not producing the expected results, double check the types of the arguments you’re setting up in the expectations.

And that’s it for now. Stay tuned for more.

Sep 24

Adding the SimpleMembership provider to an ASP.NET Web Forms app

Posted in .NET ASP.NET C#           Comments Off on Adding the SimpleMembership provider to an ASP.NET Web Forms app

If you’re a long time user of ASP.NET, you’re probably aware that the out of the box providers have some limitations. For instance, you couldn’t really use them with an SQL Compact database because they depended on stored procedure support for performing their actions. Besides that, clean up and maintenance in general depended on agents which run scheduled clean up tasks.

When Microsoft started working with Web Pages and the WebMatrix, they decided to have another go at this problem. Their first solution was known as universal providers and it solved the problem I’ve mentioned in the previous paragraph (ie, with the universal providers, you can  store your data in a SQL Compact or SQL Azure db) . The easiest way to add the universal providers to your project is to run the following instruction from the Nuget console:

Install-package Microsoft.AspNet.Proviers

Notice that I’ve used plural (provider*s*) because the package ends up installing session, membership, roles and profiles providers. You should also keep in mind that the previous instruction will also update the web.config file so that the app uses all these new providers ( if you’re just interested in one or two, don’t forget to clean up your web.config file).

But the team wasn’t finished yet. They’ve decided to introduce another provider, known as the SimpleMembership, which is way more flexible in its requisites regarding data storage (even though it’s called SimpleMembership provider, the truth is that the package introduces two providers: one for roles and another for membership – this is the most important one). Instead of forcing the use of a specific database table, this provider requires only that you specify the name of the table which is holding your users accounts and the names of the ID and username fields used in that table.

Now, there’s already some resources out there which show you how to get started with this provider (for instance, this one does a good job of explaining what you can expect from it) and that’s why I won’t be wasting your time explaining how it works.

If you’re using Web Pages, you’ll end up getting this provider for free. However, if you’re using Web Forms and you like what you see in that post, then you’re probably wondering about what’s needed to add it to your app. Once again, Nuget is your friend here Smile 

All you need to do to use this provider from your app is to run the following Nuget instruction:

install-package Microsoft.AspNet.WebPages.WebData

Now that you’ve added the required assemblies, I’ll leave it to you to explore the new features introduced by this new provider.

And that’s it for now. Stay tuned for more.

Sep 22

Razor 2: URL resolution improvements

Posted in ASP.NET MVC           Comments Off on Razor 2: URL resolution improvements

Until now, it was common to see this pattern in our views:

<script src="@Url.Content("~/scripts/myscript.js")"></script>

The Content method is a helper method which is responsible for converting a relative path into an absolute path. From now on (where now is the MVC4 release date which happened sometime ago Smile), we can simplify our code so that it looks like this:

<script src="~/scripts/myscript.js"></script>

Yes, we no longer need to resort to the helper because Razor is smart enough to translate all attribute’s values that start with ~/ into a   @Url.Content call. And when I say *all*, I do mean all. For instance, if the parser finds this:

<div data-info="~/info.txt">Some info</div>

It’s as if you had written this:

<div data-info="@Url.Content("~/info.txt")">Some info</div>

Notice you can also mix values with other code snippets. For instance, suppose you need to build an URL that combines an URL with some variable aux. In that case, you can simply write something like this:

<script src="~/scripts/@aux"></script>

The previous snippet will get translated into the following:

<script src="@Url.Content("~/scripts/")@aux"></script>

Simple, but nice, right? Razor 2 introduces a couple of other interesting features (ex.: conditional attributes), but we’ll leave that for a future post. Stay tuned for more.

Sep 20

The new Portable Class project

Posted in .NET           Comments Off on The new Portable Class project

One of the things that I needed to do in the past was to write a cross-platform project which had to be consumed from Silverlight and an ASP.NET MVC project. At the time, I was kind of lucky because you could reuse a Silverlight assembly in a .NET project provided that you only used some types (Christian Nagel has a nice post about this feature here).

This feature was nice, but it wasn’t perfect. VS 2012 improves it by introducing the new Portable Class Library project. This new project lets you write and build portable assemblies for Windows 7, Windows 8, Silverlight, Windows Phone and the XBox. Sure, there are still several limitations, but now you can reuse your assembly across a wider range of other projects types. Notice, though, that the assemblies produced by this project type can only target .NET 4 or .NET 4.5. If you’re interesting in getting more info about this new project type, then this will help you understand its restrictions.

And that’s it for now. Stay tuned for more.

Sep 20

Oh, and yes, I’m still alive and kicking ! (thanks for asking Smile)

In these last couple of months, I have really been really busy trying to finish up the Windows 8 and ASP.NET 4.5 Web Forms books (yes, at the same time Smile). I’m pleased to tell you that both books have entered their final stages, meaning that they’ll probably be out in mid October (at least, that’s what I’m hopping for).

When I look at my blog’s  right panel, I must confess that I still can’t  believe I’ve written so many books in so little time. I mean, when I was challenged to write a book about ASP.NET 2.0 (does anyone still use it? I know that my 2.0 book is still being sold, so the answer must be yes) by a couple of great guys at MS (thanks Nuno and Pedro!), it never crossed my mind that I would end up writing more than 10 books in 7 years. But it did happen and I can tell you that it was quite a ride. I’ve ended up learning a lot and “meeting” several guys along the way that really helped me improve the books and my knowledge in several areas (you guys know who you are, right?).

After all this time (and +10 books), I think it’s time to take a break and put aside my writer’s pen. Oh, no, I really don’t use a pen to write my books, but I do have a lucky pen that’s always with me and that helps me relieve my stress when I get stuck at something. I can’t really say that I won’t be writing any more books until I die. And yes, I’ll still be maintaining the ones that are out there. However, I think I’ll be having a somewhat long break. In other words, I won’t be writing any new book in the next couple of months. At least, that’s the plan. If you’ve been following this blog or if you know me, you’re probably thinking that I’ve said this before. But this time I really mean it.

The good news is that I should end up having some free time and that means I’ll probably be able to  take a deep look at several areas which interest me. As always, I’ll come back here to report my findings, hoping to help someone or probably get feedback on those things which “don’t quite click”.

And I guess that’s all for now. Stay tuned for more.

May 31

The “your developer lic has expired problem”

Posted in Windows8           Comments Off on The “your developer lic has expired problem”

Today, I’ve started getting another license error. I’ve tried to open a project I’ve built a few weeks ago and when I’ve hit F5, it simply redirected me to the store and shown me the following message:


Wtf? Another lic problem? why me??

Fortunately, I wasn’t alone in this one and I’ve found this post in the stackoverflow forums which did help me solve this problem. Instead of adding a string to the GUID, I’ve resorted to the Create GUID tool (VS->Tools->Create GUID) and replaced the GUID that was being used in the package name with a new one. And that was all it took to solve my problem.

May 18

Another one “bytes” the dust: my ASP.NET MVC book is out! :)

Posted in Books           Comments Off on Another one “bytes” the dust: my ASP.NET MVC book is out! :)

Once more, released by FCA and in Portuguese! It covers ASP.NET MVC 2, 3  and 4 (this release presents the new stuff introduced by the current beta). Btw, I should also mention that if anything changes from beta to RC or RTM, you’ll be able to get the updated info from the FCA site. Hope you guys like it Winking smile

May 07

Can’t renew your Metro developer license? Then this is for you!

Posted in Trivia Windows8           Comments Off on Can’t renew your Metro developer license? Then this is for you!

As you know if you read this blog, I’ve been unable to write any Metro JavaScript code for a few days because I couldn’t renew my developer license. Well, after complaining in the forums, I had the good fortunate to receive some attention from Mike Wong, who was kind enough to take this problem with the developer team. I must say that I wasn’t pleased with the initial solution and that I really unleashed all my rage on pour Mike. Fortunately, he redirected it to the team and come back with a solution which *doesn’t* involve reinstalling windows (this is really important to me because all my machines are only running Windows 8). So, here is what you need to do if you face the dreaded Metro license renew error:

  1. Remove all the Metro apps  you’ve installed which were built with your license. This typically means uninstalling all the apps you’ve opened in VS and hit F5 or CTRL+F5;
  2. Wait two days. I know it looks like a joke, but I’m serious: you need to wait for two days;
  3. After the those 2 days wait, you’re ready to rock-n-roll: it’s renewal time!

And that it’s. After the weekend, I was finally able to renew my license. Once again, special thanks to Mike Wong! Now, it’s time to code Smile

May 03

The unbelievable Metro dev lic renewing problem!

Posted in Trivia Windows8           Comments Off on The unbelievable Metro dev lic renewing problem!

This is simply unbelievable! As an early “Win 8 dev adopter”, I’m really stumped with the error I’m getting for the last couple of days. Being an early adopter means getting all sort of problems and being subject to changes which breaks everything you’ve written with the previous release. Sometimes, it’s not fun, but I can live with that.

What I can’t really understand is why I’m unable to deploy any app since Tuesday because my initial license is no longer valid and I’m always getting an error while trying to renew it. In order words, even though I want to write Metro code and provide feedback and ask questions in the forums, I’m simply unable to do (for 2 days now!) that because I can’t renew my license. This is not the way to bring more people to the platform! Want to use a lic system? Fine, but make sure that it works!!!

Did I mentioned that I’m pissed??

Apr 19

HTML5, 2nd edition is out

Posted in Books           Comments Off on HTML5, 2nd edition is out

I’ve been so busy in these last months that I’ve almost missed the release of the 2nd edition of my HTML5 book. I’ve added a new chapter on SVG and I’ve also added several new sections and examples to the existing chapters which illustrate how you can combine the new features introduced by HTML5 to improve your web sites. These new sections were added based on the feedback I’ve received from the 1st edition readers. I really hope these changes will help those who are interested in getting started with HTML5.

Mar 28

IIS 7.5 error 413:Request Entity Too Large

Posted in IIS           Comments Off on IIS 7.5 error 413:Request Entity Too Large

In these last days, we’ve finished moving an existing web site to a new server which was running IIS 7.5. This site had an upload service which used streaming for allowing the upload of some interestingly sized files. We’ve already had it running without any problems in IIS 6 and 7 (though in this case, we tested it using Windows 7), so it was a surprise to see that nobody could make an upload after the migration. The streaming service was returning the 413.Request Entity Too Large.

After some digging, I’ve managed to find a discussion in the IIS Forums which suggested that the problem was related with the uploadReadAheadSize attribute of the serverRuntime element. And sure enough, changing its default value in the apphost config file solved this problem because we were using SSL and that means the request entity body must be preloaded (and when that happens, the SSL preload will use that value for doing its thing).

Mar 09

It took me some time, but I finally managed to get the concepts of local vs. web contexts. It took some time not because they’re that difficult, but because the Windows 8 Metro docs are still a mess (which is understandable, since we’re still at beta – pardon me, I mean Consumer Preview) and finding someone with the time to explain it to me was not really as easy as I thought it would be. Anyways, that’s past, so lets get started.

WinJS app’s code can only be run in one of two contexts: local or Web. The need for having two contexts is motivated by the need to run code coming from different origins. For instance, you might need to embed a map in your app to enhance the way you present data to your users. In fact, you’ll probably need to interact with that map through code. Now, currently this might mean embedding a script reference to Google or Bing maps, and that really means we’ll have code written by others being executed in our app. Another good example of running external code is advertising. Typically, this also means adding a reference to an external script

If all the resources would run with the same privileges, then we might get into trouble because we can’t really know what all the 3rd party libraries do and we can’t really guarantee that all of them don’t have any malicious code (I’m sorry, but that’s just life!). And that’s why we have the concept of local vs. web context. The execution context under which a resource runs is responsible for granting features and imposing restrictions. For instance, all pages running in the local context can have full access to the WinRT and to the WinJS (some of those features depend on configuring the manifest to ask them to the final user) or even make cross domain calls (through XHR), but can’t reference any external scripts nor execute code by using the “javascript:code” scheme in an URI. Now, when code runs in the web context, some of these restrictions go away (ex.: external script references are allowed), but you’ll have new ones. For instance, you won’t be able to access the WinRT and you’ll only be able to access part of the WinJS features (for a list of these limitations, please read this).

Now, the important question: when does a resource gets executed in the local context and when does it get executed in the web context? Generally, people say that local content (i.e., content maintained inside the app’s package) runs in the local context and all external resources run in the web context. Even though this is correct in most cases, this definition is not really accurate. In fact, the platform will resort to the http scheme of a resource’s URI to see if it should be executed in the local or in the web context. All the resources using the ms-appx, run the in the local context and everything using the http, https or ms-appx-web scheme will be run in the web context. Now, ms-appx is used by default to reference resources maintained inside the app’s package (and you won’t be seeing them often unless you’re getting stuff from an external package). We all know what http and https are used for, so there’s not much to say here. What about ms-appx-web? Well, that’s the interesting one…You can use it to make a local resource run in the web context. When will you want to do this? Well, it might be a good option when you’re building mashups. For instance, suppose you want to add a map and need to write some JS code to interact with it. Since maps are added through external references, then you can’t insert them in your top page because that page will always run in local context. In that case, you can always build another local page which references the external map and has JS code to interact with it. Then, you can add an iframe to your top page which references that auxiliary local page through the ms-appx-web scheme (instead of using the default ms-appx scheme).

Btw, if you’re writing code and you need to know if you’re currently running in the local or in the web context, the easiest way to perform that check is to see if the Windows object exists or not (Windows, not window, ok?)

Now that we know the difference between both contexts and how resources are executed in one or the other, we still need to take a look at the ApplicationContentUriRules section (if you’re using the UI manifest editor, then I’m talking about the Content URIs tab). If you look at the docs, you’ll notice that this element “specifies the boundary of an app in terms of internet domain and URLs that the system hosting the app considers part of the app”. In other words, you can use this section to grant some extra privileges to external content which is going to be loaded in the web context. If I’m not mistaken, you’ll need to add an include rule to this section for any external content that tries to access the clipboard or get geo info from the geolocation object. Notice that you still won’t be getting any access to the WinRT. You can also add exclude rules and these should be useful when you want to allow a domain to access these features, while at the same time preventing a specific URI from being able to access them (this is possible because the URI specified can use a pattern for matching).

And I think this should make things clearer, right? Bottom line: a resource can only run in the local or in the web context and you can use the ApplicationContentUriRules section to allow external resources to access to the clipboard and geolocation objects.

And that it’s for now. Stay tuned for more.