Tuesday, July 14, 2009

Programming is like Chess

For a long time I have believed that software development is just like a Chess game, but apparently not many people have thought about it this way, just *bing* it and you'll see less than a page of results (Google is no better), of course this is about to change as I write this post and everybody sees the light... or not

anyway, let me elaborate on my analogy

The bad programmer
Arguably the average programmer, makes a move without thinking about the side effects, his capacity of analyzing problems is not all that great, there are so many side effects (breaking code, introducing bugs, security, etc) but this guy is not even aware of most of them, he basically relies on the debugger and if it runs on his machine then is good to go; when stuff inevitably breaks he just goes back and makes another move that seems to fix the problem, if you give this guy a large project it is likely that he'll make a stupid move that will just cause Checkmate on the project

The good
Analyzes different paths and choses the one he thinks is best, this player can play a good game, every once in a while his analysis is not that through and makes some mistakes but he can learn from that, this guy usually delivers good quality software with few bugs that he can go back and fix quickly enough to be acceptable

The best
This guy can make a whole bunch of moves all in his head, he's informed about all the latest techniques to defeat the opponent but he doesn't just rush and use them in a game, he tries them first on his own little projects and ends up using the ones that he proves to be useful, the ones that are shorter, quicker and give him the best return, he knows the techniques to use with the small projects and the ones to be used with large projects, and he knows they are very different, this guy knows what the opponent is thinking, he knows what the opponent will respond to every one of his moves so he usually chooses the best move... he knows the side effects; the "works on my machine" is not on this guy's vocabulary.

As you can see the the main two differences in my analogy are the capacity of analysis (selecting the move) and the awareness of the side effects (what happens when you make that move).
The opponent is your software project, the move is writing the code, the side effects are everything else that is affected by that.

When was the last time that you introduced a new bug fixing that other bug or writing some new functionality? or when *they* found bugs of your code right after it went to production? or when it worked on your machine but not on the server?

Every time you make a move, stop and think about the side effects, there are always side effects, if you can't think of them, there are tools that can help you think better, such as Unit Testing, the more you practice it, the better you'll get at it, I promise

Tuesday, June 30, 2009

Firefox taking a long time to start after upgrading to 3.5

Firefox 3.5 (code name Shirekoto) is out, get it while is hot!

After updating it and running it for the first time, I got this little window

It took me a while to even realize that that little guy was somewhere on my screen, I thought Firefox was just taking a long time to start after the update, then I clicked on the taskbar icon and that's when I saw the little window, I tried to re-size it but it didn't allow me to, all I could do was close the little (attempt of) window, then Firefox ran normal

thought I would blog about it in case this happens to more people

symptom: Firefox takes a long time to start after updating to 3.5
solution: click on the taskbar firefox icon and find the little window on your screen, close it, then Firefox will run normal

Wednesday, June 24, 2009

Are we done with XML yet? hello JINI

I have never been a fan of XML, I've hated it from "day one", the format is too inefficient, too bloated; I have had some ideas on things that can be done to reduce the size on xml data sets, such as having some kind of header definition embedded at the top of the file and other ideas, but the point of this post is not to talk those ideas, but rather my own proposal to start getting rid of xml.

One area where I find particularly painful to use XML is on configuration files and my proposal to fix this problem is to formalize a new format, which I call JINI for now. JINI is a subset of JSON similar in simplicity to the good old .ini files and it's used specifically for configuration purposes to replace all those app.config xml configuration files

Benefits
- Simple
- No brackets
- Simple
- Shorter
- Easier to read
- Simpler
- Everything that can be expressed in XML, can be expressed in JINI, but simpler

Too bad "jini" is kinda already taken (2 million results on Google and 714K on Bing say so)

I thought someone would have come up with this idea already, but a quick search gave me nothing, so I thought I would get the ball rolling

what do you think?

Monday, June 22, 2009

How to: Convert DIB to Bitmap

During the weekend a friend asked for some help on code to convert a DIB to a Bitmap in .NET, he had found some code in internet and it almost did everything he needed but the image was getting cut off along the sides, we figured the issue had something to do with getting the pointer to the bitmap, so we digged more and found some more code that then we had to make a couple fixes and changes to get it working. Since I was not able to find a full working solution to the problem I decided to write this post, I saw many people asking the same question in multiple forums so hopefully this will help

First, you’ll need to add System.Drawing.dll to the references of your project, then you’ll need to add the following uses clauses

//Name spaces needed
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

the next step is to declare the BITMAPINFOHEADER structure, this can be declared outside your class:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BITMAPINFOHEADER
{
public uint biSize;
public int biWidth;
public int biHeight;
public ushort biPlanes;
public ushort biBitCount;
public uint biCompression;
public uint biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public uint biClrUsed;
public uint biClrImportant;

public void Init()
{
biSize = (uint)Marshal.SizeOf(this);
}
}

Then you need to import a function from GdiPlus.dll
//GDI External method needed Place it within your class
[DllImport("GdiPlus.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int GdipCreateBitmapFromGdiDib(IntPtr pBIH,
IntPtr pPix, out IntPtr pBitmap);

Now we can get to the actual code to conver the DIB to Bitmap, note the use of a helper function GetPixelInfo, this was the culprit of our issues, and the one we had a hard time finding then getting to work, the function BitmapFromDIB that you’ll find all over the web doesn’t have this code and so it doesn’t work in many cases, in fact the function that you'll find all over the place has a parameter pPix but it doesn't specify how to get this value. This code needs to be declared inside your class

//THIS METHOD SAVES THE CONTENTS OF THE DIB POINTER INTO A BITMAP OBJECT
private static Bitmap BitmapFromDIB(IntPtr pDIB)
{
//get pointer to bitmap header info
IntPtr pPix = GetPixelInfo(pDIB);

//Call external GDI method
MethodInfo mi = typeof(Bitmap).GetMethod("FromGDIplus", BindingFlags.Static | BindingFlags.NonPublic);
if (mi == null)
return null;

// Initialize memory pointer where Bitmap will be saved
IntPtr pBmp = IntPtr.Zero;

//Call external methosd that saves bitmap into pointer
int status = GdipCreateBitmapFromGdiDib(pDIB, pPix, out pBmp);

//If success return bitmap, if failed return null
if ((status == 0) && (pBmp != IntPtr.Zero))
return (Bitmap)mi.Invoke(null, new object[] { pBmp });
else
return null
;
}

//THIS METHOD GETS THE POINTER TO THE BITMAP HEADER INFO
private static IntPtr GetPixelInfo(IntPtr bmpPtr)
{
BITMAPINFOHEADER bmi = (BITMAPINFOHEADER)Marshal.PtrToStructure(bmpPtr, typeof(BITMAPINFOHEADER));

if (bmi.biSizeImage == 0)
bmi.biSizeImage = (uint)(((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * bmi.biHeight);

int p = (int)bmi.biClrUsed;
if ((p == 0) && (bmi.biBitCount <= 8))
p = 1 << bmi.biBitCount;
p = (p * 4) + (int)bmi.biSize + (int)bmpPtr;
return (IntPtr)p;
}

finally, as a plus, what my friend actually needed was to convert from DIB to TIFF, so he wrote a function to do that, this function reuses the BitmapFromDIB function and allows you to set the image resolution

private void SavehDibToTiff(int hDIB, string fileName, int xRes, int yRes)
{
//Identify the memory pointer to the DIB Handler (hDIB)
IntPtr dibPtr = new IntPtr(hDIB);

//Save the contents of DIB pointer into bitmap object
Bitmap myBitmap = BitmapFromDIB(dibPtr);

//Set resolution if needed
if (xRes >0 && yRes>0)
myBitmap.SetResolution(xRes, yRes);

//Create an instance of the windows TIFF encoder
ImageCodecInfo ici = GetEncoderInfo("image/tiff");

//Define encoder parameters
EncoderParameters eps = new EncoderParameters(1); // only one parameter in this case (compression)

//Create an Encoder Value for TIFF compression Group 4
long ev = (long)EncoderValue.CompressionCCITT4;
eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, ev);

//Save file
myBitmap.Save(fileName, ici, eps);
}
//Helper to get Encoder from Windows for file type.
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}

and that is it, hoping this will help someone out there

Saturday, June 13, 2009

What are those colors on IE tabs?

colored tabs

I thought this was one of the best features in Internet Explorer 8, but not everyone gets the meaning of the colors on the tabs. The colors represent that the tabs are related, meaning that you followed a link from one page, IE opened another tab and assigned the same color as the previous tab, so that way the tabs that are derived from other tabs are now all grouped and it’s very easy to see this, very useful when you have multiple tabs open for different purposes. I just had to blog this because someone actually asked me what those colors were for, so I figured there’s more people who may have the same question.

Sunday, May 31, 2009

Silverlight how to: Add a user control to another user control

I'm starting to experiment with SilverLight and there's plenty of material out there, but some of the small details are really hard to find. The first application I'm working on requires a couple user controls, one embedded in the other and I spent a couple hours finding how to insert the user control into another control, then to the page, I thought it would be as easy as drag and drop but that didn't work, tried a few other things with no luck, turns out you have to add the namespace to the xaml, similar to the way you declare your controls in ASP.NET
The top xml of a user control (or the Page.xaml which is really just a user control) looks like this:

<UserControl x:Class="MyNameSpace.SomeUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="200" Height="300">

right after the last line with xmlns, you can type "xmlns:[prefix]=" (where [prefix] is the prefix you want to use in the xml to add your control, and make sure to add the = at the end); intellisense will do the rest, the first line of the drop down will contain the default namespace of your assembly, select that and you're good to go, it will look something like this:

<UserControl x:Class="MyNameSpace.SomeUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:prefix="clr-namespace:MyUserControl"
    Width="200" Height="300">

You can now start adding your control by typing <prefix: wherever you want to add your control and again intellisense will do the rest for you, you will be able to select any of the user controls that you have created previously under that namespace.
One last thing, if you will be referencing that user control from the code behind, you will need to name your control:

<prefix:MyUserControl Name="myControl" ></prefix:MyUserControl>

Doing so will give you strongly typed access to the instance of the control in your code behind, public members included

myControl.SomePublicMethod(someParameters);

Thursday, April 16, 2009

my solution to Eric Lippert's quiz

Eric posted a quiz a few days ago, it generated quite a number of responses, so I thought I would answer with the shortest possible C# answer (with my previous team we used to kinda compete on refactoring), so here it is (Justin and Paul, bring it on!):
The problem:
Write me a function that takes a non-null IEnumerable and returns a string with the following characteristics:

(1) If the sequence is empty then the resulting string is "{}".
(2) If the sequence is a single item "ABC" then the resulting string is "{ABC}".
(3) If the sequence is the two item sequence "ABC", "DEF" then the resulting string is "{ABC and DEF}".
(4) If the sequence has more than two items, say, "ABC", "DEF", "G", "H" then the resulting string is "{ABC, DEF, G and H}". (Note: no Oxford comma!)


My solution:

static string JoinStrings(IEnumerable<string> strings) {

int len = strings.Count();

return "{"+(

(len > 1) ?

strings.Take(len - 1)

.Aggregate((string head, string tail) => head+", "+tail)+

" and " +strings.Last()

: (len == 1) ?

strings.First()

: "")+

"}";

}

Thursday, April 02, 2009

public ASP.NET MVC { get; private set; }

For the 2 people who don't read many blogs (or twitter), but do read this one, yesterday it was announced that ASP.NET MVC 1.0 is open source baby! "Free like Speech." and there are no restrictions to the platform either, the license is MS-PL which provides broad rights to modify and redistribute the source code.

The first question that was raised was "can I submit patches?" and the answer is no, however nothing stops you from going and creating your own copy (forking) and start modifying it and redistributing it like this guy has already done.

You can get the source code here.

Did you know? Interface members are allowed to be private

This one comes as a surprise to most people, but it is possible to have a private implementation for an interface member, let's look at a very simple example, just for purposes of the ilustration.

public interface ITest {

void Test();

}

public class Test : ITest {

void ITest.Test() {

Console.WriteLine("test");

}

public void Test2() {

Console.WriteLine("test2");

}

}

class Program {

static void Main(string[] args) {

ITest t = new Test();

t.Test();

Test t2 = new Test();

//t2.Test(); //<<=== doesn't compile


If you don't believe it you can try it of course.

But why is this useful or how do you use this?

The technique allows you to ensure that the method is only visible to those who are using a variable of the interface type. All this does is to force the use of the member through an instance of the interface, meaning, for this example, if you want to get access to the .Test method, you can only do so through a variable of type ITest.

The only trick to make this work is to precede the member declaration with the Interface type as in:

void ITest.Test();

Not the most useful of tricks, but something to have on the bag of tricks, or maybe something to make you win a bet ;)

Friday, March 27, 2009

Do you want to view only the webpage content that was delivered securely? The simple guide

The post about the new dialog for secure/unsecure items in IE8 has had quite a few visits, so I thought I would make it much easier on the visitors to get to what they specifically need, I am guessing they are arriving here mainly to find out:
1 - What the heck does it mean.
2 - What they should do to see the full page.
3 - How can they get rid of the stupid message.
1 - What the heck does it mean?
They inverted the question from the previous dialog:
"This page contains both secure and nonsecure items.
Do you want to display the nonsecure items?"
So that more people will just click the default, and by doing so IE will not display the unsecure items on the page.

2 - I just want to see the entire page, what should I do?
Click NO

3 - How can I get rid of the stupid dialog once and for all?.
The short answer would be: Tools>internet options>security>custom level>display mixed content: Enable.
The long answer is on this other post: How to: Prevent the security dialog about unsecure items in IE

hope this helps! If I didn't answer what you were looking for, please let me know in the comments.

Friday, March 20, 2009

How to: Prevent the security dialog about unsecure items in IE

keywords: IE8, mixed, content, dialog, warning.

In my previous post about the new dialog in IE8 about mixed content, someone asked "How can I prevent this message from reappearing?", I thought it would be a good-to-have post and started writing this, but someone else already answered it (thanks Anonymous), in any case, here's what you need to do if you don't want to see that dialog:
tools>internet options>security>custom level>display mixed content: enable


Note that if the site you are visiting is NOT on the internet zone, you would have to make the changes to the appropiate zone:

here's how you tell which "zone" you are on, on the bottom right hand corner of the browser you should see something like this:


If you double click that, you can make changes to the other zones (Local Intranet, Trusted sites, restricted sites)



Just click the zone you want, and it will bring up the first dialog (from this post) where you can make the change.

This applies to IE8, IE7, IE6 (I don't know about older versions)

Do you want to view only the webpage content that was delivered securely?

keywords: IE8, usability, warning, error, dialog

Update: If you just care about making the dialog disappear go straight to comments or this post for more details, if you want the simple answers check the "simple guide". This post was originally intended for developers but it seems a lot of people are looking for an answer to this puzzle.

IE8 has been released and it's got a few really cool features as well as some really good protection mechanisms, all in all, a fairly good release.

But then I found this while navigating a secure page (Gmail)


Say what???

In what felt like I passed out I had to re-read the full dialog, then took me about 5 seconds to get what the dialog was telling me and about 10 to understand what would happen if I clicked NO.

I'm copying the contents of dialog text here just for SEO

This webpage contains content that will not be delivered using a secure HTTPS connection, which could compromise the security of the entire webpage.

Why did they change the previous dialog?:

This page contains both secure and nonsecure items.
Do you want to display the nonsecure items?



The new dialog seems very confusing to me, the extra text after the question just makes it even more confusing and for as long as I can remember we've had the same old dialog, which seemed fine.

Notice that even the answer is the opposite for the new dialog, maybe this is the reason it feels like asking a negative question.

I think the intent is for users to click the default yes, since 99.99% users don't really read any dialogs, and that will cause IE to not display the unsecure items on the page.