Saturday, February 10, 2007

magic variables to help in exception debugging

This article applies to C#, J#, and Visual Basic.
I read about these variables a long time ago in some blog, but I could not find anything about those hidden little things, mainly the problem was that they are not called magic or hidden, they are documented and are called Pseudovariables;

Pseudovariables are terms used to display certain information in a variable window or the QuickWatch dialog box. You can enter a pseudovariable the same way you would enter a normal variable. Pseudovariables are not variables, however, and do not correspond to variable names in your program.

Anyway, I don't think many people know about them, here they are:
  • $exception: Displays information on the last exception. If no exception has occurred, evaluating $exception displays an error message.
    In Visual C# only, when the Exception Assistant is disabled, $exception is automatically added to the Locals window when an exception occurs.
  • $user: Displays a structure with account information for the account running the application. For security reasons, the password information is not displayed
when you are debugging an exception you might have some code like this:

try {
//some code
} catch (Exception e) {
//don't really need e here, just to get the exception information on the Watch window
}

you could write this code as:
try {
//some code
catch { } //put the breakpoint on this line, inspect $exception (Debug, Watch, Watch 1, type $exception there)

and get the same information.

The $user pseudovariable is pretty self explanatory.

in native code you have a few more pseudovariables available, check the link if you are interested.

those little things...

Friday, February 09, 2007

DOS attack on google using google tools?

just noticed this post on the Google Operating System blog that shows how to backup your blogspot hosted blog, it basically allows you to run a query like this:

http://ebersys.blogspot.com/search?max-results=N

that retrieves N posts for such blog

but what if the bad guys just decide to use that and query a bunch of blogspot pages all at the same time? that would be a lot of data coming from the google servers, I just tried this one

http://googlesystem.blogspot.com/search?max-results=2000

and it took quite a while to download

the fix would be easy, they can put restrictions on who can run the query, for example just require that the blogspot user is authenticated and you can only run the query on your blog

unless google doesn't care and they can handle that just fine, we'll see

As a general rule, unless you are part of google, don't allow your users to run queries that return all the rows in your tables... is not a good thing

Thursday, February 08, 2007

protected, internal, protected internal... are you sure you know them?

the code for this article applies to C#

We all take access modifiers for granted, but can you tell me what protected internal does?

I bet more than half .NET developers will get that wrong, let's review:
  1. private:
    1. This is the least permissive access level.
    2. Accessible only within the body of the class or the struct in which they are declared.
    3. Nested types in the same body can also access those private members
  2. public:
    1. This is the most permissive access level.
    2. There are no restrictions on accessing public members, they are visible anywhere the class is visible
  3. protected:
    1. Access is limited to the containing class or types derived from the containing class.
    2. which means you cannot create an instance of a class and have access to protected members.
  4. internal:
    1. Access is limited to the current assembly.
  5. protected internal:
    1. Access is limited to the current assembly or types derived from the containing class.
that last one is kinda tricky, it kinda "makes sense" that it allows access only in the current assembly and the current or derived classes, but the "or" there is what makes a difference, if you mark a property protected internal, it can actually be accessed outside the assembly. basically protected overrides internal and so I'm not even sure when it makes sense to use such modifier.

If you don't believe me go check it out your self:
Assembly1:
public class Test {
protected internal string prop1;
}

Assembly2://after adding a reference to Assembly 1
public class Test2: Test {
public string prop2;
public Test2() {
prop2 = prop1; //came from the other assembly's class protected internal member
}
}

if this is news for you, you might think, that's stupid, how do you get a property to be visible only the the current assembly, current class and derived classes?

quite simple, you mark your class as internal, so your class can only be accessed from the current assembly, and you mark your property as protected, thus giving access to the derived classes only in the current assembly:

internal class Test {
protected string prop1; //accessible only in this assembly in this class and derived classes
}

Sunday, February 04, 2007

VS2005, VS2007 (Orcas), XNA, LINQ, WPF in Vista

how is that for a title... =o)

Justin and I were playing today with these technologies, it wasn't so much fun as we expected, in short all those things don't work together in Vista, if you want more details read on
  • VS2005 doesn't work on Vista, it crashes randomly and very often
  • VS2007 works fine on Vista
  • XNA development is not supported on VS2007 or Vista, only in VS2005 Express
  • the latest WPF is not supported in VS2007, only in VS2005
  • LINQ works fine on VS2007
so if you're thinking about playing with any of those technologies in Vista, reconsider using Windows XP

Tuesday, January 30, 2007

The type initializer for * threw an exception

The type initializer for *insert your favorite class here* threw an exception

This was driving me crazy, there's not a whole lot of info out there about this error, I should've used my psychic debugging powers (yes, I have those too =op) before

my scenario is a web service (.net 2.0) calling (deep down) into some code that does reflection to instantiate some classes, the exact same code works just fine under a web application, that's what's bizarre, how's a web service different to a web app on regards to permissions and security?

anyway, almost from the beginning I suspected it had to do with permissions, but being a web service, and the same code running fine under the web app made me leave that as a last option, so I looked and didn't find any real answer, then decided to configure a different user (with more permissions than the default asp_net) in IIS to run my web service, it ran just fine after that

ok, now I know the problem is permissions but I'm not happy with the "fix", so I'll keep looking and trying for a more elegant solution

free tip for those of you who may not know this one
enter "The type initializer for * threw an exception" in google... it's a beautiful thing, Google takes wild cards as part of a search, it works with multiple wild cards in one phrase too

Monday, January 29, 2007

formatting 0, 1 as yes, no or whatever

This is something we all have done at some point, convert a 0,1 value into yes, no, on, off, etc string

turns out there is a function in the BCL that can do this, string.Format will do the job

Console.WriteLine(string.Format("{0:yes;;no}", 0)); //will output "no"
Console.WriteLine(string.Format("{0:yes;;no}", 1)); //will ouput "yes"


and just for the heck of it
Console.WriteLine(string.Format("{0:yes;;no}", -1)); //will output "-yes"

...one of those little thingies

Tuesday, January 16, 2007

xna programming: pre-requisites

A few moons ago (WOW, it has been a while) I promised I would write a small game and post all my experiences and source code here, we did the game design, set the goals and started writing the game, then after getting sick, the holidays, updates to the XNA framework, etc, kinda stopped working on the game. anyway, I decided to pick it up and started studying xna tutorials again to see what kind of things I had done wrong due to my lack of knowledge, it seems I wasn't doing so bad so I can actually update the tools (since there is an official xna release now), modify a couple things on my code and I'm good to go

however there are a couple (big) things you need to download and install before we can continue
- Visual C# 2005 Express, you might want to NOT download the MSDN help for it though, that's an extra 2GB or so, VC#2005 Express can be downloaded here, and if you have any firewall issues you could download an offline installation (CD) here
- DirectX Software Development Kit, which includes XACT, a tool that will help you create and work with sounds
- XNA GSE (Game Studio Express), this is the thing that will allow you to create a xna project and conect all the dots so you can easily write xna apps, however beaware of the following:
  • Only supported on Microsoft® Windows® XP SP2 (all editions) at this time. Windows Vista will be available only in a future beta release of XNA Game Studio Express.
  • Hardware requirements are identical to those for Visual Studio 2005 plus a graphics card that supports DirectX 9.0c and Shader Model 1.1 (Shader Model 2.0 support recommended).
  • This release requires Microsoft Visual C# 2005 Express Edition to be installed before proceeding. You can install Visual C# Express from the Visual C# Express Download Page. However, other members of the Visual Studio 2005 line of products, for example Visual Studio 2005 Professional, can co-exist with XNA Game Studio Express on the same computer.
  • Installation of the XNA framework is not necessary on systems with XNA GSE installed
once you get all that working, take a look at the basic tutorials out there, get familiar with the API, play with it, my code won't be about teaching you C# like some of the tutorials on the provided links, I will assume you are already familiar with the language, although you might learn a technique or two but I won't be explaining C# coding, just the use of the XNA API and the overall design of the game

'til next time

Saturday, January 13, 2007

dummy interview question

is this code:
A)
a1 = new SomeClass();
a2 = new SomeClass();

equivalent to:
B)
a1 = a2 = new SomeClass();

??
(explain why)

The trick is how you ask the question, if you asked "what's the difference between option a and option b?" you are already telling them there is a difference.

Friday, January 12, 2007

Thursday, January 11, 2007

Tuesday, January 09, 2007

suggestion for google reader

I can start items and share items, that's great, how about you allow me to highlight stuff?

Thursday, January 04, 2007

just got my old new thing

now if I could get this book autographed J

got some reading to do J

Wednesday, January 03, 2007

first geek joke of the year

I tried posting more stuff yesterday but blogger.com was down, I couldn't even leave comments to other blogger blogs =o(

anyway, happy new year everyone!!

Tuesday, January 02, 2007

first post of the year

I'm in El Paso right now, it's been snowing all morning in Juarez and here, hopefully my flight won't be delayed, and what's worst, I'm flying through Denver...
anyway, I have internet thanks to my Cingular 8125 =o), we'll see how it goes today, at least I'll be reading a lot of blogs and updating my reading list

Friday, December 22, 2006

Remote Desktop tips and tricks

Here's a list of tips and tricks that I have compiled from my reading list, I've seen a tip here and a trick there, but not a full list, so here it is (for me to remember J)

shutdown or restart a workstation

Note: These tips work on Windows XP, but there is no guarantee that they will work in future versions of Windows.

One way to do this is to run Task Manager and select your shutdown option from the "Shut Down" menu.

Another trick is to click on the desktop and type Alt+F4. This will call up the shutdown dialog, where you get the usual shutdown options like "Shut down", "Shut down without installing updates", "Restart", "Stand by", and "Hibernate".

These next two tricks are documented and will continue to work in future versions of Windows:

If you're a command line person, you can run shutdown.exe, but that program supports only shutdown and restart; it doesn't do stand-by or hibernate. But the shutdown.exe program has a serious flaw: It requires you to have administrator privileges. If you are a limited user with shutdown privileges, the shutdown.exe program will complain. (Which means that I don't use it.)

Finally, if your computer isn't using Fast User Switching, you can type the Ctrl+Alt+End hotkey, which is the Remote Desktop version of Ctrl+Alt+Del and consequently takes you to a dialog where you can do various system-type things, among them logging off and shutting down.

Connecting to terminal services when all active sessions are used:

mstsc /console

Mapping drives via Remote Desktop

Open the remote desktop application. Click on the Options button and go to the Local Resources tab. The bottom section of the tab is titled Local Devices, and there you will see a check box labeled Disk drives. Checking this box will automagically connect all disk drives on you local machine to the remote machine when you open the RDC.

Remote Desktop on a non-standard port

Modify this registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp

Connecting via remote desktop to the non-standard port

Suppose you change the port for the virtual machine to listen in on port 3900. You simply append 3900 to the server name (or IP) when connecting via Remote Desktop.

Important shortcut keys:

Alt + Page Up
Switches between programs from left to right.

Alt + Page Down
Switches between programs from right to left.

Alt + Insert
Cycles through the programs in the order they were started.

Alt + Home
Displays the Start menu.

Ctrl + Alt + Break
Switches the client between a window and full screen.

Ctrl + Alt + End
Brings up the Windows Security dialog box.

Ctrl + Alt + Pause
Toggles between fullscreen and windowed mode
(note that this does not set the client desktop to the correct size)

Alt + Del
Displays the Windows menu

Ctrl + Alt + Num -
Places a snapshot of the client's active window on the clipboard

Ctrl + Alt + Num +

References

http://blogs.msdn.com/oldnewthing/archive/2006/10/20/849575.aspx

http://haacked.com/archive/2005/10/13/Remote_Desktop_To_Console_Session.aspx

http://stevenharman.net/blog/archive/2006/10/22/Mapping_Drives_via_Remote_Desktop.aspx

http://haacked.com/archive/2006/10/17/Remote_Desktop_On_A_NonStandard_Port.aspx

http://www.codinghorror.com/blog/archives/000570.html

Reading list

Visual Studio 2005 SP1 for Windows Vista (Beta)

is ready, just in time for christmas

Wednesday, December 20, 2006

function to generate random numbers, without repeating digits

The code for this article applies to C#

Reading blogs, I found this post (in italian), where Marco wants to write a function to generate random numbers with the following rules:

  • 5 digits long
  • result should be returned in a string
  • all the digits should be different (on each result you can't have two of the same digit)

The function he came up with was the following:

private string GetRandom()
{
Random rn = new Random();
string resultnum=string.Empty;
do
{
string a = rn.Next(0, 9).ToString();
if (resultnum.Contains(a)!=true)
resultnum = resultnum + a;
}
while (resultnum.Length<5);
return resultnum;
}

I felt curious to see what areas I could improve, and I started writing a function to get the same result, but in a more optimized way

A couple things that jump out to my mind are:

  1. string concatenation
  2. the loop and comparing each time to see if the digit is in the result already

So I wanted to write a function that: would avoid concatenation and would execute the loop exactly 5 times, this is the result:

static char[] allNumbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
Random r = new Random();
public string GetRandom2() {

char[] result = new char[5];
int max = 9, pos=0;
for (int i=1; i<6; i++) {
pos = r.Next(0, max);
result[i - 1] = allNumbers[pos];
//*** swap positions
allNumbers[pos] ^= allNumbers[max];
allNumbers[max] ^= allNumbers[pos];
allNumbers[pos] ^= allNumbers[max--];
}
return new string(result);
}

The technique I used was:

  • Have a predefined array with all possible characters
  • I have a variable max that I use to call the method Random.Next(0, max)
  • the variable is decremented on each iteration
  • I swap the digit from the result to the last position, with this I leave this digit out of the posibilities for the next call

The performance gain from these changes was minimal (3 ms per 1000 calls), then I thought about moving the Random variable declaration outside the function, so it could be reused between calls, this gave me the performance gain I was looking for, calling the function 10,000 times takes ~114ms using the old method and only ~6ms using the new one, that's where the problem was, the rest was pretty much insignificant =o(

I'm sure someone else can write a faster version, but I accomplished my goal =o)

Tuesday, December 19, 2006

A sign that you've been blogging too much: blog deja vu

Antonio Ganci says (blog in italian) sometimes when he's about to blog something, he gets this feeling that he already posted about that, kinda like blog deja vu, then he actually checks the old posts just to find out he hadn't written that post

I thought it was funny, hasn't happened to me yet, but probably happens to a lot of people; I find the Deja Vu effect quite interesting... and I few days ago I saw the Deja Vu movie which was pretty good (but I thought I found one error on the movie)

Monday, December 18, 2006

deleting items from a generic list

The code for this articles applies to C# 2.0
A more or less common task on a generic list is to remove items from it, lets see what approaches we can take:

#1 The definitive wrong way to do it:

List<Person> l1 = GetList();
//*** The wrong way
foreach (Person p in l1) {
    if (p.Age > 30)
        l1.Remove(p);
}

This code will throw an InvalidOperationException: "Collection was modified; enumeration operation may not execute."

#2 Kinda works (and allows you to perform an action on the item being deleted)

List<int> ints = new List<int>();
ints.Add(1);
ints.Add(2);
ints.Add(3);
ints.Add(4);
ints.Add(5);
ints.Add(6);

ints.ForEach(delegate(int i) {
if ((i % 2) == 0) {
Console.WriteLine("removing"+i.ToString());
ints.Remove(i);
}
});



If you run that code it will work just as we expect it, but there is a problem with it, if you add all the pair numbers first you would see that it doesn't delete all of them, it doesn't throw an exception, it just breaks out of the loop and keeps going, so this method works but on very specific conditions


#3 The right way: we traverse the collection backwards and delete items

int x = ints2.Count;
while (--x>=0) {
if (ints2[x] < 4)
ints2.RemoveAt(x);
}



#4 A better way: the list has a method for this purpose

ints2.RemoveAll(delegate(int i) {
return i <4;
});



#5 But what if I need to perform an action on the item being deleted?

ints2.RemoveAll(delegate(int i) {
if (i < 4) {
//*** Perform action here
Console.WriteLine("removing :" + i.ToString());
return true;
}
else
return false;
});



if the item was a class we could call methods on it before deleting it from the list (perhaps a call to a DB)


On future posts I'll talk on detail about why exactly #1 and #2 don't work

put the focus on a ChangePassword Control UserName field

I was trying all sorts of things to set the focus to the UserName control of the ChangePassword Control, turns out it was as simple as:

if (!Page.IsPostBack)
ChangePasswordControl.Focus();

works for the Login Control too

if (!Page.IsPostBack)
LoginControl.Focus();

macros in good old DOS

I just read this post (from Jeffery Hicks?): Make an old friend do your work where he explains how you can use good old doskey to make your life easier (at the command line), and it motivated me to write a blog entry for 2 reasons:

- he missed a few points
- I want to remember this stuff too, since it seems I'm starting to forget stuff =o(

Let's see, first of all he defines a macro like this:
doskey xl="%programfiles%\Microsoft Office\Office11\Excel.exe" $1 $2 $3 $4 $5

and explains "You can use variables like $1 and $2 (all the way up to $9)".
but why limit yourself to 9 parameters? you can write it as:
doskey xl="%programfiles%\Microsoft Office\Office11\Excel.exe" $*

that will take whatever number of parameters you pass to it. To test that it actually took more than 10 parameters I created a file 1.xls and then ran this command (a lot of people don't know this one):

for /l %e in (2,1,11) do copy 1.xls %e.xls

Which by the way means (loop from 2 to 11 in steps of 1, copy file 1.xls to [variable].xls);
now I had 11 files to play with, so I called my macro:
xl 1 2 3 4 5 6 7 8 9 10 11

which brings me to another point he missed: "from a command prompt I can type xl file1.xls file2.xls file3.xls and have Excel open all three files"
You don't have to specify the extension, you can just pass the file name-no extension and excel will open it happily

This also brings me to another point: if you just wanted to open a single file, you could just type the file name:
1.xls
and Windows will open it in the default application (most likely excel) so for single files, we don't even need the macro

finally, this macro thing doesn't really work for notepad (or notepad2) if you call
np 1.txt 2.txt it tries to open the file "1.txt 2.txt"

you can only open single files =o(

one last tip, to delete a macro you just do
doskey myMacro=

Sunday, December 17, 2006

Get (another's class) private fields

About 2 months ago I wrote a couple articles on reflection, specifically about executing another's class private methods, someone left a question on how you can get the private fields, just now I found the time to answer to that; first of all let's create a test class:

class TestClass {
private int prop1;

public int Prop1 {
get { return prop1; }
set { prop1 = value; }
}

private string prop2;

public string Prop2 {
get { return prop2; }
set { prop2 = value; }
}

private bool prop3;

public bool Prop3 {
get { return prop3; }
set { prop3 = value; }
}

public bool field4;

public TestClass() {
prop1 = 10;
prop2 = "20";
prop3 = false;
field4 = true;
}
}



Then we create an instance of it, and use the method GetFields to (you guessed) get the list of fields, we just have to specify on the parameters that we want private members and they have to be instance members (non-static), once we get the list we can do *whatever* we want with it, in this case the code prints the field type and it's value


TestClass test = new TestClass();
FieldInfo[] fields = test.GetType().GetFields(BindingFlags.NonPublic BindingFlags.Instance);
foreach (FieldInfo f in fields)
Console.WriteLine(string.Format("type:{0} \t value:{1}", f.FieldType.ToString(), f.GetValue(test)));


That's about it. Now, just to make it a little bit more interesting I created a small generic function to accomplish the previous task and now you can reuse that with any other class:

static void PrintPrivateFields<T>(T theInstance) where T:class {
Type t = theInstance.GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic BindingFlags.Instance);
foreach (FieldInfo f in fields)
Console.WriteLine(string.Format("type:{0} \t value:{1}", f.FieldType.ToString(), f.GetValue(theInstance)));
}



To use it, we just create an instance of that class and pass the instance to the function:


TestClass test = new TestClass();


PrintPrivateFields(test);


Note that I don't need to specify the type when calling the function


PrintPrivateFields<TestClass>(test);


The compiler is smart enough to figure it out (since the only parameter is of that type).


Hope the code is useful, you can find the full code here

I just finished browsing "The Internet"

From tecblog

or more accurately, I just got caught up reading blogs, I have been sick and very busy for the last month or so and that's the reason I haven't posted much here. However blog writers don't give me a break and whenever I don't read blogs for a couple days I get really behind; here's a list of the blog entries that I have found most interesting (out of the 266 blogs that I subscribe to), I'll try to include this list on my blog

My starred items

Friday, December 15, 2006

How to install Visual Studio SP 1 in less than an hour

Visual Studio SP 1 update is all over the blogs now, however there are many reports that the install takes a long time (over 2 hours), I managed to install it in about 30 minutes by shutting down every program and stopping a bunch of services (except machine debug manager, I don't think is necessary but didn't want to risk it) and that was it, the installation finished really quick, hopefully it'll do it for you too

Update: on my old machine (where I just installed Windows Vista a few days ago), it took 20 minutes by following these simple steps

Monday, December 11, 2006

Tour Juarez-Chihuahua 2006

Is this time of the year where I get to back to my home town to visit family and friends, I will be in Juarez & Chihuahua from Dec. 23 to the end of the year, if you're interested in meeting, have some dinner, geek talk or whatever, drop me a line and we'll arrange something

Saturday, December 09, 2006

Windows is unable to find a system volume that meets its criteria for installation

I had a hard time installing Windows Vista on my old machine (hey, my machine is older than a year... and hey! I have been blogging for over a year!!) anyway... oh, the error message, I kept getting that error when trying to install to any of the (3) partitions on my SATA drive, I deleted them, formatted them, recreated them, nothing worked... one guy had posted a vague answer to this very problem: "Vista should be installed on active partition", what the h* is that supposed to mean?

on one last desperate attempt, I disconnected the other drive (that I didn't mention before) from my machine, leaving only the SATA drive connected, ran the installation and voila!, that's all I needed to do, the installation ran smooth after that, everything is working great so far, I think I even like IE7 a lot better in Vista and Aero Glass is sweet canadian mullet!

here are some shortcuts keys for you guys new to Vista

and hopefully my experience will be helpful to some other soul, now if you excuse me I got some playing to do, next stop: Office 2007 baby

Thursday, December 07, 2006

give me beans and fries and I can stop a plane

this is hillarious, unless, of course, it happened to you

Wednesday, December 06, 2006

Novell commands to remember

I "grew up" using Novell networks and DOS, I used to be really good at managing Novell servers but I haven't touched a Novell server in quite a while; yesterday they were having problems with an old Novell server and they asked me for help, I couldn't remember some of the basic commands, so this post is for me to remember those commands later, and maybe you are so lucky that you may need these ones sometime

Server commands

  • server - at the DOS prompt, actually starts the server
  • restart server - bring the server down and restart immediately
  • VRepair - use it to correct volume problems (you can't use vrepair on a mounted volume), also use it to remove name space entries from directory entry tables
  • enable/disable login - to prevent users from logging in
  • mount - make a volume available to users (mount all to mount all volumes)
  • dismount - make a volume unavailable to users
  • volume - get a list of mounted volumes, or information about a volume (parameter)
  • down - take the server down (nicely)
  • load/unload monitor - load/unload the monitor (get the nice UI)
  • tcpcon - nice monitor with a bunch of information about TCP and other network protocols
  • display environment/processors/servers/networks / modified environments / interrupts -
  • list devices - gets a list of storage devices (disk drive, cd-rom, etc)
  • memory - displays total amount of installed memory that the operating system can address
  • mirror status - view status of mirrored disk partitions, view percentage of mirrored data on each partition
  • modules - get a list of loaded modules

Workstation commands

  • attach - connects to another server, but remains logged in to the current server
  • caston/castoff - enables/disables network messages from other workstations and the server if the ALL option is used
  • chkvol - shows volume information, free space, usage, deleted files, etc
  • login/logout - you get the idea
  • rights - display rights for files and directories
  • rconsole - remote console, to control a server from a workstation, if no server specified, a list is shown
  • purge - removes (previously deleted) files permanently, files purged can't be recovered
  • slist - list of servers
  • syscon - manage user, groups, rights, etc

Tuesday, December 05, 2006

you have been using patterns for a while

Take this one for instance, the Composed method:
Divide your program into methods that perform one identifiable task. Keep all of the operations in a method at the same level of abstraction. This will naturally result in programs with many small methods, each a few lines long.
That's as simple as breaking a method into smaller methods, something you do in every day programming, there are many simple patterns like this one, all they do is describe the tasks you do on a daily basis.

The whole point is that by knowing the names of the patterns, you can communicate much faster, easier, better and by using them you will be a more educated programmer, a better developer; remember that a great developer is not only the one who can write amazing code, but who can communicate ideas and is able to work on a team

"the best code in the world is meaningless if nobody knows about your product."

You are already using patterns, learn their names, learn more patterns, use them and pass them on to your team, you will learn even more, by teaching others.

Monday, December 04, 2006

If you're talented, the tools don't matter that much

This is the first post using blogger beta, we'll see how this goes, check what this guy can do using Paint



...or this other guy using Excel

Sunday, December 03, 2006

css tips: header, footer, and scrollable middle area full document

Back in the days, I used to start a page with a html table with 3 rows, one for the header, one for the middle area at 100%, and a footer

Nowadays this approach doesn't work any more and we're told that we have to use pure CSS, not tables, blabla... so, how do we accomplish this with pure CSS?

We are going to need some css and a bit of javascript, first of all, lets see the css

html,body,form
{
margin:0;
padding:0;
}//prevent some default spacing on some browsers
.header
{
text-align:center;
background-color:Navy;
color:White;
width:100%;
}
.footer
{
background-color:Orange;
color:Navy;
position:absolute;
bottom:0;
border:0;
}
div.scrollable{
overflow:auto;
border-left-width:0px;
border-bottom-width:0px;
border-top-width:0px;
border-right-width:0px;
background-color:Gray;
color:White;
position:absolute;
}

the most interesting is the last class div.scrollable, overflow:auto makes it scrollable, and the rest is to eliminate the borders and set the color.


Now lets see the html:

<html>
<head>
</head>
<link rel="stylesheet" type="text/css" href="test.css" />
<body>

<div>
<div id="header" class="header" height="20px">
This is the header
</div>

<div id="mainDiv" class="scrollable">
This is the main body<br>
There is a lot of stuff in the main
<br><br><br><br><br><br><br><br><br><br>
There is a lot of stuff in the main
<br><br><br><br><br><br><br><br><br><br>
There is a lot of stuff in the main
<br><br><br><br><br><br><br><br><br><br>
There is a lot of stuff in the main
<br><br><br><br><br><br><br><br><br><br>
There is a lot of stuff in the main
<br>
<br><br><br>
This is the last line
</div>

<div id="footer" class="footer" height="20px">
<div style="float:left">This is a div on the left</div>
<div style="float:right">This is a div on the right</div>
</div>

</div>

</body>
</html>

I put a lot of lines in the middle, just so you can see the document scrolling. As a "bonus" I put two divs on the footer, one aligned to the left and one to the right, both in the same "row", this is one of those things that people have a hard time finding. We're almost there, we just need some javascript now:

var mainDivHeight;
var mainDivWidth;

function AdjustFullSize() {
var screenHeight = 450;
var screenWidth = 610;

if (window.innerHeight) {
screenHeight = window.innerHeight;
screenWidth = window.innerWidth;
}
else if (document.body) {
screenHeight = document.body.clientHeight;
screenWidth = document.body.clientWidth;
}

mainDivHeight = screenHeight - 20 - 20; //20+20 for header and footer
mainDivWidth = screenWidth - 0;

document.getElementById('mainDiv').style.height = mainDivHeight + 'px';
document.getElementById('mainDiv').style.width = mainDivWidth + 'px';
}

The different browsers have different properties to access the document height and width, we account for that and then assign the size to the main div, call this function on the body onload (and resize!) and we are done, the end result looks like this, you can get the full source from there, hope you find it useful.

Wednesday, November 29, 2006

two checks in one with bool.TryParse

I just ran accross some code like this:

bool b = bool.TryParse(ConfigurationManager.AppSettings["SomeSetting"].ToString(), out b);

ignore the fact that I'm not checking for null on the appsettings.

At first sight I thought it was a bug, but then read the documentation, ran a little test and some investigation with Reflector, it turns out it does exacly what we needed to do

bool.TryParse doesn't return the value of converting the string passed to it; it returns true or false, indicating if the conversion succeeded, the value of the conversion is returned in the out parameter (which in this case was the same variable) so the only way to return true in that case is

  1. The conversion succeeded
  2. the value was true

so I don't need to say

if (bool.TryParse(someVariable, out b))

if (b)...

...little dangerous lines of code

Tuesday, November 14, 2006

Delphi has a new home

finally after what seemed like an eternity, Delphi has a new home (although still kinda living with it's parents, it will soon move out), no more Borland, it's now CodeGear

http://biz.yahoo.com/bw/061114/20061114006381.html...

Tuesday, November 07, 2006

Code reuse, next level

The code for this article is written in C# (tested in VS2005)

I'm still catching up with my blog reading; a few days ago I read an article on latindevelopers: sorting objects with IComparer (code in English, comments and article in Spanish); it reminded me of a common mistake: the use of conditional statements in (not so obvious) loops (e.g. callbacks) which results in a type of (not so obvious) code duplication.

In Delphi this error is commonly seen in component development, specifically on the Paint event where they use if statements to decide which font to use, colors, etc, and what's worst, many times an instance (of whatever objects are required) is created on each iteration; all those objects, of course, don't change unless you change properties of the component!!, so those should be cached and kept on variables where they can just be reused; yes, code reuse doesn't just mean re-using classes, or refactoring code into methods, caching objects is a form of code reuse because it avoids conditional statements and places code calls directly.

Let's see the code from the original example, specifically the PersonComparer class, it has a constructor which takes the SortField and stores that on a variable that is later used on the Compare method

public PersonComparer(SortField sortField) {
this.sortField = sortField;
}
public int Compare(object x, object y) {
if (!((x is Person) & (y is Person))) {
throw new
ArgumentException("Los objetos deben ser de tipo Person.");
}

switch (sortField) {
case SortField.Name:
return
Comparer.DefaultInvariant.Compare(
((Person)x).Name, ((Person)y).Name);

case SortField.LastName:
return
Comparer.DefaultInvariant.Compare(
((Person)x).LastName, ((Person)y).LastName);

case SortField.Age:
return
((Person)x).Age - ((Person)y).Age;

default:
throw new
ArgumentException("Tipo de ordenamiento desconocido.");
}
}

Perhaps you don't see it very clear because the example doesn't use generics, let's see what we could do using generics (there is a TimeZone2, so why can't I have my PersonComparer2?):

    public class PersonComparer2<T> : System.Collections.Generic.IComparer<T> where T:Person {
delegate int ComparerDelegate(T x, T y);
ComparerDelegate comparerDelegate;

Now we have a delegate declaration, a variable of that type and we got rid of the SortField variable, let's see the constructor:

public PersonComparer2(SortField sortField) {
switch (sortField) {
case SortField.Name:
comparerDelegate = delegate(T x, T y) {
return x.Name.CompareTo(y.Name);
};
break;
case SortField.LastName:
comparerDelegate = delegate(T x, T y) {
return x.LastName.CompareTo(y.LastName);
};
break;
case SortField.Age:
comparerDelegate = delegate(T x, T y) {
return x.Age - y.Age;
};
break;
default:
throw new
ArgumentException("unknown sort method.");
}
}

Instead of caching the SortField variable, I'm caching the method that will be executed when the comparison takes place; finally, let's see the actual Compare method:

public int Compare(T x, T y) {
return comparerDelegate(x, y);
}

do you see it? the decision of what method needs to be used for the comparison gets executed only once (on the constructor), then we can call it directly, instead of asking the same question over and over again on each iteration.

Every time you see a conditional statement on a loop or a method that gets executed in some kind of loop (like paint events, callbacks, etc) consider using this technique, it will help you build more structured and faster code, also consider using arrays or dictionaries of methods.

The concept applies to programming in general, but the implementation may vary from language to language, the main idea is to cache objects / methods in some way so you don't have to repeat conditional statements to create objects or decide which code block to execute.

The full code for this example can be found here, as always, play with it, learn from it, improve it.
kick it on DotNetKicks.com

Sunday, October 29, 2006

How to: Instantiate a class with a private constructor

Applies to C# (tested in VS2005)

On a recent post I talked about accessing (another's class) private methods through reflection; apparently not a lot of people was aware that this was possible. Well, here's another one for y'all, you can instantiate a class even if it's constructor is private

Here I'm including one example for a private constructor, one for protected and one for a (regular) public constructor, all of them using reflection.

Let's create our test class to play with:

public class TestClass {
private TestClass() {
Console.WriteLine("private TestClass constructor");
}
protected TestClass(int i) {
Console.WriteLine(string.Format("protected TestClass constructor (int:{0})", i));
}
public TestClass(string s) {
Console.WriteLine(string.Format("public TestClass constructor (string:{0})", s));
}
}

now let's see how easy is to instantiate this class using any of it's constructor, regardless of their visibility, all this through reflection:


- you need to include System.Reflection in your uses clause


The first one is a simple parameterless private constructor, not much is required here

//*** Private constructor
ConstructorInfo ci1 = typeof(TestClass).GetConstructor(
//*** Non public and instance (non static) constructor
BindingFlags.NonPublic | BindingFlags.Instance,
//*** No binder, no parameters, so no parameter modifiers
null, new Type[0], new ParameterModifier[0]);
//*** Call our constructor
TestClass tc1 = (TestClass)ci1.Invoke(new object[0]);
The second one is protected (you still still use "non-public" for the BindingFlags), 
it does include a parameter so we have to pass the parameter type
//*** Protected constructor
ConstructorInfo ci2 = typeof(TestClass).GetConstructor(
//*** non public and instance (non static) constructor
BindingFlags.NonPublic | BindingFlags.Instance,
//*** no binder, 1 parameter of type int, no modifiers for the param
null, new Type[1] { typeof(int) }, new ParameterModifier[0]);
//*** Call our constructor
TestClass tc2 = (TestClass)ci2.Invoke(new object[1] { 10 });
The third one is public, we could instantiate it without reflection, 
but I'll just leave it as an example. 
//*** Public constructor
ConstructorInfo ci3 = typeof(TestClass).GetConstructor(
//*** public and instance method
BindingFlags.Public | BindingFlags.Instance,
//*** no binder, 1 parameter of type string, no parameter modifiers
null, new Type[1] { typeof(string) }, new ParameterModifier[0]);
//*** Call our constructor
TestClass tc3 = (TestClass)ci3.Invoke(new object[1] { "test" });

That's it, that simple; this technique should rarely be used, more than anything I want you to be aware that it is possible and how easy it is


You could even combine the flags: BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance and it would instantiate the class if the access modifier was private, protected or public

You can find the full code here, have fun

By the way, I'm in Guadalajara now, I'll be here until Tuesday, then I'm going to Tulancingo Hidalgo and then Aguascalientes, if anyone wants to join me for dinner or just talk let me know


kick it on DotNetKicks.com

Thursday, October 26, 2006

Javascript madness

Found this on Javi Moya's blog

1. Highlight the text below
2. Ctrl+C
3. Alt+D (Ctrl+L in opera) (or just go to the address bar)
4. Ctrl+V
5. [Enter]

javascript:scroll(0,0); R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.getElementsByTagName("img"); DIL=DI.length; function A(){for(i=0; i-DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=(Math.sin(R*x1+i*x2+x3)*x4+x5)+"px"; DIS.top=(Math.cos(R*y1+i*y2+y3)*y4+y5)+"px"}R++}setInterval('A()',5); void(0);

6. You can navigate to other sites and try it there too

7. Even better in sites with tons of pics

8. Don't go around sites just copying and pasting javascript code in your address bar! =oP

Wednesday, October 25, 2006

Escape characters to use reserved words as variable names in .NET

This post is a follow up to Jean-Paul's article: Naming variables using the variable type name (useless tip #1), from the MSDN documentation we get this (at the top of the C# keywords section)

Keywords are predefined reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a legal identifier but if is not because it is a keyword.

.NET solved what was one of the biggest problems in the development area, which was seamless language interaction (because now every language compiles down to Intermediate Language).

Today in .NET you can write code in any .NET language and use it in any other .NET language; however, this does bring one issue, which is that reserved words in one language may not mean anything in other language, for example you might be programming in C# and you could call a variable begin, which in Delphi is a reserved word, and so when they used your C# code from Delphi they couldn't use it; to solve this problem, languages should (for their own good) implement some kind of escape character that allows you to use reserved words as variable names in case you are using code that was written in another language and they declared a variable name with the name of a reserved word in the language you are using

in C# you use the @ prefix

string @while = "something"
Console.WriteLine(@while);

in Delphi you use the & prefix

&begin:Integer;
begin
&begin := 10;
Console.WriteLine(&begin);

in VB.NET you use brackets to delimit the keyword

Dim [Dim] = 20
Console.WriteLine([Dim])

let me know if you know the escape character for other .NET languages

p.s. just noticed Jeff calls them escaped identifiers


kick it on DotNetKicks.com

Monday, October 23, 2006

How to: Execute (another's class) private methods

Applies to C# (Tested using C# 2.0)

The access modifier private is the most restrictive one, allowing access only to the containing type

Every once in a while we want to access a private method in some class that we don't have source code for (BCL anyone?); usually we shouldn't have to do that, but in case you need it for whatever reason, here's a way of doing it:

Lets create a test class to be used as our example:

public class TestClass {
public TestClass() {
}
private void HiddenMethod() {
Console.WriteLine("secret method, should only be called from the containing class itself");
}
private string HiddenMethodWithParams(string firstName, int age) {
return string.Format("hello {0}, you are {1} years old", firstName, age);
}
}

Basically this class is useless, because it doesn't expose any public methods... unless we had access to the private methods (okay, it's still useless, but this is just my lame example)


Now, let's see how we can access those private methods

TestClass tc = new TestClass();
Type testClaseType = typeof(TestClass);

MethodInfo hiddenMethod =
testClaseType.GetMethod("HiddenMethod",
BindingFlags.NonPublic | BindingFlags.Instance);
hiddenMethod.Invoke(tc, null);

MethodInfo hiddenMethodWithParams =
testClaseType.GetMethod("HiddenMethodWithParams",
BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[2] { typeof(string), typeof(int) }, null);
string result = (string)hiddenMethodWithParams.Invoke(tc, new object[2] { "Eber", 25 });
Console.WriteLine("result: "+ result);

Let's go in detail:



  1. 1- The first line just creates an instance (tc) of the class (TestClass) we're interested in (because it contain those precious private methods that we want)
  2. 2- The second line gets the type of the class, in this case it would be TestClass, this variable (testClassType) is used later on to query that class about it's methods.
  3. 3- Then it gets interesting, we acquire a "pointer" to the "hiddenMethod" private method and store it in the hiddenMethod variable; we do this by querying the testClassType variable, passing the name of the method; the parameter BindingFlags.NonPublic means you want a member which is not public (private in this case) and BindingFlags.Instance means you want an instance method (as opposed to an static one), remember that static methods don't get executed from an instance, but are called directly from the class.
  4. 4- Now that we have a pointer to the method we just need to call it, all we have to do is call the Invoke method of our hiddenMethod variable, we pass tc as a parameter, this is the instance on which we are executing the method (tc is the instance we created on the first line)

That's pretty much all we have to do, but of course a method that doesn't take any parameters and doesn't return anything is not very useful, so I included an example of calling a more complex method, one that takes parameters and returns something.


We just have to change a few things to make it work:


On step 3, where we get the pointer to the method, we need to pass information about the method's parameter types, this information is passed in an array, if you go to the top and look at the TestClass, you'll see that the method HiddenMethodWithParams takes 2 parameters, a string and an int, now let's see how we specify that:


new Type[2] { typeof(string), typeof(int) }


Which means: 2 parameters, the first one is a string, the second an int


You could (of course) pass any type of parameter here


Now we have the pointer to the method we want, but this method returns something, so we'll have to change the way we call it:


string result = (string)hiddenMethodWithParams.Invoke(tc, new object[2] { "Eber", 25 });


Here we create a variable to store the result, then we call the method, casting it's result to the type we know it returns (a string), the parameter tc remains the same, remember this is the instance on which we are calling the method, last we need to pass the parameters to the function, the way of passing the parameters is very similar to the way we specified their types


new object[2] { "Eber", 25 }


Which translates to: 2 parameters, the first one is "Eber", the second:25


That's it! try not to abuse this technique, full source can be found here


side node: while running Live Writer spell checking it suggested that I should call my test Class Testicles instead of TestClass


kick it on DotNetKicks.com

Get first and last elements of an Enum

This article applies to C# 2.0

From time to time (not very often) we have an enumeration and we want certain parameter (perhaps coming from a db) to be within the bounds of our enumeration (remember that it's legal to cast any integer value into an Enum, even if the value is out of the range defined in your Enum), most of the code I have seen just checks if such value is less than the last element in the enum, something like:

enum TestEnum {

  Enum1 = 1, Enum2 = 2, Enum3 = 3;

}

TestEnum myValue; //this might be coming as a parameter to a function

if (myValue > TestEnum.Enum3) //some code to handle this situation

and each time you have to update the enumeration, you have to take care of changing this part of the code.

This function returns the first and last elements (not int values) of an Enum, I wrote it using generics so you can reuse it with any Enum type, you could modify this to be specific to your enum and the function could be used in C# 1.0 (VS2003), the use of the function is probably rare, but anyway, here it is

public void GetLowHighFromEnum<T>(out T lowElement, out T highElement) {
if (!typeof(T).IsSubclassOf(typeof(Enum))) //make sure we got an Enum
throw new ArgumentException("parameterized type should be Enum");
T[] values = (T[])Enum.GetValues(typeof(T));
lowElement = values[0];
highElement = values[values.Length - 1];
}

To use it, it would be something like:

TestEnum te1, te2;
GetLowHighFromEnum<TestEnum>(out te1, out te2);
Console.WriteLine(te1.ToString());
Console.WriteLine(te2.ToString());

Saturday, October 21, 2006

It is legal to cast any integer value into an Enum even if the value is out of the range defined in your Enum

I've been researching Enums recently and have found some very interesting facts about them, for example:

It is legal to cast any integer value into an enum even if the value is not defined in the enum.

this is valid:

public enum TestEnum {
Enum1 = 1,
Enum2 = 2,
Enum3 = 3
}

...


TestEnum t = (TestEnum)10; //WTF?
Console.Write(t.ToString());
Console.Read();


Consider when the value comes from another source, such as a database


If you are dealing with Enums, you should read this article by Krzysztof Cwalina, it is a very complete reference / guideline for Enums; then when you get into Nullable Enums it gets even more interesting, I'll post a few things I'm doing with Enums

Wednesday, October 18, 2006

using the mouse: did you know...?

did you know that the middle button serves the purpose of closing windows in most tabbed-document applications? (you have to click on the tab)

for example all the new browsers: IE7, Firefox, Flock, Opera, etc, implement this; but also Visual Studio, Some Notepad replacements, MSN Messenger, etc, most of the tabbed-documents applications implement this funcionality

also, on browsers, "middle clicking" on a link opens the link on a new tab

Monday, October 16, 2006

quest for a better CAPTCHA

Recently, Geoff got concerned with SPAM and the current alternatives to try to avoid it, ever since he has been working on a simpler approach (for the user) where he provides pictures instead of text, and you have to click on a few of the pictures, depending on the given instructions; while the idea is original, and it does make it easier on the user, I can see a few issues with the approach

  • images have to be downloaded to all your readers (bandwidth)
  • you have to have a considerable amount of pictures to make this usable (and more bandwidth problems associated with that)
  • Each implementation of this would have to have it's own set of pictures and rules associated with them (kinda hardcoded)
  • it's kinda big

This, however, has given me another idea, why don't we combine regular text with Geoff's idea?

we could have something like:

click on even numbers: 123641

click on mathematical symbols: 123+45/6*21

click on uppercase characters 1A654abPK

etc, the font of course can be different (and bigger), the advantages are:

  • very small
  • infinite number of CAPTCHAS can be generated programmatically
  • it's readable
  • taking some precautions it can be very clear and simple what the user needs to do (some times I can't tell if Geoff is smiling or he's angry =o( )

am I missing something, or did I just come up with the greatest idea against SPAM? =o)

if you still like Geoff's idea, I think at least the images (and questions associated with that) could be generated programmatically, e.g. lines in different angles, circles, triangles, etc, that by itself would solve most of the problems I see with Geoff's approach

anyway, time to go to sleep

Thursday, October 12, 2006

careful with commas in your SQL statements

yesterday we had a bug that was something like:

select field1, field2, field3
field4, field5
from SomeTable
where field1 = 'someValue'

can you spot the bug?

the query runs just fine, but it didn't output the desired results

the problem is that it's missing a comma between field3 and field4, thus is like saying:

field1, field2, field3 as field4, field5

which, you can imagine; you are expecting certain data (and data type) on that field on you get something else and you mis a field

this syntax I believe is Ansi 92 SQL standard, so you can get the same problem on MSSQL, MySQL, Oracle, etc (our code ran fine in MySQL and the bug came up in Oracle because we had different data)

Wednesday, October 11, 2006

Tour Guadalajara - Aguascalientes

I will be traveling on vacations to Guadalajara & Aguascalientes (Mexico) from the 28 of Oct - 6 Nov (I might go to Mexico city a couple of days), if anyone is interested in meeting there and have a geek dinner, talk about development and geek crap, leave me a message

Tuesday, October 10, 2006

Filemon is to files what ____ is to debugging

if you answered Debug View, you get a star, if you don't know about this gem, let me give you a little introduction:

DebugView is an application that lets you monitor debug output on your local system, or any computer on the network that you can reach via TCP/IP. It is capable of displaying both kernel-mode and Win32 debug output, so you don't need a debugger to catch the debug output your applications or device drivers generate, nor do you need to modify your applications or drivers to use non-standard debug output APIs.

DebugView works on Windows 95, 98, Me, 2000, XP, Windows Server 2003, Windows for x64 processors and Windows Vista.

Basically, on your code (pretty much any language that uses the standard windows libraries to output debug), for example C#, you just put something like:

Debug.WriteLine("this is freaking awesome");

you run Debug View, then you run your program (web app or whatever it is you are debugging) and that's it! you get the output in a window much like filemon shows the file activity

brought to you from the guy who doesn't see problems, only solutions