
Thursday, April 26, 2007
Just about to leave to Las Vegas for the MIX'07 and with a chance in my hand to interview Scott Guthrie, I would like to apply the concept of the TV Show with the same title as this post, mostly known in Spain, where a set of citizens asks different questions to their government president.
Well, my idea is as follow, I would like to extend my interview with questions from all over the world and all kind of readers. So, do you have any interesting question to ask Scott Gu? feel curious about anything technical or professional about him?
If you are on the YES side, don't hesitate to write them at the end of this posts. Use the comments section, and I'll manage to include them within my interview (as far as they are policatlly correct)
Thanks all, and see you in Vegas!

Friday, March 09, 2007
One more post today to say that I'll be attending MIX'07 this year with a couple of friends from Spain, the winner of the gadget contest and Europe community leaders/influencers. It will be my first visit to Sin City, so hope to come back complete :)

http://www.visitmix.com
And after that, I'll spend a couple of days in London visiting Wonder Boy and attending a couple of concerts over there.
We still running the first gadget contest held in Spain, organized by the Madrid .NET User Group with the support of lot of companies and people. If you haven't checked it out yet go to http://gadgetizate.madriddotnet.com
So, I think now it's the time to tell people about some of the ideas I have to develop some gadgets. This ideas were private and I planned to develop them by my own, but you know, I'm so busy I don't even have time to write them. So here they go, feel free to develop any of them and get a chance to visit Las Vegas:
- A download manager, integrated within Internet Explorer, that makes use of the BITS API integrated in XP and Windows Vista
- A snow report gadget that informs you about the state of the slopes in your favourites ski resorts
- A gadget that keeps a list of cool taglines that can be used in the MSN Messenger personal message. The gadget can include a set of mood states and change automatically the message depending on the mood you choose
- A technorati monitor that keeps track of when your blog or blogs are linked in other places
- A gadget that monitor you websites and tells you when any of your sites is down
- A gadget that aggregates statistics from Alexa or your personal sites stats (via IIS logs, awstats, or any stats software) and keep a cool graph of how your sites behave
- A Google AdSense monitor that keeps track of you earnings with google advertisment
- A YouTube/SoapBox viewer, where you can put the code of the video and play it directly on a flyout window
- A Last.fm Groups of the Week gadget that recomends you songs to listen and your personal TopList of bands.
I have a couple more of them, but I keep them private :)
Hope you like this list and feel free to create any of them... just drop me a line in the readme or help of the gadget jiji
This is just a quick note, getting out of my actual busy status, to let you know that I'll be attending the Globlal MVP Summit in Seattle next week. If you feel like having a chat or something, drop me a note.
Anyway I'll be attending, with lot of friends from Spain and Europe, to Jeffrey Palermo's party... if you are an MVP and haven't heard of it yet, read this and join us next Sunday.

Friday, February 16, 2007
We are actually holding a contest in the context of Madrid .NET User Group that can take you to Las Vegas with your Gadget for Windows Vista.
The rules are easy. Build a gadget for Windows Vista Sidebar and submit it to the contest. Participation is open from 16th of February to 29th of March. And winners will be announced at Developer Days 2007 the 29th of March in Madrid, Spain. You can submit as many gadgets as you want to, but the only requisite is that you have to be living in Spain.
We have a big first prize that consists of a travel to Las Vegas to attend Mix'07 and spend 5 days there with all the guys and influencers from EMEA. There will be a special flight from Microsoft departing from London, we'll take you there and you could spend 5 days with lot of the most interesting and smart guys over the world. This prize includes flight, lodging and event expenses; and I think there's is also included an helicopter trip over the Grand Canyon :-)
The rest of the prizes are an Xbox 360, a smartphone, 30 development books in Spanish, 3 subscription to DotNetMania magazine and software licenses by JetBrains, RedGate and ComponentOne.
To give the same chances to all of you (because the winners will be decided by the site visitors; they'll vote the best gadgets) the web is published with a big banner telling about the contest, and gadget submission and gallery will open next Monday. So you have all the weekend to prepare your first gadget.
Check it out at http://gadgetizate.madriddotnet.com
You can redistribute this and the images as far as you want to. Spread the word.
I would like to thank all the people that made this possible, people that provided the money and prizes we needed to run this contest: Scott Guthrie and Ray Winninger from MIX'07; David Stennett from JetBrains; Rachel Hawley from RedGate; Catherine Geiger from ComponentOne; Susana Krahe and Juan Miguel Asensio from Anaya Multimedia; Paco Marín from DotNetMania; Chema Alonso from Informática 64; Agustín Rodriguez from ilitia technologies; and Alfonso Rodriguez and David Carmona from MSDN Spain. And of course, all the coordinators of Madrid .NET User Group for collaborating creating this: David Herraiz, Daniel de Andres and Jesús Jiménez. Thank you all, you made this possible: around 12.000 EUR in prizes!!!!!!


Tuesday, January 30, 2007
This is a quick note to myself. I always forget how to get which svchost.exe process is hosting a service that I need to debug. It's quite simple, from the command line just type:
And you'll get a list of all the service hosts running, with a detailed view of which services are contained in each host and the process id associated. Faster and easy way to attach to the process and debug it.

Wednesday, January 17, 2007
I've been up preparing the catalog of training courses for this year at Ilitia. I had to prepare a small A4 flyer to show up in events and clients, and I decided to give Microsoft Expression Design a try. Thus, I had to download and install it on my Vista laptop. Everything went fine.
The tool itself seems much better than previous beta's or ctp's and it ran flawlessly to create the sample flyer I needed. Anyway, I've seen some strange things that are more complicated or hidden than in other design suites (Freehand, Corel Draw, Illustrator or Fireworks):
- It took me a lot of time to figure out how to create text inside a shape (rectangle in my case) because it's called Adapt Text To Path. To me that means to draw a path and put your text over it, adapting to the path. This was a bit hidden.
- Although it seems possible to export to EPS format, it's not available to import files in EPS format. This is a must!
- I had an strange error when using the drop tool to get a color from the screen. It completely crashed the application, but I was unable to repro it.
- Exporting your design as PDF has some errors... if you have some text layers over shape layers, it wouldn't raster your text into the PDF. To solve this I had to convert all the text to paths and then export to PDF.
- The fill tools are not intuitive. I need some time to figure how to create a gradient for a shape.
- The fill with texture tool is not really complete, there are not too much patterns to add as textures to shapes and I mean really used patterns like dots, lines, etc.
Anyway I think this tool would have a great potential, because it seems it's getting mature. Don't know when it's supposed to be released to market but I'll try to provide this feedback to Microsoft, so they can see if it's something they can improve. This is how it looked while designing the flyer I linked to before:


Wednesday, January 03, 2007
Denis van der Stelt tagged me. I knew this would reach me sooner or later, sooo as everybody is playing I'll keep growing it. So here is my list of five things that you'll probably won't know about me :
- When I was younger I used to play in a local band. It was this kind of bands that go through the city in Easter or during special days. I played a series of instruments and the last one I was playing was an slide trombone :)
- I guess some people already know this. In fact, they've seen my reactions when exposed to a Duck. I don't like them; people tend to say poor ducks, poor ducks but I'm scared of them. When I was a child I had a fight with one of those aggressive animals; actually, the duck fought with me, I was just running and crying.
- I like to cook. I mean, I really love to do it. I use to invent all the food I cook. I cook my own food almost everyday and take it to the office. I would love to find a school here in Madrid where I can learn the right and appropriate techniques to improve my cooking. Anyway, I'm happy with my results, and lot of people are curious about how and when did I learnt to do it: it's just a matter of time doing it, since I was a child I've been raised as the older of three boys and I had to take care of the food most of the time when mum was working. So I learnt to love it.
- I really love graphic design, music and coding. To me, all of them are expressions of art; ways to express yourself. I consider myself good in all of them, but I'm more productive coding, then designing and the creating music. When people see other things I create, not related to code or programming, they get shocked because they don't understand how could it be. But it's quite simple, in my early teen age I joined an Spanish demogroup called Polygon and we started to create graphic routines, music and designs sync'ed together. This is the reason why I got my eyes educated in design and photography, my ears educated on music and my brain educated on coding. If you feel curious about it, go and check http://www.demoscene.org
- Related to the above, after a couple of years living in Madrid, I was working around 6 months as a "cool hunter" ... I just walked through the streets with a camera and a notepad; taking notes and taking pictures of anything interesting in fashion, street art, events or similar that could be an upcoming trend. When I was almost finishing my report, I got my camera stolen while eating in a restaurant with my friends Kelly and Alex; I lost all the pictures in the roll inside the camera. And this kind of interest in street art makes me get involved with movements like flashmobs or freehugs (you can try to catch me in Madrid's streets doing it)
And now, let's spread this over the Spanish community... I tag to David Carmona, Rodrigro Corral, David Salgado, Ricardo Varela and Pablo Pelaez

Monday, January 01, 2007
This is just a good way to start a new year. Yesterday night I went out to celebrate the new year. I went to sleep really late, around 10am. Woke up a couple of hours ago. And the first thing I see in my mailbox in 2007 says:
Felicidades! Es para nosotros un honor nombrarle MVP de Microsoft® 2007.
It's in spanish, but it just translates to "Congratulations! You've been awarded Microsoft 2007 MVP" ... So it seems that my community activities during 2006 were enough for Microsoft to renew my MVP status. I wish all the years started like this, with a good new just to say "hello new year"
Enjoy and have a nice new Thread(2007).Start();

Friday, December 29, 2006
For those of you who are not up to this story, Microsoft and AMD decided to give away 2000 free high-end Ferrari laptops to bloggers and influencers preloaded with Windows Vista Ultimate or even Media Centers. For free. That sounds pretty nice if you are one of the chosen bloggers. But this started to make clicking sounds and roars soon after it was announced over the blogsphere.
Some people thought they deserved also one free laptop, while others didn't disclosed it was a gift from Microsoft. Some others started to talk about Microsoft buying good reviews of Vista and some readers started to blame bloggers about not being objective in their reviews because they've been "paid" by Microsoft.
Wow!! This topic is completely grinding its gears.
Microsoft has always gifted influencers and collaborators, just have a look to MVP and Regional Director programs. Lot of people was participating in the Windows Vista Beta Program, and they sponsored free Vista keys to some of the most active bug reporters. It's not a matter of buying good reviews. It's more a matter of providing a good Vista experience so you can express yourself freely about the real user experience. Of course, if I had to choose people to try Vista at it best they would be the most active Vista influencers.
So I think this doesn't seems too important... it seems more like a jealousy thing from people that didn't received one (and of course I didn't) ... I don't think anyone would change it's objectivity for this or would your ethic sway with such a gift?
Personally my ethic or objectivity never swayed when talking in Microsoft presentation or events, blogging about them, talking about bugs, productivity or any other issues... I think the main topic they are looking for while creating communities is people that are able to talk coherently about their experiences with their products, not someone you can buy with a gift.

Thursday, December 28, 2006
Next year it's starting with a busy busy month. This is the list of the engagements I already have, if you are nearby any of the cities I'll be visiting don't hesitate and we can have some beers ;) I'm also interested in meeting people in Tenerife that are willing to join INETA and create a .NET User Group over there...
So actually this are the planned speaks:
- C# 3.0 Language Features // Madrid .NET User Group, January, 18th 2007
Introducing Extension Methods, Query Languages, Lambda Expressions and all the upcoming C# 3.0 language features. Further details and registration at http://www.madriddotnet.com
- C# 3.0 Language Features // .NET User Group Galicia, Coruña, January, 19th 2007
First meeting of .NET User Group Galicia, and I'll be there presenting Extension Methods, Query Languages, Lambda Expressions and all the upcoming C# 3.0 language features. Further details and registration at http://www.nugg.es
- LOVE Tour: Windows Workflow and Windows Communication Foundation // Tenerife, January, 23rd 2007
I keep collaborating with MSDN presenting .NET Framework 3.0 over major cities in Spain. This time I'll be in Tenerife (Canary Islands) presenting Windows Workflow and Windows Communication Foundation. Further details and registration at http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032312578&Culture=es-ES
- LOVE Tour: Windows Presentation Foundation // Málaga, January, 25th 2007
I keep collaborating with MSDN presenting .NET Framework 3.0 over major cities in Spain. This time I'll be in Málaga, directly from Tenerife, presenting user interface improvements with Windows Presentation Foundation. Further details and registration at http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032312580&Culture=es-ES
More to come for February.

Wednesday, December 27, 2006
A couple of days ago my fellow friend Ricardo Varela started to blog in spanish (in parallel with his actual english blog). Former member of Microsoft communities, he is actually working at Google UK. The actual point is that on his new blog he started a post with some kind of coding teasers, going back to basics, to the principles of coding. This is going to be funny.
Well, this is my answer to his post. There were three questions regarding data structures and alternative thinking about reversing things.
- Do you know how to reverse a string? In example, if you get "abc" the returned string should be "cba"
This seemed pretty easy. In C# every string is represented as an array of chars, so you can use the indexers to get chars at any position and reverse them "manually" with something like:
string inputString = "abc";
string reversedString = string.Empty;
for (int c = inputString.Length; c > 0; c--)
{
reversedString += inputString[c - 1];
}
Console.WriteLine("Original String: " + inputString);
Console.WriteLine("Reversed String: " + reversedString);
Or you can use some of the features of the .NET Framework to do it in a more "elegant" way:
char[] chars = inputString.ToCharArray();
Array.Reverse(chars);
// Use the reversed array of chars
- Going deeper into data structures, do you know how to reverse the bits of a byte? In example, if you get 1 the returned byte should be 128
I must admit this was a hard one. Although I perfectly know the concepts of bits and bitwise operations the C# language doesn't provide an easy or structured way to access those elementary elements of data structures. I finally managed to achieve it. The smallest numeric data structure available to represent a byte internals I found was a simple byte[8], so now I just have to fill it with the values for each byte:
static byte[] getBits(byte inputByte)
{
byte[] bits = new byte[8];
for (int p = 0; p < 8; p++)
{
bits[7 - p] = (byte)(1 & (inputByte >> p));
}
return bits;
}
Simple? Ok, I'll explain it a bit... the bitwise operator >> just shifts the bits in the byte to the right so if 01010101 is shifted one position to the right it becomes 00101010... then I perform a logical AND operation with the mask 00000001 to determine if the bit is setted. I just store the state of every bit in the output array and return it. As a quick note, the bit array could be directly reversed if I change the line inside the for loop to:
bits[p] = (byte)(1 & (inputByte >> p));
But I wanted more generic methods to convert between byte and bits, so I didn't included reversing directly in that method. Once I have an array, it's simple to reverse it just with the previous method used with string arrays or via the .NET framework features:
And know, we only have to be able to convert the bit array back to a byte structure:
static byte setBits(byte[] bits)
{
byte obyte = bits[0];
for (int p = 1; p < 8; p++)
{
obyte = (byte)((obyte << 1) + bits[p]);
}
return obyte;
}
The method used is similar to the one I used to extract the bits, but this time the bitwise operator << is shifting bits to the left, so I can increase the number til it reach to the desired value. A simple test program to test how it works would be:
byte inputByte = 1;
byte outputByte = 0;
byte[] bits = getBits(inputByte);
Array.Reverse(bits);
outputByte = setBits(bits);
Console.WriteLine("Input Byte: " + inputByte);
Console.WriteLine("Reversed Byte: " + outputByte);
- And a more complex one. Floating point numbers are represented usually by the standard IEEE 754, would you be able to reverse the bits of a floating point number? In example, if you get 118.625f the output should be -17180580000f
Wow! This is was a really hard one. I didn't know how the IEEE 754 standard worked so I read it at the wikipedia (the IEEE page for this standard is under revision and there was no info available) and it seems pretty simple. The floating point its a 32bit data structured divided like this:

So now it seems much simpler to me. It's just a bit reversing operation, in C# the two floating point structures are Float or Double, the former to store floating point numbers with 32bits precision and the last with 64bits; the problem is that those types don't allow bitwise operations, so I need to create a new set of methods to work with them using the BitConverter class.
It's probably refactorizable so just a pair of methods suit all the needs of bit operations, but the goal was to reverse the floating point number, so here I go:
static byte[] getFloatingBits(double input)
{
byte[] bytes = BitConverter.GetBytes(input);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
byte[] bits = new byte[64];
for (int i = 0; i < 8; i++)
{
Array.Copy(getBits(bytes[i]), 0, bits, i * 8, 8);
}
return bits;
}
I explain the method it...The float type can by divided into 4 bytes and the BitConverter.GetBytes method can give us an array of that four bytes, but unfortunately it doesn't include a method to turn back an array of four bytes to a float, so I created this method for the double type and used casting :(
The method is pretty simple, I extract the 8 bytes of the double precision float number. Then, I verify if the processor is LittleEndian and in that case I reverse the byte order to reflect the actual value. Everything is copied to an array of bits, and we are done. Now we only need to reverse that array of bits:
And turn back to the method that reverse the process from a bit array to a double precision floating number:
static double setFloatingBits(byte[] bits)
{
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++)
{
byte[] actualByte = new byte[8];
Array.Copy(bits, i * 8, actualByte, 0, 8);
bytes[i] = setBits(actualByte);
}
if (BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
return BitConverter.ToDouble(bytes, 0);
}
The issue is that the expected floating number is not the one I got with this method that reverse the complete array of bits. In fact, I've also re-read the question and it said "are you able to reverse the order of the bits for the exponent and mantissa?" ... I actually did also that, reversing only bits for mantissa and exponent, obtaining the following bit arrays:
Original: 0 10000000 10111011010100000000000
Reversed: 0 00000001 00000000000101011011101
Expected: 1 10000100 00100000000000000101011
But that reversed number doesn't represent the one that Ricardo stated in his post. What am I doing wrong? Is anything wrong in my point of view or is the expected number wrong? I'm really curious about why there is one bit less in the expected number and how the sign bit changed.

Monday, December 25, 2006
This year is touching its last days. It's been a funny and active year both in personal and professional sides of me. I hope you also got what you expected from it.

I wish you have a nice christmas and start the new 2007 full of energy and achievements.
Enjoy this season!

Thursday, December 21, 2006
It's been finally released. Yesterday. So if you installed Visual Studio 2005 Service Pack 1 over your Windows Vista SO you can now get rid of that annoying popup that knocks every time the IDE is started. This patch tries to address some of the issues related to the use of Visual Studio 2005 in Windows Vista.
Go and download from http://www.microsoft.com/downloads/details.aspx?FamilyID=fb6bb56a-10b7-4c05-b81c-5863284503cf&DisplayLang=en
I've already downloaded and installed it. And to be honest, I'm pretty nervous to see what improvements and features had been included in Visual Studio 2005 and, most important, in Team Explorer, Team System and Team Foundation Server (all of them also touched by this service pack)

Monday, December 18, 2006
Yesterday evening I just decided to go and get an Xbox 360 System. I was a bit reticent to get this console because I'm an active fan of PS2 because of the Final Fantasy series. Anyway, now I'm starting with the Xbox360 but actually I only own one game: Splinter Cell Double Agent.
Things I loved from my first eXperience: the user interface, Xbox live options, media center capabilities and the way my Vista Ultimate detected my Xbox and added it as an extender. I also love the chance I have to create XNA stuff from my computer and play them in the Xbox; let's see if this turns out to be a good idea :)
Things I didn't loved that much: is there any reason for such a big external power supply????
So if you are also on the 360 side of the life, go and join me to play something. My gamertag is:
PD: Sunday Geek stands for a category to post whatever a kindofgeek does on a typical Sunday.

Saturday, December 16, 2006
I was reading a post by Perci Reyes (spanish link) inspired by a Coding Horror post about understanding code. After reading it and all related links (Joel's thoughts and Peter Hallam's post) I have something to add that it seems nobody thought about...
I agree we all of the authors about the current developer's activities statistics... and maybe it's true that we spend a lot of time trying to understand code. By default, programmers are so narcissist that they need to feel they created something, so they are prone to change anything they don't understand to a more suitable and personal solution, under their point of view. Everybody seems to argue about this narcissism and programmers willing to rewrite instead of understanding but I have some doubts about it being a programmer's problem instead of a code problem...
I mean... is the code too complex to understand it? Maybe it is. I've personally seen thousand of lines of code impossible to read and understand because the chosen architecture, data or business layers, presentation model or even UI layer where poorly and improperly designed, or even not present at all. That adds lot of complexity, but you should agree it's not related to the programmer modifying that code. It's related to the code itself. That code was once written by a developer that thought it was the best solution to the business problem (or maybe it was the best suitable solution possible that could be written with the project, developer and solution constraints present at that time; or maybe related to a lack of experience or knowledge in the side of the developer on how to write that code)
I guess that if a team of peers are developing a solution they do it the best way they can, using known patterns, decoupling code and user interface, and refactoring classes and methods. Following some simple rules you should be unable to find something like a 400 lines method or a class with only one method and 2000 lines of code. And I swear this kind of code exists, I've seen it lot of times.
In that case I would obviously replace and rewrite the smelly code. Not because I prefer it my way, just because it's so poorly designed that it will drive us mad while developing the solution; but most important, it will frustrate working hours of future developers maintaining that code.
So, my point about all that thread of posts was simply to include that developer's are narcissist but they are also able to read understandable code. The problem is introduce by poorly designed software, that actually is pretty common to find anywhere. We need to have in mind that any software we develop will hit production sometime, and it will be supported by a team of developers (maybe not the same team who wrote it) that will need to understand it.
So, my personal advice is (and this is what I actually do when I wrote code in a project) that every developer out there should write the code the best way possible but always making it perfectly readable and understandable. The code must talk by itself, not through the use of code comments, and you should refactor and simplify it until you get something readable and understandable by mere humans. It's not that hard. There are lot of practices to achieve this goal and it will also, under my point of view, make you a better developer; but my favorite statement about this is:
"if you feel the need to add a comment, just refactor your code so it the comment seems superfluous; this way your code will be simpler and easier to understand"

Monday, December 11, 2006
Just a quick note to let you know about the first event for Artalde, the recently created .NET User Group in Bilbao. The event will take place this Wednesday, 13th December at Deusto University. I will be speaking, together with Oscar Alvarez from Ibermatica, about Windows Communication Foundation.
If you are in the area don't hesitate to pass by and have a chat with us.
Proceed to the registration page located at MSDN Events
By the way... this wednesday it's going to be a pretty active day in the Spanish Usergroup scene because people at NavarraDotNet, the also recently created .NET User Group in Pamplona, are helding their first public meeting featuring Chema Alonso from Informatica64 speaking about Developer's Security. Go and check the registration page at MSDN Events

Monday, December 04, 2006
A lot of people asked me about the percentage in my messenger nickname. Some of them thought it was the actual completion state of any of the project I'm involved, and they were wondering how in hell was I able to measure it so precisely.
In fact, the percentage in my nickname (actually 63,78%) is not related to technology, but to nature. It's the level of the water reserve in Madrid. I've been monitoring it during the last 5 or 6 weeks. Daily. Going to the local water company and checking it manually. It actually surprised me how we moved from a poor 27% to the actual reserve in such a little time frame. Amazing. And obviously, it's pretty welcomed.
But this task it's boring. Really boring. I wanted that info directly on my desktop. So, this seemed like a perfect place for Inspector Gadget to play with Vista!!!
We first need a simple Html page to host all the gadget code. It's simple javascript + html, also know as the pretty famous dhtml. We then need a simple icon to show in the Gadget Library and of course bunch of nice javascript intervals, json, webservices, xml and xsl parsers to get all the data.
So I managed to get access to a webservice providing the percentage of water reserve for Madrid and wrote the code to embed it into a Gadget, dragged it to my Sidebar and et voilá! it's doing the hard work for me.

If you feel like curious about how it's done, download the actual Agua Gadget and inspect the code. It's pretty simple yet. I plan to upgrade it to support settings, nicer graphics and be able to monitor more areas of Spain (my current knowledge about water distribution is limited to Spain, but if you know any source of data to your region, don't hesitate to contact me and I would love to include it)
Download Agua Gadget 0.1 for Windows Vista. To install, simply unzip it and double click de .gadget file. Windows Vista would install it for you :)
You can find more info on how to create a basic Sidebar Gadget at this step by step tutorial and more info at the System.Gadget namespace reference.

Friday, December 01, 2006
During the following post I'm going to explain a design pattern widely used during software development processes and how it fits into the .NET ecosystem. This pattern would probably fits into the structural patterns group and it's mainly used to decouple components, so abstractions and concrete implementations can vary independently.
Using the provider pattern in .NET (and most object oriented languages) is pretty easy. We need the following artifacts:
- A provider definition, used as a contract that specifies what it should do
- One or multiple provider implementations of the declared contract
- A consumer willing to make use of the provider and it's implementations
Imaging the following real life scenario: There is a basic definition of what a car should do (provider definition) and what is considered a car: it must have 4 wheels, an engine, steering wheel, etc.. in the market you are able to find lot of implementations following the actual definition of a car (implementations of the provider), and we, as consumers, can make use of the knowledge and methods defined in the provider contract to change the implementation we use without affecting our behavior (we are able to switch cars and use the common definition of it, as a car, to drive any of the implementations).
So know, imagine it in the context of software development. We have an interface that defines a set of properties and methods that our provider must implement; we then have one or multiple implementations of that interface available; and of course, any consuming application can use the interface to switch between implementations without being affected. Have a look to the following diagram:

This is pretty awesome and practical when we are willing to create componentized and decoupled applications. We just use interfaces. This pattern has been widely used in the new ASP.NET 2.0 to create the application services provider infrastructure. For example, the MembershipProvider can be defined either as SqlMembershipProvider or as a custom OracleMembershipProvider; they both provide the same functionality but with different behavior (one uses SQL Server as repository while the other is using Oracle databases)
This pattern itself, IMHO, can dramatically increase the quality of your architecture because of the modularity and simplicity it provides.
One of the hidden treasures of .NET is the existence of a Provider Model Framework that allows you to create custom Providers for anything (not only extensions of ASP.NET Providers, but any kind of .NET application or service)
Using .NET Framework 2.0 Provider Model
So let's start writting some code. To create a provider we first have to create a public abstract class that defines our contract. This class must implement the System.Configuration.ProviderBase abstract class and it should contain the definition of methods and properties used as the "contract" of our provider.
1 public abstract class ImageProvider : ProviderBase
2 {
3 public abstract bool CanSaveImages { get; }
4 public abstract Image GetImage(int id);
5 public abstract void SaveImage(Image image);
6 }
We then need to add the actual implementations of the provider. In this case, we are going to add an image provider for the file system and an extra one for SQL Server.
1 public class FileSystemImageProvider : ImageProvider
2 {
3 public override bool CanSaveImages
4 {
5 get
6 {
7 return true; // As we allow to save images
8 }
9 }
10
11 public override Image GetImage(int id)
12 {
13 // Some witty code to get the image from a folder in the FileSystem
14 return null;
15 }
16
17 public override void SaveImage(System.Drawing.Image image)
18 {
19 // Some witty code to save the image to a folder in the FileSystem
20 }
21 }
22
23
24 public class SqlImageProvider : ImageProvider
25 {
26 public override bool CanSaveImages
27 {
28 get
29 {
30 return true; // As we allow to save images
31 }
32 }
33
34 public override Image GetImage(int id)
35 {
36 // Some witty code to get the image from a folder in the FileSystem
37 return null; ;
38 }
39
40 public override void SaveImage(System.Drawing.Image image)
41 {
42 // Some witty code to save the image to a folder in the FileSystem
43 }
44 }
And finally, we need to create the service that will use the ImageProvider. It's is coupled to the contract definition of our provider and not to it's implementations, so it knows what to ask for but no actually how or where will it be done. The service just initializes the provider using the LoadProvider() method (it should read the provider from the config file; have in mind that here it's hardcoded for instructional purposes and you only need to change the LoadProvider method to achieve that goal)
1 public class ImageService
2 {
3 private ImageProvider _provider;
4
5 public ImageProvider Provider
6 {
7 get
8 {
9 return _provider;
10 }
11 }
12
13 public ImageService()
14 {
15 LoadProvider();
16 }
17
18 public void LoadProvider()
19 {
20 ProviderSettings ps = new ProviderSettings("FileSystemImageProvider", "FileSystemImageProvider_Type_Assembly");
21 _provider = ProvidersHelper.InstantiateProvider(ps, typeof(FileSystemImageProvider)) as ImageProvider;
22 }
23
24 public Image GetImage(int id)
25 {
26 return _provider.GetImage(id);
27 }
28
29 public void SaveImage(Image image)
30 {
31 _provider.SaveImage(image);
32 }
33 }
The main caveat of using the .NET Provider Model is that you must reference the System.Web assembly in, probably, non-web projects. This is needed in order to access the ProvidersHelper class used to instantiate the provider collection. And it also forces the application to use the System.Configuration namespace and classes to read the provider configuration located in the web.config or app.config files.
You'll have to deal with the types and assembly names where those types are defined to create the ProviderSettings instance needed by the ProvidersHelper.InstantiateProvider method. It's maybe not recommended to use all this "web" references in a desktop or service context; so there's a clean and elegant alternative for the OO purists :)
The pure OO implementation
So, we need to get rid of the System.Web reference and make the provider pattern work without using the .NET Framework 2.0 model. The first thing we need to do is to refactor provider's abstract class to an interface (or leave it as a class, it's up to you, but remove the ProviderBase inheritance and any reference to the System.Configuration namespace) and change the concrete providers implementations to make them use the newly created interface. The class diagram should look similar to:

First, we should create the following code for the provider contract:
1 public interface IImageProvider
2 {
3 bool CanSaveImages { get; }
4 Image GetImage(int id);
5 void SaveImage(Image image);
6 }
And of course change the signature of the concrete provider implementations for FileSystemImageProvider and SqlImageProvider so they use the new contract:
1 public class FileSystemImageProvider : IImageProvider
2 {
3 // Implementation of the provider code, only signature of the class changed
4 }
5
6
7 public class SqlSystemImageProvider : IImageProvider
8 {
9 // Implementation of the provider code, only signature of the class changed
10 }
The ImageService still almost the same, we only need to change LoadProvider's code so it creates an instance of the desired concrete implementation without using the ProvidersHelper class. Something like this may work perfectly:
1 public void LoadProvider()
2 {
3 _provider = Activator.CreateInstance(typeof(FileSystemImageProvider)) as IImageProvider;
4 }
Any conclusion?
As you can see, the approach it's quite similar for both methods and it's really simple to introduce it in most of actual software projects and architectures. It provides ease of installation, highly decoupled systems and modularity both in development and deployment.
There's no excuse to avoid this pattern, as far as it's possible and pragmatic to use it in the context of your architecture :)
Hope this helps anyone.

Thursday, November 30, 2006
Well, it seemed that Windows Vista didn't shipped with a full version of the Windows Mobile Device Center. It shipped with an standard RNDIS driver to make simple connections to mobile devices, but it's not able to sync with my Outlook 2007.
So after some web crawling, it ended up at a Windows Mobile Team's page where you can download Windows Mobile Device Center Beta 3 for Windows Vista. So I did it, and installed it.
I tried to sync my device but it didn't worked out. Frustration. I crawled again and found that there is an incompatibility between Windows Live One Care 1.5 Beta and Windows Mobile Device Center Beta 3, because One Care Firewall won't detect the needed applications and ports.
Hence, you have two options:
- Disable Live One Care Firewall each time you need to sync your device. ouuuch.
- Configure the needed ports and applications manually within the Live One Care Firewall:
- Ports:
- port990: open inbound TCP
- port999: open inbound TCP
- port5678: open inbound TCP
- port5679: open outbound UDP
- port5721: open inbound TCP
- port26675: open inbound TCP
- Applications
- C:\Windows\WindowsMobile\wmdc.exe
- C:\Windows\WindowsMobile\wmdHost.exe
- C:\Windows\WindowsMobile\wmdsyncman.dll
And there we go. It's working perfectly now :)
