Sunday, August 27, 2006

the church of... Google?

We at The Church Of Google believe a convincing argument can be made stating that the search engine Google is the closest mankind has ever come to experiencing an actual Deity. It is the ultimate bridge between people and information.

 

Thou shalt have no other Search Engine before me, neither Yahoo nor Lycos, AltaVista nor Metacrawler. Thou shalt worship only me, and come to Google only for answers.

..way too much free time on their hands

what!? you are going to join?

Friday, August 25, 2006

The programmer's Bill of Rights

I'm all up for this:

I propose we adopt a Programmer's Bill of Rights, protecting the rights of programmers by preventing companies from denying them the fundamentals they need to be successful.

...is just weird that the link is 666...

finally {} is not a good place to commit your transactions

I just fixed some code (not written by me!) that went something like this:

transaction = connection.BeginTransaction();
try {
try
{
//***.... database operations here...
} finally {
transaction.Commit();
}
} catch {
transaction.RollBack();
}

First of all, there is a bug there, if an exception is ever raised, it will raise a new exception because it cannot rollback a transaction that was committed (the message will not be that clear, but that's what it means, the exception says something about unable to complete the operation due to the current state of the object), and you'll lose the original exception that you got


Second, it's just wrong, it defeats the purpose of using a transaction, is like you are saying


//*** delete some records


//*** update some records


//*** some db operation that caused some exception


//*** finally, commit what I had done so far


leaving your data in an unknown state because you commited all the operations up until it failed


hint: always use "using" for any DB related stuff (connections, commands, transactions, etc)

Tuesday, August 22, 2006

Hiding generics complexity

On my last post I showed you some wicked use of generics, Ayende says he can't read code like that and provided an alternative; I agree with him, it is very ugly code, but there is hope!

here's the equivalente code for the first section (note that I'm still using generics, even if it doesn't look like it), where we wanted to store a list of file names:

FilesList filesList = GetFilesList();
ListFiles(filesList);
Then we have the bidimensional generic, to store folder name and the files in it:
FoldersWithFiles foldersWithFiles = GetFoldersWithFiles();
foreach (FoldersWithFilesPair kv in foldersWithFiles) {
Console.WriteLine(string.Format(" Folder: [{0}]", kv.Key));
ListFiles((FilesList)kv.Value);
}

And finally where we store computer names, with the folders, with the files in it:

ComputerFiles computerFiles = GetComputerFiles();
foreach (ComputersWithFoldersPair kv in computerFiles) {
Console.WriteLine(string.Format("Computer: [{0}]", kv.Key));
foreach (FoldersWithFilesPair kv1 in kv.Value) {
Console.WriteLine(string.Format(" Folder: [{0}]", kv1.Key));
ListFiles((FilesList)kv1.Value);
}
}
And my last example would now look like this:
ComputerFiles computerFiles = new ComputerFiles();
instead of this:
Dictionary<string, Dictionary<string, List<string>>> ComputerFiles = 
new Dictionary<string, Dictionary<string, List<string>>>();

Now, if the code is equivalente and I'm still using generics, what did I do?


I am using aliased generics (yup, invented here too J) which give me friendly names, instead of the ugly multidimensional generics syntax

Here's the aliases declaration:
using System.Collections.Generic;
using FoldersWithFilesPair = KeyValuePair<string, List<string>>;
using ComputersWithFoldersPair = KeyValuePair<string, Dictionary<string, List<string>>>;

using FilesList = List<string>;
using FoldersWithFiles = Dictionary<string, List<string>>;
using ComputerFiles = Dictionary<string, Dictionary<string, List<string>>>;

The best of both worlds, you can use complex generic data structures and keep your code readable.


You put all the uglyness in a simple place, and you are able to use friendly names which look like normal classes, plus you get more extensibility because you could change the signature of the aliased generics without breaking the code.


On my next post I'll show you another technique to accomplish the same thing, and some gotchas, then I'll put the full source code in a zip file so you can download it.

Blogging since 1969

 some people have just been blogging for too long

(oh yeah, and I wanted to test the Live Writer image uploading capabilities...)

Monday, August 21, 2006

C# multidimensional generics

You can think of Generics as Arrays on steroids or Collections on steroids or a combination of both, they offer an extensible list of items with type safety; or as MSDN puts it:

Generics allow you to define type-safe data structures, without committing to actual data types.

One thing that I haven't seen much is how you can use multidimensional generics (yup, invented here J), let me explain what I mean

let's say we wanted to store a list of file names, we could do something like:




List<string> filesList = GetFilesList();
ListFiles(filesList);


now, we want a list of directories with the files in them, we could use a bidimensional generic type to keep the directory name on a dictionary key and the list of files on the dictionary value:


Dictionary<string, List<string>> foldersWithFiles = GetFoldersWithFiles();
foreach (KeyValuePair<string, List<string>> kv in foldersWithFiles) {
Console.WriteLine(string.Format(" Folder: [{0}]", kv.Key));
ListFiles(kv.Value);
}


finally, let's say we want a list of computers, with folders that contain files, we can use a multidimensional generic type that has the computer name on a dictionary key, and the folders with files on another dictionary stored as the key:




Dictionary<string, Dictionary<string, List<string>>> ComputerFiles = GetComputerFiles();
foreach (KeyValuePair<string, Dictionary<string, List<string>>> kv in ComputerFiles) {
Console.WriteLine(string.Format("Computer: [{0}]", kv.Key));
foreach (KeyValuePair<string, List<string>> kv1 in kv.Value) {
Console.WriteLine(string.Format(" Folder: [{0}]", kv1.Key));
ListFiles(kv1.Value);
}
}


For the sake of completeness here's the ListFiles function, just so you can see some cool use of generics combined with anonymous delegates:


static void ListFiles(List<string> filesList) {
filesList.ForEach(new Action<string>(delegate(string s) { Console.WriteLine(string.Format(" {0}", s)); }));
}


As you can see, with generics we can create some complex type-safe data structures, however, as always, some people will complain that multidimensional generics become very cryptic;

and you can see it if you did something like:



Dictionary<string, Dictionary<string, List<string>>> ComputerFiles = new Dictionary<string, Dictionary<string, List<string>>>();

in my next post I'll show you a couple techniques you can use to hide the generics complexity while keeping all of their benefits

Tuesday, August 15, 2006

RegisterChannel is obsolete, use RegisterChannel instead

I got this error:

Warning 6 'System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(System.Runtime.Remoting.Channels.IChannel)' is obsolete: 'Use System.Runtime.Remoting.ChannelServices.RegisterChannel(IChannel chnl, bool ensureSecurity) instead.'

It threw me off for a little while because System.Runtime.Remoting.ChannelServices.RegisterChannel doesnt' really exist

the problem there was that they just missed the .Channels part of the namespace, so it should've been:

"use 'System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(IChannel chnl, bool ensureSecurity) instead"

ok, that was the first part, now if this overload is obsolete, which one is the equivalent?

RegisterChannel(chnl, true)

or

RegisterChannel(chnl, false)

Reflector to the rescue, the equivalent is to use false as the second parameter, that's what the current function does right now when you call

RegisterChannel(chnl);

it calls:

ChannelServices.RegisterChannelInternal(chnl, false);

Monday, August 14, 2006

First bug in live write

This happens when you add multiple blogs accounts, on the last dialog if you uncheck the "switch to this blog now" (or something like that) the new blog won't appear in your list of blogs, so you are not able to switch to that

restarting the app refreshes the list

Hello world from live writer

This thing is pretty cool, it allows me to write to my multiple blogs just fine, check out their blog too

cool use of the coallesce ?? operator in C#

We just coded something like (please disregard the variable names, I'm just illustrating the point)

return myCollections.Services ?? (myCollections.Services = dbLayer.GetServices());

one-liner to do a bunch of stuff, and it's still clear what you are trying to do, if you know the ?? operator you can stop right here, if you don't let me explain a bit more

the ?? operator returns the left-hand operator if it is NOT NULL, else it returns the right operand

so this code is the equivalent of:

if (myCollections.Services == null)

  myCollections.Services = dbLayer.GetServices();

return myCollections.Services;

Wednesday, August 09, 2006

Notepad hidden features: How to use Notepad to create a (manual) log file

In case you missed it, here's how "Bush hid the facts"
To create a log file in Notepad:
1. Click Start, point to Programs, point to Accessories, and then click Notepad.
2. Type .LOG on the first line, and then press ENTER to move to the next line.
3. On the File menu, click Save As, type a descriptive name for your file in the File name box, and then click OK.
When you next open the file, note that the date and time have been appended to the end of the log, immediately preceding the place where new text can be added.
You can use this functionality to automatically add the current date and time to each log entry.

How to Use Notepad to Create a Log File

Pretty cool, everytime you open the file after that (in Notepad), it adds a timestamp
 and you can enter some text

get Delphi for free

seems like things are starting to get shape for Borland's Developer Tools Group, they are coming up with these "express" (free) and cheaper versions of Delphi, C# and C++
Turbo Delphi, Turbo Delphi for .NET, Turbo C++ and Turbo C# will be generally available in the third quarter of 2006. The Turbo Explorer editions of these products will be free. Pricing for the Turbo Professional editions will be under $500. Student academic pricing for the Turbo Professional editions will be under $100. For more information, visit www.turboexplorer.com.

August 8, 2006 - Turbos Press Release

We'll see what they can do against the Microsoft Express versions which have been out and free for a while, right now I don't see how they could compete but we'll see; if they run (and probably will) against the .NET Framework 1.1 that will discourage a lot of people

Monday, August 07, 2006

I'm natural hacker material J

Points For Style
Again, to be a hacker, you have to enter the hacker mindset. There are some things you can do when you're not at a computer that seem to help. They're not substitutes for hacking (nothing is) but many hackers do them, and feel that they connect in some basic way with the essence of hacking.
* Learn to write your native language well. Though it's a common stereotype that programmers can't write, a surprising number of hackers (including all the most accomplished ones I know of) are very able writers.
* Read science fiction. Go to science fiction conventions (a good way to meet hackers and proto-hackers).
* Train in a martial-arts form. The kind of mental discipline required for martial arts seems to be similar in important ways to what hackers do. The most popular forms among hackers are definitely Asian empty-hand arts such as Tae Kwon Do, various forms of Karate, Kung Fu, Aikido, or Ju Jitsu. Western fencing and Asian sword arts also have visible followings. In places where it's legal, pistol shooting has been rising in popularity since the late 1990s. The most hackerly martial arts are those which emphasize mental discipline, relaxed awareness, and control, rather than raw strength, athleticism, or physical toughness.
* Study an actual meditation discipline. The perennial favorite among hackers is Zen (importantly, it is possible to benefit from Zen without acquiring a religion or discarding one you already have). Other styles may work as well, but be careful to choose one that doesn't require you to believe crazy things.
* Develop an analytical ear for music. Learn to appreciate peculiar kinds of music. Learn to play some musical instrument well, or how to sing.
* Develop your appreciation of puns and wordplay.

How To Become A Hacker

Saturday, August 05, 2006

The problem of naming your blog after a technology

Specially at Microsoft, technology names change and some times they change often, I've seen quite a few blogs named after MS technologies that later change the name, some recent examples include Windows Vista and PowerShell

You can't know it all, so what to do?

You can't know it all. No matter how smart you are, no matter how comprehensive your education, no matter how wide ranging your experience, there is simply no way to acquire all the wisdom you need to make your business thrive.Donald Trump - Learning - Business - Knowledge

Learning Quotes


In the programming world we hear this more and more often, frameworks have thousands of classes, functions and features, even the people behind those frameworks don't know other parts of the framework, what makes you think you can know it all

It's key to be comfortable with your own ignorance. Understand that you can't know it all and stop trying to or pretending that you do. Understand that other people are ignorant too, and help educate them when you can rather than resenting their shortfall. On the same track, don't resent someone who's trying to teach you something either, swallow your pride and better yourself for it.

The Critical Path / eMail Newsletter / Issue 6.1



My approach to this issue is to learn the language features as good as I can, then on the features of the frameworks I make a distinction on technologies that I'm interested in learning right now and learn them, and as many others that might be useful at some point, but the point is to be aware that such features exist and what they do; that way when you actually need them you can find them a lot faster because you know there is something to do just that and you avoid reinventing the wheel in many cases

services like del.icio.us can help you with this problem, if you see something cool that you might be interested in the future you can save a link and tag it with something like "future" and you can build a list of things to learn or that you can posibly use some time later

You can't put everything in your brain, so use the existing tools to do some of that work for you

Is just like in soccer, is always good to win, but if you can't win is good to tie, if you can't tie is good to lose for as little difference as possible

Improve your tabbed browser experience

These extensions greatly improve the tabs behavior in Firefox/Flock

Ctrl Tab Preview
This is an extension that replaces the behavior of Ctrl+Tab. Instead of directly changing tab it works some thing like Alt+Tab on windows. It views preview of the tab and you can change directly to the tab you want to or just go through all tabs to see what you got in them. A pictures tells more then thousands words so look at the pictures or try it.


SessionSaver
SessionSaver restores your browser -exactly- as you left it, every startup, every time. Not even a crash will phase it. Windows, tabs, even things you were typing -- they're all saved. Use the menu to add + remove sessions; right, shift, or middle-clicking will delete. "Simple mode" for peace of mind, or "Expert mode" for advanced flexibility. Just Click. Install. Rad.

Perma Tabs
Adds the ability to turn tabs of your choice into permanent tabs ("permaTabs") that can't be closed, and stick around between sessions.

Multiple home pages in your browser

One of those things that not many people know, most modern browsers these days allow multiple home pages.

Firefox/Flock



Internet Explorer



Opera also allows you to do it, quite a bit more complicated, but can be done

Multiple home pages in Opera

In Firefox/Flock there is also an extension that allows you to cycle your home pages:

Home Page Cycler
Load a different home page each time Firefox starts.

Tuesday, August 01, 2006

Don't click it, really

quite a different user interface, what do you think?

Don't click it

Sunday, July 30, 2006

using the right tool for each job, which web browser do you use?

I use 5 different browsers approximately as:

70% - Flock - This is like a Firefox on steroids (actually based on the Firefox engine), allows me to blog from it, integrates with flickr, etc, Any firefox extension that I use, I load on this browser

10% - Firefox - I use this browser pretty much clean of all extensions, when I want to load a site and leave it running on the background I use this browser.

10% - Internet Explorer 7 - Beta 3 at this point, so far I like it a lot, but there are a bunch of sites that just refuse to work with it, once it becomes a release version I'm sure I'll use it more

5% - Internet Explorer 6 - On the other hand, there are some sites that only look good or only allow Internet Explorer 6, I use this browser for IE specific sites and/or sites that I trust (e.g. intranet)

5% - Opera - Since out of my list of browsers, this is the least used, this kinda gives me more "protection" when I'm visiting sites that I don't trust that much (e.g. sites about hacking)

Friday, July 28, 2006

new class for creating SQL connection strings in .NET 2.0

I just found about this little gem, I've seen all kinds of wicked code to create a sql connection string, anything from storing the whole connection string, to concatenating the string, to using a StringBuilder, etc. This class allows you to do all of the above but easier
SqlConnectionStringBuilder Class Note: This class is new in the .NET Framework version 2.0.Provides a simple way to create and manage the contents of connection strings used by the SqlConnection class

SqlConnectionStringBuilder Class (System.Data.SqlClient)

once you create an instance of that class, you can read/write to the individual items of the connection through properties or through the indexer as:

//you could pass the connection string in the constructor too

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

//using the indexer

builder["DataSource"] = "someDataSource";

//or using the property

builder.DataSource = "someDataSource";

this would be useful in a number of cases, for example if you had two connection strings that were different only by the server name

technorati tags:, ,

Thursday, July 27, 2006

Google help

With so many google products, it was about time to have a central place to look, first for all the available products, second, for help on how to use them
Those of us in user support had a pet peeve: there was no single place that held all of Google's help information at your fingertips. So we decided to build one -- and now you can visit Google Help to find tips, tricks, and troubleshooting solutions for just about every Google product and service. We don't want you to have to work hard to find anything, so we also added an A-Z guide in case you do know exactly what you're looking for.

Official Google Blog: A roadmap for Google help

technorati tags:

How to capture a PowerShell terminal session

Just found about this cmd-let that captures all the input/output in Powershell

to start it simply type:

Start-Transcript

it will tell you where the transcript is being stored, by default it creates a text file on your "c:\documents and settings\user\..." folder, but you can specify where you want the transcript to be stored just passing a file name after the cmd-let, you can also pass -append so that if the file exists, it keeps adding to it

To stop it:

Stop-Transcript

This is kinda the equivalent to the unix script command

technorati tags:

Free MSDN library from now on

For the first time, we're making the MSDN Library freely available for download from Microsoft Downloads. Previously, the Library was only available for download to MSDN subscribers. The current download is the May 2006 Edition and future editions will also be available when we release them.

Rob Caron : Free Download: MSDN Library May 2006 Edition



now this is great news!

Tuesday, July 25, 2006

Crazy windows bug

Captured in video for all you windows-haters viewing pleasure, it has sound
CRAZY COMPUTER BUG

YouTube - CRAZY COMPUTER BUG

Ruby for Visual Studio 2005

Found this today at TSS.net, Ruby in Visual Studio, for those of you interested in alternative languages
Ruby in Steel for Visual Studio 2005Posted by: Regina Lynch on July 25, 2006SapphireSteel Software will be releasing Ruby in Steel, a Ruby add-in allowing developers to take advantage of the Visual Studio IDE. The product will include debugging, Intellisense, code completion, code snippets and support for Rails.With the 1.0 release, both a free personal version and a developer version will be available. The developer version will include more advanced functionality, such as a fast debugger. SapphireSteel is planning to release several beta versions prior to release in order to implement further VS features and fix reported bugs.Ruby in Steel version 0.7 is currently available for download. It includes a Rails New Project Wizard, import capabilities, integrated SQL Server development, automated database setup and syntax error checking.

Ruby in Steel for Visual Studio 2005

check it out

Ruby In Steel

Saturday, July 22, 2006

10 years ago, today

It was July 22, 1996, back in my hometown in Mexico when I joined the company that I work for today, for most people to hear that someone has been working this long for the same company is quite shocking, for a few others it would be normal; for me it has been a great experience, I've grown a lot, I've had opportunity to meet a lot of people in many different cities.
10 years... that's a long time, it's the difference between being 19 or 29 years, I hope I have been able to help some people through my work.

Fortunately I won't have to bring a pound of chocolate per every year at the company or anything like that

Thursday, July 20, 2006

Windows Shortcut keys

I found this short useful well formatted list of Windows shortcut keys, so you can impress your friends "how did you do that?"

These shortcut keys work fine in Remote Desktop

Windows Shortcut Keys

Wednesday, July 19, 2006

PowerShell:Get a list of paths from the environment variable PATH

First of all, to get access to a variable from the environment you run:

$env:[variableName]

so, to get the PATH you do:

$env:path

on my machine, I get something like this:

PS C:\> $env:path
C:\oracle\product\10.1.0\Db_1\bin;C:\oracle\product\10.1.0\Db_1\jre\1.4.2\bin\c
lient;C:\oracle\product\10.1.0\Db_1\jre\1.4.2\bin;C:\Oracle\product\10.1.0\Clie
nt_1\bin;C:\Oracle\product\10.1.0\Client_1\jre\1.4.2\bin\client;C:\Oracle\produ
ct\10.1.0\Client_1\jre\1.4.2\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\Syst
em32\Wbem;C:\Program Files\Microsoft SQL Server\80\Tools\BINN;c:\Program Files\
Microsoft SQL Server\90\Tools\binn\;C:\Program Files\QuickTime\QTSystem\;C:\Pro
gram Files\Support Tools\;C:\Program Files\Windows PowerShell\v1.0\
PS C:\>

that's kinda hard to read, so you can use this method instead:

$env:path.Split(';')

PS C:\> $env:path.Split(';')
C:\oracle\product\10.1.0\Db_1\bin
C:\oracle\product\10.1.0\Db_1\jre\1.4.2\bin\client
C:\oracle\product\10.1.0\Db_1\jre\1.4.2\bin
C:\Oracle\product\10.1.0\Client_1\bin
C:\Oracle\product\10.1.0\Client_1\jre\1.4.2\bin\client
C:\Oracle\product\10.1.0\Client_1\jre\1.4.2\bin
C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem
C:\Program Files\Microsoft SQL Server\80\Tools\BINN
c:\Program Files\Microsoft SQL Server\90\Tools\binn\
C:\Program Files\QuickTime\QTSystem\
C:\Program Files\Support Tools\
C:\Program Files\Windows PowerShell\v1.0\
PS C:\>

ah... much better

what? you need the list on a file?

$env:path.Split(';') > list.txt

technorati tags:,

Technical terms in your language

I found this document: Microsoft Terminology Translations, via Edgar

the document contains almos 15,000 terms in 47 different languages, so if you speak another language, chances are you'll find it there

Tuesday, July 18, 2006

quickly find out which version of the .NET framework is installed on a system

This is something I have answered several times to many people, anything from production personnel to network administrators

is quite easy (the yucky using the mouse way)

You go to the control panel, Add or Remove Programs, wait forever for that to populate the list, then go find "Microsoft .NET Framework X.X"

if you want to do it quicker than that, you can use this method instead:

open a folder to:

c:\WINDOWS\Microsoft.NET\Framework\

or whatever the equivalent on your machine is, like

c:\WINNT\Microsoft.NET\Framework\

first of all, if the folder c:\windows\Microsoft.NET doesn't exist, then you don't have any .NET framework version installed

Then, if you do get to that folder, you should see some folders like

v1.0.3705

v1.1.4322

v2.0.50727

That's the version of the .NET framework installed (the first two digits matter the most)

It's also important to note that just because the folders exist there it doesn't mean that version is installed, to make sure you would actually have to go inside the folder and see that it has a ton of files (100+) and about 6-10 folders

for ~95%+ of the cases though, I just type c:\WINDOWS\Microsoft.NET\Framework\v at the "run" window and see what shows up and that works just fine

technorati tags:,

Microsoft acquires sysinternals

yup, the company that created filemon, regmon, tcpview, autoruns and so many other really cool tools is now part of Microsoft
I’m very pleased to announce that Microsoft has acquired Winternals Software and Sysinternals. Bryce Cogswell and I founded both Winternals and Sysinternals (originally NTInternals) back in 1996 with the goal of developing advanced technologies for Windows. We’ve had an incredible amount of fun over the last ten years working on a wide range of diverse products such as Winternals Administrator’s Pak, Protection Manager, Defrag Manager, and Recovery Manager, and the dozens of Sysinternals tools, including Filemon, Regmon and Process Explorer, that millions of people use every day for systems troubleshooting and management. There’s nothing more satisfying for me than to see our ideas and their implementation have a positive impact.

Mark's Sysinternals Blog: On My Way to Microsoft!

technorati tags:

Blogged with Flock

Monday, July 17, 2006

PowerShell support for old command line behavior

While playing with PowerShell I noticed that it has pretty good support for the behavior found in "old" CMD and/or "DOS", all the function keys work just as expected

Now, in case you don't know how to use the function keys in "DOS" here are some pointers:

F1 - will repeat the last command one character at a time, so if your last command was "dir", you will get "d", "i", "r" as you press F1 multiple times

F2 - "Copy up to char" function (of the last entered command): Not used much, it allows you to copy up to the character you enter after pressing F2, e.g.

If you previously entered: dir "program files"

on the next line you could enter: dir [F2]m

and it would complete it as: dir "progra

F3 - repeats the last command

F4 - "delete up to", I can't really remember how to use this one, but is rarely used I guess

F5 - iterate backwards through the list of previously entered commands (same as using the up arrow key)

F6 - ^Z or text file terminator: I can't see how to use this in PS, but if you were entering a text using "copy con [filename]" you can get out of it and save the file by pressing F6, which by the way, PS doesn't have support for "copy con" but supposedly this guy wrote something equivalent to it:

http://tfl09.blogspot.com/2005/10/monad-and-command-console.html

F7 - Provides a list of the previously entered commands and you can select one using the arrow keys

F8 - Iterates in a loop backwards (when it gets to the first one it goes the last one) through the previously entered commands

F9 - "Enter command number": allows you to enter the command number you want to execute, to find out the command numbers you would have to use F7 first

technorati tags:, , ,

Blogged with Flock

Sunday, July 16, 2006

(PS) how to get back "home"

I have a story of being a keyboard guy and a "command line guy", recently I have been interested in PowerShell; thanks to the secret geek I was encouraged to download it and try a few things, so far I'm loving it!, it's awesome... of course this is definitely not for everyone, specially not for programmers =o(, at least the great mayority of the ones I know don't really like command line stuff, anyway (is not like you are required to be an expert on it, PowerShell is oriented at System Administrators, I just happen to prefer command line when working at a computer, is just so much faster to accomplish things).

I was reading on the secret geek blog about one of the cmd-lets:"Get-PSDrive":

Once Upon A PowerShell i went looking for a cmdLet to display a list of all the current drives.I found one, 'Get-PSDrive' which does exactly that... but i was gobsmacked at what else it revealed!'Power shell drives' are not just your boring old 'C:' etc -- they can be all sorts of hierarchical structures, such a registry keys, environment variables, functions(!) and more.

Babysteps in PowerShell part deux: Variables! Real Proper Variables!

on mi machine it displays something like:

PS C:\> get-psdrive

Name       Provider      Root
----       --------      ----
A          FileSystem    A:\
Alias      Alias
C          FileSystem    C:\
cert       Certificate   \
D          FileSystem    D:\
E          FileSystem    E:\
Env        Environment
F          FileSystem    F:\
Function   Function
HKCU       Registry      HKEY_CURRENT_USER
HKLM       Registry      HKEY_LOCAL_MACHINE
Variable   Variable


PS C:\>

notice those Function, HKCU, HKLM and Variable at the end...

you can do a "cd Variable:" then do a "ls" or "dir" and it will list the variables declared, you can do "cd Alias:", then "dir" will list the aliases in the system (alias for the different cmd-lets")


anyway, I was playing with those and for a few seconds I was stuck when I did "cd Alias:", after finding out what was there, I wanted to go back, so I immediatly did "cd ..", didn't work, "cd \", nop... "cd /" nothing... panic!

quite simple actually, we just need "c:" or "cd c:"

(uff, that was close)... and now I have a new category to blog about

technorati tags:,

Thursday, July 13, 2006

Time to update .NET 2.0

This Information Disclosure vulnerability could allow an attacker to bypass ASP.Net security and gain unauthorized access to objects in the Application folders explicitly by name. Note that this vulnerability would not allow an attacker to execute code or to elevate their user rights directly, but it could be used to produce useful information that could be used to try to further compromise the affected system.

Microsoft Security Bulletin MS06-033: Vulnerability in ASP.NET Could Allow Information Disclosure (917283)

technorati tags:,

Wednesday, July 12, 2006

Tuesday, July 11, 2006

Singleton Pattern the way you should NOT do it

found this code today at c-sharp corner
public static SingleTon GetObject(){
if(instance == null)
instance = new SingleTon();
++m_nNofReference;
return instance;
}

Singleton Pattern

don't use it, it is not thread safe, you can read this instead if you want to learn about the singleton pattern

technorati tags:, ,

"googling" officially a verb now

"This week googling officially became a verb. The 11th edition of the Merriam-Webster Collegiate Dictionary now includes “googling” (lower case g). Actually the Oxford English Dictionary (OED) beat them to the punch a month ago by listing Google (upper case g) in their authoritative lexicon of the English language. It’s about time. People have been using Google as a verb for years, despite protestations by the company (many of which I authored myself) about the genericization of the trademarked name."

check it out

technorati tags:

Thursday, July 06, 2006

Bush hid the facts?

1.) Open an empty notepad file.
2.) Type "Bush hid the facts" (without the quotes).
3.) Save it as whatever you want.
4.) Close it, and re-open it.

...

now for the spoiler, try the same thing with

"this app may break"

or

"aaaa aaa aaa aaaaa"

technorati tags:,

Monday, July 03, 2006

.NET Framework 3.0 structure

in case this is still clear as mud, this picture should help

technorati tags:,

Tuesday, June 27, 2006

what should I hide?

I'm going through Code Complete 2 and got to this key point on chapter 5 about hiding information

"Get into the habit of asking "What should I hide?" You'll be surprised at how many difficult design issues dissolve before your eyes."

I think it should be quite the opposite, you should be in the habit of hiding everything and asking your self "what should I show?"; in C# if you omit the access modifier it defaults to private, and that's there for a good reason

You have to think in terms of what would someone else do, if they were trying to mess up with your code or get that precious information that your project is accessing

Of course not all projects are that critical that you should worry about securing every single aspect of the application, but you should get into the habit of hiding as much as possible and only making visible what you actually need, that way you'll be programming in a more secure way by default without even thinking about it

Monday, June 26, 2006

share keyboard and mouse accross computers (software driven)

This little tool allows you to share your keyboard and mouse accross multiple computers, even with different Operating Systems loaded, that's pretty dang cool

the only thing is that the configuration part of it is really buggy and makes the program die after it gives you the error message, basically you have to use the default options or it will crash

but after you get it working it does just what is supposed to without getting in the way, you don't have to switch from your laptop to your regular pc keyboard and back...

basically what you have to do is
- install the server in the machine where the keyboard and mouse is hooked phisically and
- install the client on the machines where you want to use the same keyboard
- then you start the app on the server,
- chose the "share this computer's keyboard and mouse",
- click the configure button,
- add the "screens" (machines), in that screen you can specify if there are some corners where you don't want the mouse to go over to the other machine, just make sure you specify a size greater than zero, or it won't work
-once you add your screens (normally 2), you go to the links

where you specify something like:
0 to 100% of the "right" of "main pc" goes to 0 to 100% of "secondary"

basically saying the right part of the monitor on "main pc" goes to the other pc; you have to specify the other way too

0 to 100% of the "left" of "secondary" goes to 0 to 100% of "main pc"

click start (in both computers) and you're good to go, if you need to change the config, close the program (in both sides) open it again, and go in the configuration button (in the server only)

I'm loving it =oP

Tuesday, June 20, 2006

.9 = 1

this post has generated so many comments and is so interesting (if you're not that good at math) you have to check it out

the point is simple:

.9 (repeating) = 1

not just close to 1... it is 1, if you don't believe it go check it out

technorati tags:,

Saturday, June 17, 2006

VS2005 Set Multiple Startup projects

To set multiple startup projects
1. In Solution Explorer, select the solution.
2. On the Project menu, click Properties. The Solution Property Pages Dialog Box opens.
3. Expand the Common Properties node, and click Startup Project.
4. Click Multiple Startup Projects and set the project actions.

How to: Set Multiple Startup Projects

This is more of a note for my self, but I'm sure a lot of people doesn't know about this feature, supposedly even the debugger attaches to the multiple projects, that's really useful when developing multi layered projects

technorati tags:, ,

Visual Studio Environment Animation Speed

this is a little trick I hadn't heard of, some items in the Visual Studio IDE have animation, e.g. when you open/close the properties, solution explorer, etc windows, there is some animation to make the windows appear/dissapear, sure is visually nice, but if you're like me, you don't want little whistles taking up your computer resources, I've seen those animation get quite slow specially when I have my machine loaded with a bunch of other stuff

there is a way to speed up those animations or even disable them completly

in the menu Tools, Options, Environment, General

bump "animation speed" all the way up, or uncheck the "animate environment tools" checkbox to disable this feature

this applies to both VS2003 and VS2005

Wednesday, June 14, 2006

blogging from flock

this is just a test from the flock browser, it has built in blogging capabilities and some other goodies, is based on Firefox, so check it out

Friday, June 09, 2006

World Cup live scores and schedules from google

Yesterday Edgar posted about a little program written by Microsoft to keep track of scores and stuff on the World Cup, and I just noticed that google has created something similar, but right into their web page

nice!

MSDN VS2005 & 2.0 framework Wiki

this is nice, Visual Studio 2005 and the .NET framework 2.0 documentation now on a wiki where everyone can collaborate

good job MS

Thursday, June 08, 2006

browser sync for Firefox

"Google Browser Sync for Firefox is an extension that continuously synchronizes your browser settings – including bookmarks, history, persistent cookies, and saved passwords – across your computers. It also allows you to restore open tabs and windows across different machines and browser sessions."

I don't know that I could use this, but probably some people would find it useful, I prefer to use delicious for that kind of thing, but anyway...

notice how it is only for Firefox... evil google!

Wednesday, May 31, 2006

Visual Studio 2005 Team Edition for Database Professionals

that's a heck of a name but oh well, you should be used to it by now; the point is, this looks very promising

The new Visual Studio Database Project allows you to import your database schema and place it under source control. When the time comes to deploy schema changes the new project system allows you to quickly build update scripts or packages and then provides a mechanism to deploy them to the database of our choice

Rename Refactoring allows you to easily rename any object in your database and be assured that all references to that object will be renamed to correspond to the change

DataCompare allows you to quickly compare two databases and script updates to bring the data in these databases into sync

and a lot more, check it out

hint: the page looks better in IE (than it does in FireFox) but don't let that discourage you

(not) managing developers

if you are managing developers or are thinking into moving in such position, be it software manager or assistant software manager, or something related to that (like managing overseas developers), this is definetely a must read

"The catch-22 of software management is that the ones who want it most are usually the worst at it. Some people, for worse or for worst, want to be managers because it gives them power over their peers. There's nothing good that can come of this arrangement: you should never give power to someone who craves it, for reasons that I hope are obvious."

"Unfortunately, many tech companies do exactly that, because they don't know any better."

I couldn't agree more, I guess developers can benefit from this as well, perhaps pass it on. you can find the article here

I'm back

not that I ever wrote on my blog that I was leaving on vacation, but anyway... I had a great time in Mexico, specifically in Juarez, Chihuahua and Cuauhtemoc (Chihuahua) with most of my family, unfortunately I missed some friends, which sucks because I don't get to go back very often...

Juarez is a great city to visit, there are tons of things to do there and the food is really good

I'm still catching up on reading blogs and stuff, I've found some good posts... back to reality

Monday, May 22, 2006

Free Intellisense for SQL Query Analyzer

for those of you who can't type fast intellisense lovers

couple this with my SQL Connection manager and you're good to go (I know, lame name)




  • Code completion for fast, accurate script building
  • Discoverability in SQL Server query creation
  • Keyword formatting, code snippet integration other extended features
  • FREE until 1st September 2006
  • No time-bombs, no restrictions
go get it while is fresh

Friday, May 19, 2006

simple elegant way to read ini files (Delphi)

I still see people do weird things to load settings from an .ini file; I always use this method

uses
IniFiles;
...

with TIniFile.Create(Application.ExeName) do
try
//load the settings here
finally
Free
end


nice, short, clean and simple

my thing is whenever I find something simpler or nicer than the way I do things, I change to that new way and stick to that, I think that's a simple principle to keep on becoming better developer

Thursday, May 18, 2006

Atlas Demo

in case you haven't seen it, check it out, very cool stuff

Tuesday, May 16, 2006

obfuscating the QueryString (just don't)

I just read this post by Peter A Bromberg, where he suggests that you can obfuscate the Query string to pass sensitive data around by "performing ASCII-to-HEX scrambling"; the guy usually has good ideas, but this one, please just don't use it, security through obscurity is not security

Friday, May 12, 2006

agile lunch?

I just read a post by Brendan Tompkins titled Agile HR; at work, we (the group of developers on our division) usually try to go out for lunch on Thursdays and yesterday we were going in two different cars and one guy said "remember that we have to go in pairs" (to get some discount because they had some coupon) to which I immediately replied "so this is going to be Agile lunch?"

then we started talking about agile practices and what we liked and didn't like, I won't post that here because I would probably get flamed, but anyway...
we're such geeks... do you guys do agile lunch?

Saturday, April 29, 2006

Assign permissions early

Last week I decided to restrict the access to one of the drives on my main pc, an 80GB drive with quite a bit of files in it, I took so many hours that I had to go to sleep before it was done

it reminded me that we should always assign permissions as early as possible, in the case of disk drives the bigger and more files you have on them, the longer it will take to complete the operation because it has to adjust permissions to every single file on the drive

the same concept applies when developing, but the problem in this case is that YOU (not an automated tool) will have to adjust the security, this may require a change on the architecture, which then introduces bugs, whichs costs time and resources... it can get quite ugly

assign permissions early wherever it applies, it will save you a lot of resources on the future

Monday, April 24, 2006

manage your SQL connections in one place

where I work at I use about 10 different SQL servers, is hard to keep up with the server names, catalogs, user names and passwords required for each one

wouldn't be nice if I had a central place to access all of them without having to remember all the names/catalogs/user names/passwords, but most importantly, without having to type the same stuff over and over to open my connections in Query Analizer?

even if you use SSPI to access your servers, you'd still have to type the server name and select the database you want to access

that's why I wrote this little utility program, you enter your SQL servers along with the user names, passwords and databases that you want to access and it sits quietly on your tray, where you can access them quickly

you can configure it to open the connections on an existing Query Analizer window, or to open a new one each time you open a connection

when configuring a new connection you can configure which file you want to load, e.g. if you regularly run some queries against certain database, this option would help you

now, if you're worried about security, I added a password to keep all this information encrypted using industry standards

this is a freeware application, it gets the job done for me, suggestions are welcome but I don't guarantee anything

Wednesday, April 19, 2006

bare minimum required comments for your projects

commenting is one of the things that programmers/developers really suck at

but please, do your self a favor

at the VERY LEAST, put comments at the top of the main source file; for example whenever I start a new project I always put something like:

Program: Program Name
Written by: Eber Irigoyen
on: 04/19/2006
Uses (third party components):
- Indy 9.0.14
- XceedZip 4.5.77.0
- MDAC 2.7
Compiled with: Delphi 7

Description:
- blablabla
- more bla
- etc...

include any history updates here...

is just a few lines and it tells me quite a lot, how many times have you spent hours just because you don't know what version of the X components some co-worker used?

adding these headers will take you only a minute or two, and it can save countless hours in the future

the next thing is whenever you make changes to your project, at least include a description at the top of the main file, along with the version number, your name and date when the update was done

simple things like this are part of being a better developer

note: Updated the article to clarify some points just like Ayende mentions in the comments, another thing is that you should include the 3rd party components in the source repository;
the bare minimum comments in the source and the components in the source repository are real life savers!

Friday, April 07, 2006

how to use google as a dictionary/encyclopedia

in this world of acronyms and new terms everyday we can't keep up with all those things, that's where google comes to the rescue

at the search box just type
define:your term here

here are some samples and their results:

define:google
Google, a popular search engine, is a tool for finding resources on the World Wide Web. Google scans web pages to find instances of the keywords you have entered in the search box.

define:Microsoft Corporation
An incredibly successful supplier of computer software founded in 1975 by Bill Gates and his partner Paul Allen. Microsoft has grown to become the world leader in the software industry by supplying software to the world’s largest computer base (IBM-compatibles). A large portion of Microsoft’s success is due to its popular Windows operating environment.

define:Test Driven Development
Testing methodology associated with Agile Programming in which every chunk of code is covered by unit tests, which must all pass all the time, in an effort to eliminate unit-level and regression bugs during development. Practitioners of TDD write a lot of tests, ie an equal number of lines of test code to the size of the production code.

as you can see you can enter more than a single word to find the definition

now, it gets interesting, you can also enter things like file formats, ZIP, PDF, EXE and get a definition for those as well

define:pdf
Portable Document Format. An electronic document that must be read with the Adobe Acrobat computer program.

define:js
An external JavaScript file. One of the methods of implementing JavaScript on to a page is to write an independent file containing all methods and variables and store it as a .js file. This file is then imported into an HTML or other type of web page as and when required.

how cool is that!

you can also use it as an encyclopedia

define:Salt Lake City
# Salt Lake City is the state capital and most populous city in the U.S. state of Utah. Its population as of the 2000 Census was 181,743. The Salt Lake City-Ogden metropolitan area, defined as Salt Lake, Davis, and Weber counties, had a population of 1,333,914 as of 2000.

define:George Bush
# Bush: 43rd President of the United States; son of George Herbert Walker Bush (born in 1946)
# Bush: vice president under Reagan and 41st President of the United States (born in 1924)

nice!, you can also use it to find acronyms (HTML, WEB, CSS, etc), jeez, how easy is for kids to do homework these days

you might not always get the definition on the first result, but I've seen good results usually in the top 3 definitions

you also get a list of related phrases which may give you a more detailed result on whatever it is you are looking for

Thursday, April 06, 2006

how to get database connection using a Delphi personal version?

This question comes up very often in the Delphi forums
the bad news is that the personal versions of Delphi don't come bundled with database components, you have to use a third party solution, the good news is that there are a few free ones, here's one of them

http://www.deer-soft.com/

and here's a tutotial from delphi.about about working around this limitation using text files, typed files, etc, in a few cases, these methods might be enough for your application

Creating flat (non-relational) databases with no (Delphi) database components

loading another copy of an assembly on Reflector might cause little headaches

First of all, if you haven't used Reflector, go download it now and start looking around in the BCL assemblies to see how things are really done behind the scenes, it can decompile code to IL, C#, VB.NET, Delphi, Chrome and MC++, I can't really say much about the quality of the Delphi and Chrome versions of the code it generates, but the C# is pretty good

anyway...
one thing to be aware when using reflector is, if you have an assembly loaded, and you try to load a different copy of the assembly in a different directory, it won't load it, it will keep the previous assembly loaded, and if you were loading it to see if there was a mismatch you'll think they're equal

what you have to do is just to right click on the assembly you're trying to reload, select close, then open the other copy and you're good to go
Vendor's voices on Delphi's future

check out what the vendors have to say about the future of Delphi, a lot more optimistic than I expected in the sense that they will support their products throughout whatever Delphi versions come out, which is good for the Delphi community

Wednesday, April 05, 2006

Windows Live Mail rocks
full blown (AJAX, web 2.0 or whatever you want to call it) email client, very, very nice

you can have email views like the ones in outlook 2003, you can do multiple selection with the mouse, drag and drop, it has spelling built in... definitely worth it giving it a try
To use stored procedures or not to use stored procedures

I thought this battle was settled down, and we had all agreed that stored procedures (from now on called SPs) are (for the most part) the way to go when accessing your SQL data

turns out Ayende is not quite convinced yet, in fact it seems he prefers to use no stored procedures at all, I told him SPs can give you scalability, flexibility, security, etctirity, and here's his response

"I completely disagree with this, if you didn't catch on so far. Here is my refutal:

Scalability:
There is no performance advantages to using SP over Parameterized SQL.
Scaling the database is much harder than scaling an application.
Note: I implemented a caching web service once that simply cache data for certain period of time, saving quite a bit from the poor database. Deploy a bunch of those, and you're seriously reduced the amount of work the database has to do.
Flexibility:
Stored Procedures are... Well, procedures. This means that you've all the advantages and disadvantages of procedural programming. On general, I wouldn't call it very flexible. Changing the procedure's internal can be done without breaking clients is possible within a certain set of changes, but major stuff is hard.
A search procedure should be flexible, you should be able to search by any combination of parameters, how easy it is to write this procedure?
Security:
Not applicable in situations where you don't give users direct access to the database, in my opinion. There are things to be said about defense in depth, but I don't think that they should be curried to the point where you are forced to give up significant advantages while keeping the security of the system (using views / triggers instead of procedures, for instance, can result in a situation just as safe, and far easier for the programmers to work with effectively)."


let's see

"Scalability:
There is no performance advantages to using SP over Parameterized SQL. "


...you probably posted that in the incorrect section, Scalability and performance are different things

"Scaling the database is much harder than scaling an application. "
that's just another reason to separate the data rules (SPs) from your application

"Note: I implemented a caching web service once that simply cache data for certain period of time, saving quite a bit from the poor database. Deploy a bunch of those, and you're seriously reduced the amount of work the database has to do. "
you can still cache the result of the stored procedures, I don't see how that's an advantage of not-using-stored-procedures

"Flexibility:
Stored Procedures are... Well, procedures. This means that you've all the advantages and disadvantages of procedural programming. On general, I wouldn't call it very flexible. Changing the procedure's internal can be done without breaking clients is possible within a certain set of changes, but major stuff is hard. "

even if they are just a few, I still didn't have to recompile (and potentially distribute the application) just to make those little changes

"A search procedure should be flexible, you should be able to search by any combination of parameters, how easy it is to write this procedure? "
just as easy as it is to write a query on the app, besides that, I can make important changes to the stored procedures, perhaps look in other tables (history, cache, etc), take other parameters to use the same SP in another application, etc; again, without having to recompile my app

"Security:
Not applicable in situations where you don't give users direct access to the database, in my opinion. There are things to be said about defense in depth, but I don't think that they should be curried to the point where you are forced to give up significant advantages while keeping the security of the system (using views / triggers instead of procedures, for instance, can result in a situation just as safe, and far easier for the programmers to work with effectively). "

secure programming is all about good practices, the stupid SQL injection is because people just do

"select * from users where userName = "+UserID

if they would've used a stored procedure, that would've been ok, the same thing would've been accomplished by using a parameterized query as you point out

but is much more than that, security is not only who can get access to your data, is who can mess up with your data, and changes to that are far easier accomplished using SPs; is the exact same concept you use when you break up your code in files and classes, you give each class a responsability (I hope), is the same thing with the database, you give the database it's responsability and let your application do it's responsability. it's about using the right tool to get the job done

Tuesday, April 04, 2006

01:02:03 04/05/06
010203040506

as a way of *celebration* for this peculiar event I created a big clock, a version in Delphi and a version in C#

you can get the code here and here, not much really but you could re-use it in 04/05/2106

the picture was actually taken at 01:02:03 04/05/06
...I'm such a geek

update: I made a change to the code to "freeze time" at whatever time configured, that's a nice touch, now I can use that for other count downs, I'll put up the new versions

Monday, April 03, 2006

don't miss the 01:02:03 04/05/06

On Wednesday of this week, two minutes and three seconds after 1:00 in the morning, the time and date will be

01:02:03 04/05/06

this event happens every 100 years, since we use two digits for the year

for most other countries the date will be on May 4, since they use DD/MM/YYYY

Saturday, April 01, 2006

April fools summary

check it out right here

http://en.wikipedia.org/wiki/April_1,_2006

one of the first ones that came out is this one from Microsoft

http://www.msnsearchspoof.com/

where you can setup a page that will simulate MSN search site, go play a good prank on your co-workers

Friday, March 31, 2006

(SQL) should I use #temp table or a @table variable?
I found this great article about all the advantages and disadvantages between #temp, ##temp, @temp, temp tables

definitely worth reading, or course is part of my delicious feed too
(SQL) How do I update only the top # rows from a table?

This can be specially handy when you are testing your data, but it can apply to many production cases as well, I've seen people invent so many ways to do this, but here's a simple way of doing it

set rowcount 100
update YourTable set SomeField = 'Something' where SomeField is null
set rowcount 0

it is very important that you run set rowcount 0 after finishing whatever you needed rowcount for, else any other query (select, updates, etc) that you run will only run for the first # records and it can really give you some headaches, so whenever you write

set rowcount #
write
set rowcount 0

immediatly after that, then write the query in the middle that requires to be ran with the limited rowcount
Favorite features in .NET 2.0

Edgar posted today about one of the new functions in .NET 2.0 to make your life easier, like using

aString.IsNullOrEmpty()
instead of
aString != null && aString != "";

it reminded me about this video from Kit George where he shows some of the new cool little functions that will help you a lot

in .NET 2.0 you can now use:

if (aString.Contains(otherString))
instead of:
if (aString.IndexOf(otherString)<>0)

or

foreach(string line in File.ReadAllLines("c:\theFilePath"))
Console.WriteLine(line)

instead of:
string line;
using (StreamReader sr = new StreamReader("c:\TheFilePath")) {
while ((line = sr.ReadLine()) != null)
Console.WriteLine(line);
}

check out the video to learn more about these and other features

you'll also find the link on my delicious feed under videos
my del.icio.us feed
in case you haven't (heard of, or) used this yet, it is definitely a must, for those of you that don't know that del.icio.us is, is a place where you store your favorites (links) and you can attach TAGS to them, it creates a page for you with your list of favorites and you can quickly filter for what you are looking for using the TAGS you assigned when you added the link

this has many advantages, how many times have you tried to synchronize a list of favorites between more than one computer, or maybe you are with someone else and you know you have a site on your favorites list that you need right now...
del.icio.us will do that for you, pretty simple concept, but it is really powerful

if I didn't do a good job describing what del.icio.us is, here's the definition from the de.icio.us site itself

"What is del.icio.us?
del.icio.us is a collection of favorites - yours and everyone else's. Use del.icio.us to:
- Keep links to your favorite articles, blogs, music, restaurant reviews, and more on del.icio.us and access them from any computer on the web.
- Share favorites with friends, family, and colleagues.
- Discover new things. Everything on del.icio.us is someone's favorite - they've already done the work of finding it. Explore and enjoy."

here's my del.icio.us feed, I'll keep updating that

check del.icio.us out, I'm sure you'll find it usefull

Saturday, March 25, 2006

I just got my (very late christmas present) Cingular 8125, it's sweet!

sent from my cingular 8125, this is my dog Kombo

Friday, March 24, 2006

"it won't affect anything"... on basic development rules: don't make assumptions

When you go to sleep you set the clock's alarm and you assume that it'll work and it'll wake you up in the morning, in some cases you'll setup two alarms assuming that if one doesn't work the other one will (I least I do that when I'm going to be traveling the next morning), when you are driving you drive through a green light assuming that no one is coming from the sides, because they have a red light, etc, etc, etc, at some point we assume something; we live by assumptions!

when we are programming is no different, many times we make assumptions, and quite often those assumptions translate into poorly performant software or users end up using your software in a way you didn't expect it to which translates into a bad experience because you didn't program the software to be used that way (you assumed a different use)

so it's all about assumptions, we assume that a connection will exist, that a file will be there, that a query will run...

do yourself a favor, think about the assumptions you make and try and remove them, this is FAR easier said than done, but just by being aware that you shouldn't make assumptions you will already be ahead of the game, I have been living (not only programming) by this concept for years and I still make assumptions that will *cost me* errors in the software I write, but it is definitely a lot less errors

a very huge assumptions that is made is
"it won't affect anything"

that's a big one, everyone's done it several times, so think back how many times you've said "it won't affect anything" and you ended up breaking the entire system, messing up the database, etc

sure, that's what testing is for, but first of all, if you introduced new bugs you end up wasting a lot more time that it was necessary and second, not everyone has a test team, and if you test your own software since you are pretty sure "it won't affect anything" you don't test your software that well

here's a list of common things that you SHOULD NOT assume
- your app can use all the RAM it needs
- your app can use all the DISK space it needs
- a file will exist
- you will have permissions to do X or Y (specially on web apps, accessing files, etc)
- your app will run under administrator privileges (this is a big one too)
- a connection will be present (TCP, HTTP, SQL, etc)
- a connection will not be dropped in the middle of things
- it won't affect anything

that's a small but pretty good list I think, start avoiding assumptions, I guarantee you will become a better developer that creates more reliable software faster

Thursday, March 23, 2006

on quick little tips: claim your computer memory (kinda manual garbage collector)
on my development machine at work I have Windows 2000 with 1GB of RAM, that used to be more than enough, but nowadays, programs are just getting more and more memory hungry

while you can leave your computer up without reboots for weeks and weeks, you'll notice the memory consuption to keep going up and up

here's a trick to claim some of that memory back so other programs can use it:
- restart a bunch of your windows services and stop (or even disable) the ones you're not using!
- restart (close and reopen) any web browsers that you are using
that's it...

now if you want more detail keep reading

to open the services console, click on Start, Run, type "services.msc" (without quotes of course!) hit enter
click on the "status" colum, so get all of the ones that are started all together

the first one is Automatic Updates, stopping this service will claim quite a bit of memory, if you are good are keeping an eye on updates, stop and disable this one and you'll have an extra 30MB of RAM for other things

here's a list of services that you can (most likely) safely restart without causing problems
- Machine Debug Manager
- Print Spooler
- Your antivirus, i.e. I have "Symantec Antivirus Client"
- Task Scheduler
- TCP/IP NetBIOS Helper Service
- VNC Server (in case you have VNC installed on your machine)
- IIS Admin Service (this will restart other services that depend on it)
- MSSQL* (there can be a number of these ones, depending on what version of MSSQL you have, you can restart them all)

other services you can restart, I haven't noticed much gain from restarting them though:
- Background Intelligent Transfer Service
- COM+ Event System
- Computer Browser

Services you can stop (or disable):
- IIS Admin Service (this will stop other services that depend on it)
- MSSQL* (if you have the 2005 version, you have a bunch of these ones, and they all take a lot of memory)

I usually stop IIS and MSSQL because I don't use them everyday, if you can't stop them because you always use them, at least restart them

if you don't use MSSQL or IIS, except in very few cases, you can even disable them, and then just reenable them whenever you need them

performing the above steps can claim back a bunch of RAM, I've seen 200 MB go back in my machine, but it can vary greatly

now, if you don't like doing that manually, you can always create a .BAT file to do all that for you, and then you could put a shortcut somewhere in your desktop or quick launch bar

to restart a service from a .BAT file you just enter something like:
net stop "Task Scheduler"
net start "Task Scheduler"

you do that, and you can claim a bunch of RAM every day with a single click

of course, nothing beats restarting the machine, but again, there might be services that you don't really use, so no need to have them enabled, and of course you can always use the RAM for other things
Tour Technet - Mexico
I don't know that I have any readers (at all?) in Mexico, but if anyone's reading and are interested, Microsoft Tour Technet is coming to Mexico from March 14th through March 30th to the following cities:

Queretaro, Guadalajara, Chihuahua, Juarez, Monterrey, Len, Ciudad de Mexico Zona sur, Coatzacoalcos, Ciudad de Mexico Zona centro, Puebla y Tijuana

you can find more information and register by going here:
http://msevents.microsoft.com/cui/eventdetail.aspx?culture=es-mx&eventid=1032292033

and you can find the agenda and more information here:
http://www.microsoft.com/spanish/msdn/mexico/eventos/

Tuesday, March 21, 2006

Internet Explorer beta 2 (3 really) is looking pretty good
I've been browsing today using the latest release of Internet Explorer, and so far is looking pretty good, they have fixed some bugs with fonts and CSS (sites that didn't work right in the previous version are working ok now), I like it
opening and closing tabs using the middle button is pretty cool, there are a bunch of other features, click here to go to the download page and try it your self, I like it a lot better than FireFox now

Friday, March 17, 2006

SQL Bug (or feature?) when using sub-queries

I have been using SQL sub-queries for quite a while and had never seen this until today, I was trying to delete records from a table that were found in another table

*luckily* I created a backup before deleting anything, the query to delete ended up deleting every single record from the first table, I knew that not all the records from one were in the other one, so I investigated a little bit, and was able to reproduce the behavior

try this:

CREATE TABLE [temp1] (
[Field1] [nvarchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Field2] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Field3] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO

CREATE TABLE [temp2] (
[Field2] [nvarchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Field3] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Field4] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO

--Execute both inserts a few times
insert into temp1
values ('v1', null, null)

insert into temp2
values ('v2', null, null)

--now run this query
select * from temp1
where field1 in (select field1 from temp2)

you get all the records from temp1

notice that the field field1 doesn't exist in temp2, but it does exist in temp1, if I try a field that doesn't exist in neither table I will get the "Invalid column name 'fieldx'." error

weird... I wonder if this is a bug/known bug... or a feature!

Monday, March 13, 2006

blaming it on something else, other than your application

this article about ASP.NET 2.0 Unhandled Exception Issues reminded me of people that always tries to blame it on something else when their application fails, not that I like how the exceptions are handled in ASP.NET 2.0, but I've heard programmers complain about the network's fault, that the third party DLL is not behaving properly, that the drivers are corrupt, even that Windows is *crashing* (imagine that! =oP)

in the case of the article it refers to unhandled exceptions killing your application, truth is, when problems arise a lot of developers will look at something else before looking into their code to see what's wrong

if you just made a change to your program and now is not working, 99.999 it was your fault!, just go look at the changes you made and fix it! instead of wasting time blaming it on something else

if an exception is killing your application and you are left with nothing but criptic messages about the error, it still is your fault, go and put proper exception handling, exception handling should be there from the time you first write the code, why leave it at the end? or why leave it until you are not able to determine the cause of the errors?
whenever you are about to write code that can potentially raise exceptions, always write this code first (adapt it to whatever language you're using)

try
catch
finally

and then write the code in between

in the catch:
handle exceptions, re-raise if needed, include any additional information that will help you track what caused this exception (line #, record #, whatever data you were dealing with, etc, it will make it a LOT easier to track if you include this information)

in the finally:
release any resources

for Delphi I like to use
try try
except
//*** handle exceptions
end finally
//***release any resources
end

C# also allows you to use a "using" statement
using (somevariable = new... blabla) {
}

which is basically an implicit
somevariable = new blabla
try
//***your code here
finally {
somevariable.Dispose();
}

so use it whenever possible

unhandled exceptions are a BIG cause for software failures, so handle your exceptions and stop blaming it on something else

Friday, March 03, 2006

on quick little tricks, how do I verify that all the lines of a file have the same length?

open the file in your favorite text editor (on second thought, use Notepad, Notepad2, WordPad or something like that, certain fonts, margins and other beautifiers might screw up the results), make sure Word Wrap is OFF, select all the text, then scroll to the far right side and you should see a perfect line as long as you are using a fixed-width font (a font that displays all characters with the same width)

update: to include the name of such fonts, thanks Mason

Thursday, March 02, 2006

Windows Vista helps you protect your kids

if you are a parent worried about what sites their children are visiting, who are they chatting with, etc, you will be glad to know about the new built-in features on Windows Vista, check out the article:

Family Safety on Windows Vista

what is amazing to me is the comments of people complaining about these features, of course everyone can have whatever opinion, but I think leaving your children open in the wild internet is just plain stupid