Friday, February 29, 2008

[.NET] Strings gone wild

Are .NET strings evil? Not at all, but there is an exception to this: where in big packs strings can become very dangerous for performance of your app. Let's see why and how to avoid this.

System.String is a reference type implemented to behave as a value type; Strings instances of this type are IMMUTABLE : When a string is created if you modify it a new one is created and the old one is abandoned to the care of the garbage collector. For example with the following code we are creating 3 strings not just one, and we're keeping a reference to the last one that's been created:
string mySillyString = "hey";
mySillyString += " hey ";
mySillyString += " hey!";

This is fine if you are doing just a few of these operations, but if you are going down with massive string manipulation (maybe within loops), all the overhead associated with the string creation will cause your app to slow down, plus all the abandoned strings will pack together and go wild, giving an hard time to the garbage collector, and eventually feckin'up you app performances.

In such a case we should use a way to operate on strings dinamically. Without using any unsafe block of code, we can easily do this trying to use when possible string methods like Join, Concat and Format (the latter - as we all know - very useful). But the real rock star here is the StringBuilder: it sure carries a bit of overhead, so it might not worth it to use it just for a few string manipulations, but if you plan to do more than 10 operations you should use it as a rule. In case of fast machines, even more than 5 operations might justify the use of a string builder (as indicated on this MSDN paper: ).
Here an example of how to use the StringBuilder:

System.Text.StringBuilder myKickAssStringBuilder = new
myKickAssStringBuilder.Append("hey ");
myKickAssStringBuilder.Append(" hey ");
myKickAssStringBuilder.Append(" hey!");
myKickAssStringBuilder.Append(" hey Stoopid");
string myLonelyString = myKickAssStringBuilder.ToString();

All for today. Kick-Ass out there.

Wednesday, February 27, 2008

[.NET] Quick and Dirty guide to choosing between Struct and Class

Hey there, welcome to the .NET Butchering quick and dirty guide to choosing between Struct and Class. You probably already know that Structs are value types (everything on the stack) while classes are reference types (reference on the stack, actual allocation on the heap), and allocation on the stack is generally cheaper in terms of performance far small stuff and so on; if you didn't know you do now. If you need inheritance there's not much to think about since Structs do not support it, but if you don't just refer to the following bulletlist; if you can identify as FALSE one of the items on the list, then a bullet hits you and your doubt is killed: you go for Class. If you go through the bulletlist without being hit Struct is instead your way to go:
  • You are trying to represent a single value - let's say you're looking fo a way to wrap a built-in type like a string in order to make your code more readable (do not if you will to get the .NET Butchering Certification):

    Struct myBoringReadableType
    string value;
    //all your properties and crap

    Another good example could be the classic representation of a Point as a Struct (which I am not going to write here).

  • The size of your instance is gonna be less than 16 Bytes - If you plan to stuff your soon-to-born type with more than 16 Bytes (i.e. [4 int] - [2 double] - [2 int, 1 double] - [1 decimal] - [16 Byte] ... ) you're done thinking: go for a class. Moving such a fat-ass on the stack is definitely not worth it.

  • Your instance will be IMMUTABLE (or something like that) - If your type is a mutable one by concept, and you plan to change it all the time, you should go for a class.

  • You plan NOT to cast your instance to a reference type - In other words you don't plan boxing your potential struct. Simpler example of this is casting to Object.

That's it. Hope you find it Quick and dirty enough.

Tuesday, February 26, 2008

Regular Expressions: learning with an email regex

In computing, regular expressions provide a concise and flexible means for identifying text of interest, such as particular characters, words, or patterns of characters. Regular expressions are written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification.


So a regular expression is a way to identify a definite sequence of characters, useful in the search inside a long text or to validate a user input.
The "simplest" (are we sure??) example is the processing of an email address obtained by a user input from a, e.g., registration form.
Email adress are composed in this way:
  • alphanumeric characters mixed with (. and/or - and/or _) not in the start/end

  • @

  • alphanumeric characters and/or (. and/or - and/or _) not in the start/end

  • . followed by 2/4 letters

A valid representetion for this kind of regex sounds like this:

I'm not blind, this is surely not cool, but in few lines I'll explain you what this mess means.

Firs of all the ^ and $ characters stands for the start and the end of the searched sequence: they are mandatory, infact the regex ^Hello finds all strings that begin with Hello, while end$ those which ends with end, middle stands for sequences with one or more occurence of the word middle and at last ^just this$ match correctly only the just this string.

Square brackets [ ], in couple, stands for a set of characters, so for example the regex [12345] match every sequence that contains al least one number between 1 or 5, so are correctly matched 1hello and abcde51z2 but not 6a.
Of course, using a back slash \ you can use all protected characters for your sequences.
For numbers and letters, you can use the - to obtain a range of characters ([a-z] stands for the whole alphabet in small caps).

The + after a sequence means that that sequence should be repeated at least once, while the * states that that sequence can be present 0 or more times; moreover the ? means that the preceding sequence is optional, so it can appear 0 or 1 times.

In the above regex I have written a backslahed dot, because the . is a special character, meaning wathever character except for new line caracter (\n\r or \n\n or \r\n depending on your operating system). Infact the regex ^.+$ recognizes every strings, except one with only new lines or null.

Ending we can group together diverse sequences with round brackets ( ).

And now a brief explaination of the complex regex of an email addess:


beginning of the sequence


the first past begins with an alphanumeric character (one or more)

( [\._-]*[a-z0-9]+ )*

the first part can contain dots, underscores and dashes but they must be followed by alphanumeric characters (it can end with a non alphanumeric); moreover this kind of sequence could not be present (*), so the previous part can recognize alone a simple email address without non alphanumerical characters (such as


simply the @ character


the same as above


a dot followed by a simple sequence of small caps letters from 2 to 4 units


end of the sequence

Monday, February 25, 2008

[.NET] Nullable Types - Go forth and nullify

A very useful and not-so-common feature of .NET built-in types is they're NULLABLE. This feature has been introduced with .NET 2.0 and comes in quite handy when you wanna be able to tell if a value has not been assigned (e.g. this can be used instead of the old ugly
–2147483648 trick for int32 and so on).

in C# you can use either:

Nullable<bool> myNullableBool = null;

bool? myNullableBool = null;

If you declare a variable as nullable you can then use the HasValue method to evaluate wether tha value has been assigned or not, like this:

if (myNullableBool.HasValue)
{ /* My bool is an average true/false*/ }
{ /*oh My! My bool is NULL!*/ }

In VB the declaration syntax is slightly different, and actually it looks like shit (but just keep in mind the OMEN: we all -sooner or later- will have to deal with VB):
Dim MyNullableBool As Nullable(Of Boolean) = Nothing

Ok, now all you gotta do -if you feel like it- is ... go forth and nullify!

Thursday, February 21, 2008

[.NET] Built-in Types Performance Tip

Here's something not everyone knows about .NET framwork built-in types performance:
Quoting from MCTS Training Kit for Exam 70-536, .NET Framework 2.0 - Application Development foundation:

"The runtime optimizes the performance of 32-bit integer types (Int32 and UInt32), so use those types for counters and other frequently accessed integral variables. For floating-point operations, Double is the most efficient type because those operations are optimized by hardware."

Let's be honest: in average development conditions this won't make much of a difference. Depending on what kind of app your working on, tough, it means that -if you're not working on very constrictive memory conditions- even if you need just a float (4 bytes) to represent numeric values, you should go for a double in order to optimize your floating point operations, and so on.

It's just kind of nice to know this, so next time you'll meet a memory maniac -who's using short variables as counters- you'll have a concrete reason to laugh at him.

Tuesday, February 19, 2008

[ASP.NET] Difference between HyperLink and LinkButton

Wanna know the difference between the ASP.NET server controls HyperLink and LinkButton?
You're in the right place pal.

The major difference between the two - which will make you choose the one you need - is that The HyperLink will not PostBack your page to the server. It will post a simple request to the server for the URL you set as NavigateURL. The LinkButton works exactly as a normal Button but it looks like an HyperLink, so it will PostBack your page to the server allowing you to do your business (like setting variables at session level or doing some DB operation or whatever). Another (obvious) difference, which is more an imposed consequence of the above, is that the HyperLink doesn't have the OnClick event.

So, if you're asking yourself "which one should I use", here's the answer: if you need to do any operation with data that's on the page you will have to use a LinkButton (or a Button), but if you just need to redirect the user to somewhere else go for an HyperLink (You will avoid half roundtrip!).

E.g. you wanna avoid to have Button or LinkButton handlers with just this code:


which I do all the time, but - hey - I am a certified .NET butcher.


Thursday, February 14, 2008

[.NET, IIS] Failed to access IIS metabase

After one year of Apache, Java and PHP, last week I installed on my home server IIS on a different port (getting all together with Apache on port 80) just in case, I thought, I'd have decided to learn some finally I did.
[.Net, J2EE] A walk from J2EE to .NET: impressions and hopes was a preamble to this kind of experiment.
Anyway I left IIS with an orrifying HTML static page with a list of bullshit about me.

When I started learning I had no chance to try some of my new language scripts in my brand new web server, and I found that IIS didn't recognize the header of my .aspx page (XML parsing error)!

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="CurrencyConverter.aspx.cs" Inherits="CurrencyConverter" %>

I found it is a common problem: you should not install IIS before .NET framework, because it will lose the reference to the brand new .NET framework.

Solution (1): uninstall IIS and reinstall it (from Control Panel -> Install applications -> Windows Components -> IIS, of course in Windows XP).

That didn't work, even if after that IIS answered with a bad error:

It is a "Failed to access IIS metabase" error ... Oh my Gosh!!!
Google helped me again , in few searches.

Solution (2): it seems to be a problem of the .NET 2.0 version. You just need to reset all 2.0 registry keys, by moving to your framework directory (usually C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727) and executing:
aspnet_regiis -i
And finally all worked perfectly, with my super useful Currency Converter web application! Thanx uncle Bill!

[JAVA] How to Retrieve Application Path

This brief article will explain in a few lines how to retrieve the application path in a JAVA enviroment, both the official way and the butchers' way (just as we like!).

(1) The first way calls the System.getProperty static method passing the user.dir value:

String dir = System.getProperty("user.dir");

This way is simple but I found that sometimes (I'm not sure if Sun has fixed it) the returned directory could be slightly different from the one in which the application resides: this is because some times it gives out the directory in which the application has been started and not the one where your classes are.

This happened to me using Eclipse Plugins: usign several plugins, I needed a common directory to retrieve some XML resources, but the working directory returned was the one in which eclipse was running and of course not the same of the plugins one.

I fixed it using a ResourceBundle class. Actually that wasn't a bug, because most of libraries needed to run my plugins were inside Eclipse directory.

(2)And now the butchers' method! This method creates a fictitious file and retrieves its absolute path: I found that this method can overcome the problems using user.dir system property: currentDir = new"");
String dir = currentDir.getAbsolutePath();

Generally to retrieve your resources that are in a class directory (and maybe not in the working directory) you won't need the entire path, because we can use this method:
InputStream in = MyClass.class.getResourceAsStream("MyImage.gif");

So my advice is using paths of external directories and storing them into configuration files (such as .properties files) or calling resources without using absolute paths; moreover don't try to modify user.dir system property because it is set when your application starts and if you change it you don't know how will be the behaviour of all other classes.

Stay tuned!

Wednesday, February 13, 2008

5 Weirdest Google Searches to End up in this Blog

Hi there, this is not SEO bullshit, it's just my TOP 5 of Weirdest Google Searches to End Up in This (Development) Blog (gathered from google analytics):

(5) How we solved huge doprdown list loading - I would have never thought that someone could eventually look for this in these terms; what's the probability anyway that someone will try to stuff 10K records into a dropdown list as faced in this post --> How to fix Performance Problems - guidelines ? Sure we're living in a world of butchers. Anyway the answer they were looking for: you don't solve it, you just take off the page the damn thing. But the most interesting answer here is: why in hell would someone search in google for the words 'HOW WE SOLVED'? Jeez.

(4) hate Crystal Reports - Ok, I know Crystal Reports is not exactly popular (and I am not a fan myself --> 6 good reasons to hate Crystal Reports), but, again, I didn't know there was enough hatred out there to make people search for this. Some serious thinking to do here.

(3) PHP "Design Patterns" bad idea - This guy is a genious, whoever he is. Maybe he went "mmm everyone's talking about Design Patterns, let's check out on google if it's a bad idea to use'em with PHP", or maybe not, but anyway this search makes his way to the third position. He eventually ended up with the post Design Patterns you use without knowing them.

(2) how to fucking pass an xml document to fucking javascript - The guy is obviously screaming for help here; looks like someone is forcing him to pass XML to a fucking Javascript, but I wouldn't be surprised if they were brute-forcing him to use Javascript as well. Anyway he ended up with the XML Loading post and hopefully we made his day. How about this: how to friggin pass a fucked up const ref to shit language C# motherfucking function.

(1) butchering a human being - This is simply put the best way ever to end up in a development blog. What were they looking for and why did they come in? Maybe they did think this might have been a snuff development blog. Anyway, was someone somewhere about to be butchered? Gosh.

People sure are strange, developers sure are stranger than that.

kick it on

Monday, February 11, 2008

[.Net, J2EE] A walk from J2EE to .NET: impressions and hopes

Last night, just before bed time, I was reading a book [reference] about Component Oriented Programming using .Net framework. Surely the introduction that resembles OOP against COP was interesting, but after few pages I asked myself: "What is .Net?"
Its nothing more than the same stuff as J2EE.

Since my degree, about 1 year and a half ago, I'm currently programming in JAVA, using all that kind of stuff that J2EE represents, such as JSP with its libraries, servlets, portlets, DB integration, web services, and so on.
I've never thought about .NET because I haven't needed it and my company uses to program in JAVA: why should I begin with .NET?

Actually in this year and a half I found myself in trouble with all J2EE technologies, what is a web service and how to use it, how to make a web server run and configure it, what a servelt is, which portlet containers should I use (starting without any knowledge of what a portal container is), which libraries supports XML handling, which supports other stuff, and so on: this is all understandable regarding my total ignorance of J2EE, but this multitude of libraries slows me down even now, and usually what I need is not documented as it should be.
So it seems J2EE is hard for newcomers that, like me, have not many live links with J2EE experts (I learned all alone with so little help), and even forums don't help (great tutorial for real noobs or too much in depth for the beginning!!).

Still now I'm on a project developed using portlets, web services and servlets, but yesterday I was thinking about what happened about 1 year ago.
One of my friends was about to do an inteview, and one of the tasks before the "personal" interview, was to implement a simple web service using .NET framework: even without any knwoledge of web services and what it's behind, I managed to accomplish that task (and my friend has been hired!)... I don't tell you what such a disaster has been my attempts in JAVA (I dominated them, but how hard!).

And now I think: the aim of every enterprise is to make profit, so what if I managed to accomplish the same task in half the time?
Reading a book about ASP.NET lend from a friend (a +1000 pages book, from the bases to the most advanced features [reference]), I succeed to understand all topics presented...I haven't implemented anything yet, but now I know .NET Framework makes things easier.
Its learning curve is faster, maybe you need a greater effort at the beginning: that's different in JAVA, infact coming from a general C/C++ knowledge and XML undestanding, you can easily implement a JSP that print out "Hello World!", but as you proceed on the road of J2EE consciousnees, things gets harder and harder.
Instead in .NET you need some time to orientate yourself about technologies used (the base language, C#, web services, web page layout creation, DBs, and so on), but as soon as you have enough knowledge of the framework, building an application will be straighforward.

And moreover, one of the greatest benefits of using JAVA is its portability and platform-indipendence, but I always programmed in Windows, using Microsoft ways of representing files, web servers configured in "windows-mode", so all efforts may have been useless, and learning .NET I would have found time to learn anything else, and increse productivity.

Ending, .NET and J2EE offers the same kind of malicious machineries and the first seems to be more programmer friendly.
I wonder if you, the reader, leaving away every "f**ck the system" ideology and open source nerdology , agree with me.
I just hope that I haven't wasted my time...
And so I ask: where do you think is the future of component programming?

Saturday, February 9, 2008

[.NET, VC++] 6 good reasons to hate Crystal Reports

Hi all, here I present my short list of good reasons to hate Crystal reports. This is basically about why working with Crystal Reports is the definitive punishment for every developer. After many fights with the Business Objects support people - we eventually became friends - I am tired of hoping the thing will actually start working as supposed to, so here goes the list (They had it coming):

(6) If you jump onto an ongoing project, if they produce some reports, they are using Crystal Reports.

(5) When your users go print some Crystal reports, if you're not extremely lucky, they got a number of blank pages in between or at the end of the report. And you get the complaints. It's important to underline here that the only reason you are using Crystal reports is to get easily printable reports (e.g. You usually have your users to select which pages to print from the print preview, discarding the blanks, which sucks).

(4) In older versions of Crystal reports (8,9) there is a maximum number of sub-sections for a given "details section" you can programmatically access. If you exceed that maximum number, there's no way in hell you can programmatically edit the options of the exceeding sub-sections. Moreover, before you discover this and you need to set some sub-section option (e.g. make it invisible) if you try to get the section code from the section index you'll keep modifing the options of some other section, as -once you exceed the maximum- the section codes you get back restart from the first sub-secion in loop.

(3) The simpler the task you're up to looks, the more blood you'll have to sweat.

(2) The excel export of a report is the worst thing ever in the history of computing, often looking either like an abstract work of art or a scrabble game.

(1) Once you report is finished, every time your boss wants something new in it (e.g. a new column) you're screwed.

Crystal Reports is the most frustrating and fragile technology you will be ever called to deal with. Why should someone bother learning how to use Crystal reports if with the same effort you can produce better results from scratch?

Tuesday, February 5, 2008

[.NET] Top 5 Visual Studio Hotkeys

Ok, to cut a long story short, these are the 5 Visual Studio Hotkeys I would bring with me on a desert island (if I had to go there with just my Viz, mylaptop, and an electrical generator):

(5) CTRL+SHIFT+B: Build - This is quite banal, you use it all the time so even if it ain't so sweet as hotkey it manages to enter my top 5. If you don't know this, man, you're out. Bread and butter (like the good old F7 in Visual Studio 6).

(4) F12: Go to definition - it's kind of nice sometimes to pull it in front of people: you just lose them. The move.

(3) CTRL+F6: Next IDE Window - Ain't is sweet? No more Window->Windows then selecting from that ugly list on that cheap dialog. Lightspeed!

(2) F5: Start with Debug - This is a well known 2-in-1 hotkey: you start the debugger and whenever you hit a breakpoint you just push it again to get going. Can't live without.

(1) F9: Toggle/Untoggle Breakpoint - This is my favourite: I just can't get enough of those red dots. Addictive.

(BONUS) CTRL+Tab: Tab Between Windows - Really useful. Not as immediate as CTRL+F6 but you can choose which window you wanna open, and in VS2008 this one lets you see a preview of what's in the documents. It performs as CTRL+F6 in VS2003 and VS6. Secret Weapon.

So, those were my favourite 5 Viz hotkeys; all of them work in all VS versions unless specified differently. Keep the good butchering up and share your hotstuff (keys included)!

Update [09/04/08] - Commenting/Uncommenting HOTKeys:

This are really helpful hotkeys I had to cut off from my top 5 even if I use them a lot:
COMMENTING -> select (with mouse or keys) the block of code you want to comment and then go with the following keys chord: CTRL+K to select - CTRL+C to comment what you just selected.
UNCOMMENTING -> select (with mouse or keys) the block of code you want to uncomment and then go with the following keys chord: CTRL+K to select - CTRL+U to uncomment what you just selected (must be commented to work).

Sunday, February 3, 2008

[BookReview] Beginning C++ Game Programming

BookRef: Beginning C++ Game Programming
(Amazon book ref)


Comment: Here we go again with the same old "game programming" trick. Let's face it: this ain't about beginning game programming, this is mostly about beginning C++. YES, we have a few console games in the end of the book ( like hangman or BlackJack ) but all the examples are console apps and the most of the coding is driven by statements like "imagine a spaceship" or "imagine a monster" while explaining types, structs, pointers, classes and so forth. A fair title would've been: "Beginning C++ (with console crippled games as examples)". With its not-so-academic buddy-to-buddy approach the book ain't so bad as C++ reference for absolute beginners, but stay away if you're looking for a tough game pogramming guide.

Favourite Quotes:

"Now, when you first hear the term overloaded, you might think it's a bad thing—the operator is about to blow!"

Friday, February 1, 2008

[Javascript] Change HTML "class" and "style" attributes

It seems trivial, and it is, but if you are going to write a cross browser script, you can find that sometimes (i.e. always) most used browsers, Firefox and Internet Explorer, work in different ways...damn it!
One of those troubles is the class attribute of a generic HTML; I found that in IE you cannot simply set a class attribute to your own HTML node, but you have to set a className node with the list of your CSS classes.
This is THE code:

/* find out which is the browser */
var isIE = (window.ActiveXObject)?true:false;
var isMozilla = (document.implementation.createDocument)?true:false;

/* the name of the attribute, depending on the browser */
var attributeClass = (isIE)?"className":"class";

/* set the attribute */
htmlNode.setAttribute(attributeClass,"classX dummyClass");

Moreover there is also another strange behavious as for the style attribute; if you want to set the whole CSS text of a node's style (and not a particular sub attribute), this is the syntax:

[UPDATE 01 feb. 2008 - 17:50]
Max and other users made me notice that "else if(isMozilla)" may exclude other
kind of browser, not allowing a wide "cross browsering". Thanx guys!

var styleString ="font-size:10px;";

if(isIE) ;
else //if(isMozilla)

I assure you: writing cross browser script is a really butchery task! Try if you don't believe me!