Nicer way to check for a flag presence

Imagine you have this enum definition and a variable of same type:

[Flags] public enum Tubo { One, Two } ... Tubo tubo = Tubo.One;

Now, how do you check if a variable of type Tubo contains a flag, i.e. Tubo.One? Simple, like this:

bool b = (tubo & Tubo.One) == Tubo.One;

But do you really like this notation? I mean it is a lot of typing and the expression is not clear at first sight. That's why I checked out if extension methods might help. So I created this experimental method:

public static bool Contains<T>(this T list, T flag) where T : struct { return (Convert.ToInt32(list) & Convert.ToInt32(flag)) == Convert.ToInt32(flag); }

And the new test would look like this:

bool b = tubo.Contains(Tubo.One);

Isn't this notation much more readable and easy to type? Sure. But there are two drawbacks in here:

  1. If a non-numeric structure is used the compiler won't catch the error (the restriction of generic type T is struct) - at the runtime you'll get casting error when the structure can't be converted to Int32.
  2. Performance. There is a monstrous performance hit, like 500x slower. There are many operations involved - mostly because of Convert.ToInt32 method usage. (extension method call is probably inlined). There is no other way since, as far as Contains method knows, the arguments are struct types, and struct types can't be used like numbers just like that.IOW this code won't work:
  3. public static bool Contains<T>(this T list, T flag) where T : struct { return (int)list & (int)flag == (int)flag; }

    But if the code above worked one would get a decent performance, not much slower than doing a simple bitwise and operation.
Unfortunately there is no better solution AFAIK. It would certainly help if we could restrict generic type T to enum (where T: enum).

Slovenia/1st European Silverlight Challenge

SLODUG has launched the Slovene website of the 1st European Silverlight Challenge. You can read more about it in this post (in Slovene) or go directly to the website (also in Slovene).

Believe in your talent! Take part in the “European Silverlight Challenge” Competition – Dare to participate in the European Silverlight Development Competition. Win the recognition that goes with first place and, of course, fabulous prizes! (or 'swag' as our UK friends would say)

Note that words "fabulous prizes" are actually, thanks to the generous sponsors, an understatement.

So, hurry up, read the rules, apply and submit a silverlight application before the 28th January 2008.

Sometimes silent changes are for better

I've been reading monthly invoice from my ISP and a line caught my eye immediately. I've been a happy user of FTTH (fiber optics) 6Mb/6Mb Internet bandwidth for a while now and I saw two lines on my invoice: one charging me for 6/6 line and the other charging me for a 20/20 line which I don't have.

Suspecting a mistake in my invoice I've phoned to my ISP hotline number and got a shocking news. Everybody on FTTH got upgraded to 20/20 line which is now "slowest" speed over FTTH. All this for the same price of previously "slowest" 6/6 line. SIOL triplicated+ my (our) FTTH bandwidths for no charge. And they don't even brag or publicize this upgrade. They just did it silently. Go figure.

Looks like we got new year's gift a bit early.

Custom embedding using CodeRush

It happened that I had to embed plenty of asp.net elements into tables, i.e:

<table> <tr> <td> <asp:Label ... /> <asp:TextBox ... /> </td> <td> <asp:Label ... /> <asp:TextBox ... /> </td> ... </tr> </table>

Basically I had to put every Label/TextBox pair into its own table. The outcome has to be something like this:

<table> <tr> <td> <table> <tr> <td> <asp:Label ... /> </td> <td> <asp:TextBox ... /> </td> </tr> </table> </td> <td> <table> <tr> <td> <asp:Label ... /> </td> <td> <asp:TextBox ... /> </td> </tr> </table> ... </tr> </table>

And there were plenty of such pairs. So I was facing tedious manual repetitive work every decent developer tends to avoid at all costs. My first though was that it might be done with [CodeRush]. After all it has embedding functionality. Not only it comes with predefined set of embeddings - [CodeRush] allows you to easily create your own embeddings easily. But first let take a look how embeddings are accessible. There are two main ways. First way is through context menu in Visual Studio editor after selecting one or more lines:

image

As you can see there are plenty of embeddings out of the box. There is another way to trigger embedding functionality: through shortcuts (i.e. CTRL+3 in my VS triggers method embedding - embeds the method where caret is located in #region [MethodName] ... #endregion block. Actually I use this embedding heavily. Note also that embedding availability is based on language of the file where caret is positioned (i.e different embeddings are available for asp.net files and c# or vb.net files) and on the context (when invoking through shortcuts). But back to my problem. I actually needed two embeddings that would do:

  1. Wrap selection into <table><tr>...</tr></table> block
  2. Wrap selection into <td>...</td> block

Here is the how you add those two embeddings.

Click DevExpress/Options... menu to open Options window, expand the tree on the left to click on Embedding node.

image

Since these embeddings will work on asp.net files pick HTML as Language in combobox on the bottom of the form.

image

Click on the big green plus sign to add first custom embedding.

image

Assign name Tabloid and caption the same. Next select proper embedding style by clicking the first icon in Style row.

image

 

The final step is to type lines <table><td> above the special line Selected Text and </tr></table> lines below this special line. These lines will form embedding header and footer. That's it. It should look like this:

image

Repeat the same steps for the table cell embedding (named Celloid with caption Table Cell in my case):

image

We are done. Now let's try it on my example. First select all lines that have to be embedded into table (Label and Textbox in my case) and right click to show context menu.

image

There they are my two embeddings - FYI there are no predefined ones thus only mine are showing up. Here is the result after Tabloid embedding:

image

Do the same with Celloid embedding.

image

The result is a good one, too. Exactly what I was looking for.

image

So far this is a great time saver and annoying typing repellent. But [CodeRush] can be of more help. It is able to fire embeddings (and other stuff) through custom defined shortcuts. Mouse is great however it is not as fast as keyboard is.

Lets create the shortcuts. The goal is to bind key t to Tabloid and key d to Celloid embeddings. Open [CodeRush] options again but this time select Shortcuts tree node.

image

Click on New Keyboard Shortcut icon

image

In the Key 1 field type t (shortcut)in Command combo box pick Embed (action) and as Parameter type the name of embedding which is Tabloid in my case.

The shortcut is almost ready and the only thing left is to specify the context where the shortcut fires. If you don't set the context the embedding will fire each time you type key t wherever you are. This might be not the desired behavior. Set that the following conditions that have to be met: Selection should span Multiple Lines (one or more lines) and it should contain Whole Line. Also, the shortcut should fire only when editing in HTML View:

image

That's it. When you select one or more lines in HTML code (which includes ASP.NET) and then press key t the action Embed/Tabloid will be fired and your lines will be captured to a table.

Almost same steps are required to create Celloid shortcut on key d. Except for the context settings. Since context is the same in both cases a copy/paste operation can be performed on context. Right click anywhere in the Tabloid's context window and pick Copy Context.

image

Go back to Celloid, right click anywhere in the context window and pick Paste Context. Context is then copied and you avoid re-clicking all of the conditions (there might be plenty of them).

That's really it. I can go now through asp.net code, selecting lines and pressing t or d to embed elements.

Trust me, if you have many pages with many embeddings to perform you'll love this embedding feature of [CodeRush]. Now you can create all sorts of embeddings you want. Enjoy.

Thanks to Mark and Dustin for guidance.

Where has TimeZone2 class gone?

If you are following blogs about .net 3.5 you might have across this interesting post. It explains the benefits of new TimeZone2 class residing in .net 3.5 System.Core assembly. The best feature of TimeZone2 for me is the ability to convert time from and to different time zones. Perhaps it is worth to mention that dealing with time zones (read: dealing with daylight saving time) is something I would really like to avoid. Unfortunately world leaders don't think so and they are not just keeping up with daylight saving times, oh no, they keep changing the rules often, just to make it worse.

Before TimeZone2 was introduced one had to do the conversion between different time zones manually - as old TimeZone class knows only to transform from/to current time zone (ToLocalTime, ToUniversalTime). So, hura, for new TimeZone2 as described in the post mentioned above. I'll just use it.

<few minutes pass>

Hm, where is TimeZone2? No sign at all of it. Even reflector can't find it. After a little more reflectoring (using clues that TimeZone2 resides in new System.Core dll under namespace System) I've soon found the best new class that resembles the TimeZone2: TimeZoneInfo. Perhaps this change is mentioned somewhere, I just couldn't find it.

To make it short: if you are looking after TimeZone2 you should use TimeZoneInfo instead, the swiss knife like tool for dealing with time zones - this is what TimeZone should be from the beginning.

UPDATE: Here is a post that mentions renaming of TimeZone2.

WebConfigurationManager.OpenWebConfiguration throws Failed to map the path '/'.

Create a ASP.NET Web Site and put this piece of code into Page_Load method:

Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);

There are good chances you'll get Failed to map the path '/'. exception. The error is a peculiar one, even more so because the code is straight from the MSDN documentation. It happened to me when I've upgraded my ASP.NET Web Site Visual Studio 2005 project to 2008 (still targeting .net 2.0 framework) one.

After scratching my head for a while and googling around I've found the solution: run Visual Studio as administrator. Right, I've set my Visual Studio 2005 to run always as administrator and thus it worked before. After upgrading to Visual Studio 2008 the problem began to manifest - because I haven't yet set Visual Studio 2008 to run as administrator by default nor did I run it as administrator explicitly. So, to make it work you should run Visual Studio as administrator. Which is a problem because many people would use administrator privileges when developing (i.e. writing into Program Files folder - don't do it!). And when they'll deploy application to normal users it will throw exceptions one after the another.

So, be cautious when you are developing under administrator privileges.

UPDATE: I run Vista x86 OS. Not sure, but the same problem might be happening on XP/2003, too.