Viking Law #1

Today, while reading this old post from Emil Gustafsson about the Viking Laws and how they can be projected into the software development context, I just can’t stop thinking that his first law interpretation is missing one of the most important, if not not the most important, commandment.

Law #1 is all about bravery and aggressivety, and according to Emil it can be projected into software development as:

  • Be direct
  • Grab all opportunities
  • Use varying methods of attack
  • Be versatile and agile
  • Attack one target at a time
  • Don’t plan everything in detail
  • Use top quality weapons

I totally agree with all these commandments but one is missing and I think it should be the first:

  • Choose your targets wisely

Never attack a target when you know you’re not enough skilled to win. Sometimes the greatest bravery you can show is to recognize you’re not ready.

Enum types, FlagsAttribute & Zero value – Part 2

In my previous post I wrote about why you should pay attention when using enum value Zero.

After reading that post you are probably thinking like Benjamin Roux: Why don’t you start the enum values at 0x1?

Well I could, but doing that I lose the ability to have Sync and Async mutually exclusive by design. Take a look at the following enum types:

public enum OperationMode1
    Async = 0x1,
    Sync = 0x2,
    Parent = 0x4

public enum OperationMode2
    Async = 0x0,
    Sync = 0x1,
    Parent = 0x2

To achieve mutually exclusion between Sync and Async values using OperationMode1 you would have to operate both values:

protected void CheckMainOperarionMode(OperationMode1 mode)
    switch (mode)
        case (OperationMode1.Async | OperationMode1.Sync | OperationMode1.Parent):
        case (OperationMode1.Async | OperationMode1.Sync):
            throw new InvalidOperationException("Cannot be Sync and Async simultaneous");
        case (OperationMode1.Async | OperationMode1.Parent):
        case (OperationMode1.Async):
        case (OperationMode1.Sync | OperationMode1.Parent):
        case (OperationMode1.Sync):
            throw new InvalidOperationException("No default mode specified");

but this is a by design constraint in OperationMode2. Why? Simply because 0x0 is the neutral element for the bitwise OR operation.

Knowing this singularity, replacing and simplifying the previous method, you get:

protected void CheckMainOperarionMode(OperationMode2 mode)
    switch (mode)
        case (OperationMode2.Sync | OperationMode2.Parent):
        case (OperationMode2.Sync):
        case (OperationMode2.Parent):

This means that:

  • if both Sync and Async values are specified Sync value always win (Zero is the neutral element for bitwise OR operation)
  • if no Sync value specified, the Async method is used.

Here is the final method implementation:

protected void CheckMainOperarionMode(OperationMode2 mode)
    if (mode & OperationMode2.Sync == OperationMode2.Sync)
    } else { 

All wrote above prove that Async value (0x0) is useless from the arithmetic perspective, but, without it we lose readability.

The following IF statements are logically equals but the first is definitely more readable:

if (OperationMode2.Async | OperationMode2.Parent)

if (OperationMode2.Parent)

Here’s another example where you can see the benefits of 0x0 value, the default value can be used explicitly.

    <my:Control runat="server" Mode="Async,Parent">

    <my:Control runat="server" Mode="Parent">

Enum types, FlagsAttribute & Zero value

We all know about Enums types and use them every single day. What is not that often used is to decorate the Enum type with the FlagsAttribute.

When an Enum type has the FlagsAttribute we can assign multiple values to it and thus combine multiple information into a single enum.

The enum values should be a power of two so that a bit set is achieved.

Here is a typical Enum type:

public enum OperationMode
    /// <summary>
    /// No operation mode
    /// </summary>
    None = 0,
    /// <summary>
    /// Standard operation mode
    /// </summary>
    Standard = 1,
    /// <summary>
    /// Accept bubble requests mode
    /// </summary>
    Parent = 2

In such scenario no values combination are possible. In the following scenario a default operation mode exists and combination is used:

public enum OperationMode
    /// <summary>
    /// Asynchronous operation mode
    /// </summary>
    Async = 0,
    /// <summary>
    /// Synchronous operation mode
    /// </summary>
    Sync = 1,
    /// <summary>
    /// Accept bubble requests mode
    /// </summary>
    Parent = 2

Now, it’s possible to do statements like:

[DefaultValue(OperationMode.Async)] [TypeConverter(typeof(EnumConverter))] public OperationMode Mode { get; set; } /// <summary> /// Gets a value indicating whether this instance supports request from childrens. /// </summary> public bool IsParent { get { return (this.Mode & OperationMode.Parent) == OperationMode.Parent; } }



switch (this.Mode) { case OperationMode.Sync | OperationMode.Parent: Console.WriteLine("Sync,Parent"); break;



But there is something that you should never forget: Zero is the absorber element for the bitwise AND operation.

So, checking for OperationMode.Async (the Zero value) mode just like the OperationMode.Parent mode makes no sense since it will always be true:

(this.Mode & 0x0) == 0x0

Instead, inverse logic should be used: OperationMode.Async = !OperationMode.Sync

public bool IsAsync
    get { return (this.Mode & ContentManagerOperationMode.Sync) != ContentManagerOperationMode.Sync; }


public bool IsAsync
    get { return (int)this.Mode == 0; }

[Begin: Edit]

Some readers suggested to use the Enum.HasFlag method. Although it’s another valid approach it’s also widely accepted that this method has some performance issues related an internal box/unboxing.

Use it when performance is not a problem (I see this method mostly used by rookie developers).

[End: Edit]

Final Note:


Allow multiple values combination

The above samples snippets were taken from an ASP.NET control and enabled the following markup usage:

<my:Control runat="server" Mode="Sync,Parent">


Zero value is the absorber element for the bitwise AND operation

Be very carefully when evaluating the Zero value, either evaluate the enum value as an integer or use inverse logic.

OpenXML error “file is corrupt and cannot be opened.”

From time to time I ear some people saying their new web application supports data export to Excel format.

So far so good … but they don’t tell the all story … in fact almost all the times what is happening is they are exporting data to a Comma-Separated file or simply exporting GridView rendered HTML to an xls file.

Ok … it works but it’s not something I would be proud of.

So … yesterday I decided to take a look at the Office Open XML File Formats Specification (Microsoft Office 2007+ format) based on well-known technologies: ZIP and XML.

I start by installing Open XML SDK 2.0 for Microsoft Office and playing with some samples.

Then I decided to try it on a more complex web application and the “file is corrupt and cannot be opened.” message start happening.

Google show us that many people suffer from the same and it seems there are many reasons that can trigger this message. Some are related to the process itself, others with encodings or even styling.

Well, none solved my problem and I had to dig … well not that much, I simply change the output file extension to zip and extract the zip content.

Then I did the same to the output file from my first sample, compare both zip contents with SourceGear DiffMerge and found that my problem was Culture related.

Yes, my complex application sets the Thread.CurrentThread.CurrentCulture  to a non-English culture.

For sample purposes I was simply using the ToString method to convert numbers and dates to a string representation but forgot that XML is culture invariant and thus using a decimal separator other than “.” will result in a deserialization problem.

I solve the “file is corrupt and cannot be opened.” by using Convert.ToString(object, CultureInfo.InvariantCulture) method instead of the ToString method.

Hope this can help someone.

ELWEA – EventLog WebEvent Aggregator for ASP.NET

Last time I wrote about Health Monitoring was during 2008 and since then I ‘m using, on a daily basis, a complex Health Monitoring EventLog provider to aggregate WebEvents from specific ASP.NET web applications.

Last year I found ELMAH (Error Logging Module and Handler) project and became a fan of the concept:

“[…] facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.”

It didn’t take much time until I start thinking  about releasing a version of my EventLog WebEvents aggregator.

I’m now happy to announce that I finally made this project available at Codeplex and name it: ELWEA – EventLog WebEvent Aggregator for ASP.NET.

While different in nature this project main goal is pretty similar to the ELMAH project: keep an ASP.NET web application error tracking isolated and easily accessible.

What makes this project different from many other like ELMAH is the fact that it’s not focused on handling and persisting error info. This project main goal is to aggregate all EventLog data belong to a specific web application under a specific EventLog source name.



I’m sure that web developer and web site administrators will love it but I think that also IT pros that manage shared hosting environments will use it.

Visit here for a more complete description and here for the project documentation.

To make your live even simpler I’m planning to make a NuGet package available for ELWEA. Keep an eye on this.

Enjoy it!

.NET – ArrayList hidden gem

From time to time I end-up finding really old hidden gems and a few days ago I found another one.

IList System.Collections.ArrayList.ReadOnly(IList list)

This amazing method is available since the beginning (.NET 1.0).

I always complain about the small support for ReadOnly lists and collections and I have no clue why I miss this one.

For those of you that have to maintain and extend legacy applications prior to ASP.NET 2.0 SP2 this could be a very useful finding.

ASP.NET Controls – System.Web.UI.HtmlControls.HtmlButton client click hits the server twice

Hi all,

At work we have about 5000 PC’s that are mainly our commercial network. All those PC use intranet services and web applications.

Until a few months ago IE6 was our corporate browser (yep) but we ended moving to IE8.

A few days ago someone came to me saying that their application appears to have some problem because every time they click some HTML buttons the server gets two hits.

Also they are able to say that this didn’t happen when they used the IE6.

In the faulty application the buttons that trigger two posts were System.Web.UI.HtmlControls.HtmlButton controls with Click event handlers registered.

After some research I found that the default type attribute value for HTML BUTTON element has changed in IE8 and later (here).

  • In IE7 and earlier the default value is ‘button’
  • In IE8 and later the default value is ‘submit’

This changed in browser default behavior was not reflected in the Server-Control that renders it: it doesn’t set the type attribute value to button when a postback is required.

Without such change, every time we attached a Click event handler to a HtmlButton we endup with two posts: one triggered by the _doPostback function and another from the form itself (caused by the default type=’submit’ value.).

I easily bypass this problem by setting the type attribute value to ‘button’ in my base control.

Even so, I think that this change should be done by the framework itself when a postback is required in a HtmlButton.

After some ‘reflection’ I propose changing the System.Web.UI.Util.WriteOnClickAttribute method to do the job.

Such change would ensure the some behavior independent of the browser version.

If you have another workaround or you think I’m completely wrong please let me know.

Also if you think this is a real problem that should be solved then visit this Connect entry I create.

Patch For ASP.NET Vulnerability Available

Microsoft has published a Security Advisory (2416728) about a security vulnerability in ASP.NET on Saturday, September 18th. This vulnerability exists in all versions of ASP.NET and was publically disclosed late Friday at a security conference.

Scott Guthrie has provided information on workarounds (please see Important: ASP.NET Security Vulnerability and ASP.NET Security Vulnerability) to prevent attackers from using this vulnerability against their ASP.NET applications.

To help with Microsoft’s response to the new padding oracle vulnerability, a new forum was also set up: Security Vulnerability.

Microsoft has now announced the release of an out-of-band security update to address the ASP.NET Security Vulnerability.

Applying the update addresses the ASP.NET Security Vulnerability, and once the update is applied to your system the workarounds Scott has previously blogged about will no longer be required. But, until the update has been installed, those workarounds must be used.

You can learn more about this security update release from this reading the Microsoft Security Response Center Blog Post as well as the official Advance Notification Bulletin.

Important Links:

2010 Microsoft® MVP Award

It’s now official and public. I was reward with the MVP award in ASP/ASP.NET.

This award is a huge responsibility but is also a sign that shows the right way.

During last year I learned many things and also made some mistakes.

What I can say about next year is that my guidelines won’t change: learn, help and share.

Thanks everyone.