Thursday, January 31, 2008

[.NET] How to Retrieve Application Path - quick reference

Problem: You need to retrieve the application path but You don't remember (or you never knew) how to do it.

Solution: there are at least 3 well-known ways of ways to do this in .NET, let's see them in detail:

(1) the System.IO.Path way - more code but you always get what you're looking for; let's look at simple sample:

You start by using System.Reflection to get the application path comprehensive of the file name, either this way:

string pathWithFileName;

Or this Way:

pathWithFileName=System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.Replace("file:/", "");

Then you pass the pathWithFileName string to System.IO.Path.GetDirectoryName:

string pathWithoutFileName;
pathWithoutFileName = System.IO.Path.GetDirectoryName(code_Base);

(2) the Sytem.IO.Directory way - it's easier to type (since you'll be copy-pasting like a good butcher I don't see the catch) and to get but there is a severe drawback:


What's the severe drawback? Well if you previously changed the Current Directory using the SetCurrentDirectoy method you'll be getting that result instead of the the directory from where your assembly is being executed. If you're the only one working on your app, maybe that's ok, but if we're talking about huge banks of code... up to you, butcher.

(3) the System.Windows.Forms.Application way - if you're using windows forms you can use the StartupPath property:


Enough - have a good butcherin' day; You bet I will.

Tuesday, January 29, 2008

Thinking in Generic

Hi Folks,
Can't wait to hear more about Generics and Templates fine-very-not-butchery feature of modern languages?
Well, sorry to disappoint you but you've got the wrong track (I'm not such expert of that, btw, raise their hand those who created their own class using generics in the last week).
I'm gonna talk instead of how people (even honest butchers like us) can try to be as generic as possible while designing their application.
I wanna introduce my personal thumb rule:
Don't make any assumption if noone will risk his goddamn neck without it.
It may sound like an easy one, but in my experience this is, in the 80% of bad designs I've seen, the main root cause.
Sometimes I've been asking around questions like:
  • "Why is that field of a so specific type ?"
  • "Why you DON'T need to have such information on your class?"
  • "Why these two classes do not have a common ancestor?"
  • "Why these properties do not belong to a super?"
Problem arises when the answer is: "I don't need that in my case" i.e., "I can assume this in my case".
Well, even a butcher like me could still ask you WHY?
OK, I've got it.
YOU think that you can make that assumption but, even if it's true (so far), why should you?
What is the catch? Saving manicure to your hands or 30 minutes from your work-clocking?
I've got it, you are saving those 30 minutes to beat Lou on Guitar Hero (yes I know you are a geek).
But, if you can't find any other reason to make those assumptions, you should just make to yourself (and to those who'll handle your design after you) a favour.
Don't make them.
And this is the reason why: there are very good chances in the air that you would be bitching yourself within a month (or that your colleagues will be bitching you) for that, believe me.
It's just an honest advice from a butcher, you don't think it's worthless right?
That's all for today, I've gotta finish writing some ugly (very butchery indeed) nested loops...

Monday, January 28, 2008

[JAVA] Easy management of XML content (Serializing, Deserializing, XSD ing, XSL ing)

problem: actually it is not a problem, it si more likely a collection of tips to manage a DOM document (using Xerces and Xalan open source library from Apache Group): parsing an XML file, serialization and deserialization, aplying an XSL or validating against a defined XSD. You don't need a degree to discover how to do it, but as you have thousands of thousands of classes inside that libraries, without Google I found it hard.

solution: ok, where is the beginning?
What we'll do first is a simple reading from a text file. Xerces gives you a simple way to open an XML file, by using:
 private Document parseXmlFromFile(String filePath){

try {
//get the factory
DocumentBuilderFactory dbf =

//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();

//parse using builder to get DOM representation
//of the XML file
return db.parse(

}catch(IOException ioe) {
Sometimes anyway you have only a string that contains your XML data (maybe got from an HTTP request or a webservice), and you just want to deserialize it into a Document object:

private Document deserialize(String xml)
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader reader = new StringReader(xml);
InputSource source = new InputSource(reader);
return db.parse(source);
catch(Exception e){


Ok, I know, it's quite the same of the previous code; the only difference is that now you take your data from a StringReader object rather then from the path of the file. I also have added two properties to the builder, one that ignores comments and the other that ignores useless white spaces (for example formatting spaces).

And what if you want to obtain the string equivalent to the content of a Document? Don't be scared, there is a solution:

private String serialize(Document document){
try {
OutputFormat format = new OutputFormat(document);
StringWriter stringOut = new StringWriter();
XMLSerializer serial = new XMLSerializer(stringOut, format);
return stringOut.toString();

} catch (Exception e) {

...and voilĂ  your string is right there!

And what if you need to apply an XSL style sheet to your wonderfull XML ?
No way of trouble, just use this simple code:

public String transform(Document xml, String urlSchema){

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer =
tFactory.newTransformer(new StreamSource(urlSchema));

StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(xml),
new StreamResult(writer));

return writer.toString();
catch(Exception e){

Ending dear fellow butcher, if you want to validate your XML data against a XSD definition, just copy&paste this code:

public boolean validate(String xml, String schemaURL) {
try {
String schemaLang = "";
SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
Schema schema = factory.newSchema(new StreamSource(schemaURL));
Validator validator = schema.newValidator();
StringReader reader = new StringReader(xml);
validator.validate(new StreamSource(reader));

return true;
} catch (Exception e) {
return false;

This method returns true/false depending of the result of the the validation process; moreover you can catch, outside the method, the exception (if it is a DOMParserException or a SAXParseException) to have an idea of why xml content is not valid.

I showed how to use DOM Classes to manage the whole XML content of a specific file/string, without discovering all the whys and becauses of each line; I'm pretty sure you can find several other ways to do what I coded but this fits my usual needs.

Sunday, January 27, 2008

[Javascript, DHTML] Easiest way to add post from Blogger

problem: There's no way in hell you can find any ready-to-use pluggable html snippet to add the current page of your blogger blog (current version) to the user's links.

solution: copy-paste the following wherever you want:

<a href='' id='delicious'>
<img alt='Add the butchers to your!'

<script language='javascript'

var currentURL = window.location;
document.getElementById('delicious').href =
"" + currentURL;


I am lazy, so I was looking for something to copy-paste into the html and amen. After an hour or so of roaming without finding anything usable as-it-is, I decided my laziness was costing me more than actually making the thing myself (what the heck). So I did it. This technique obviously will work with any of the linksharing networks (digg and others) or whatever, but the difference is I could find ready-to-plug snippet for the others. Maybe it'll save some precious hours of laziness to some other copy-paste butcher.

Friday, January 25, 2008

[VS6] Cannot find [ file path ] (or one of its components) - when opening dsw Workspace

Problem: you get a "Cannot find [ file path ] (or one of its components).Check to ensure the path and filename are correct and that all required libraries are available." error when opening a Visual Studio 6 workspace file.

Solution: delete OPT and NCB files with the same name of your workspace (you find them in the same root folder of the workspace - back them up for safety if you feel so), they'll be re-generated as soon as you open the workspace.

This is one of those nasty ones you could spend a couple of hours on without having a clue. Those two kids just get corrupted sometimes/somehow (especially if you move the project, do some changes on some other machine/environment and then go back to yours). I tried to google it but no luck; just found the microsoft error page ( ) which won't help you to solve it. I discovered the solution by empirical method (read RANDOM trials).

Talk Ya'll soon.

Thursday, January 24, 2008

[ASP.NET, SQLServer] How to fix Performance Problems - guidelines

Scenario/Problem: You have an ASP.NET (framework x.x.) application and some pages are taking forever to load up.

Guidelines: Follow these steps:
  1. If using DBs: Are you indexing your DB? If not you should consider it (up to 30% speed increase, depending on you DB design)
  2. Check your controls ViewState: are you sending unuseful stuff back and forth? If you're generating/populating dinamically some control you should disable its viewstate. Use ASP.NET trace to check controls viewstate size (DRAMATIC speed increase, depending on your app)
  3. Look at your T-SQL stored procedures: are you abusing temporary tables or dynamic SQL execution? If so it's not a good idea, use SQL profiler to check for stored procedures recompilation-execution time. If you don't have stored procedures you probably should use them
  4. Look at your code behind: are you round-tripping more than you need? Are you sharing open connections to DB when you can (use SQL Profiler to spot how many connections you are opening and closing)? Are you mis-using some controls (huge drop down list can cause major delays)? Use ASP.NET trace to locate hot-spots and long latencies.

Real World Case: I don't feel much of a butcher these days: I was working on a web app [ASP.NET 1.1, SQLServer2000] developed by someone else and i realized butchery is a fine art and I still got a long way to go.

My main task was to speed things up. It was taking 18 seconds to load a single page, with an average amount of data (nothing major). I first tried to put some indexes on the DB (1), which didn't have any, but not having at the time much experience on DB indexing I put my life in the hands of the Enterprise Manager Index Tuning Wizard (painful experience), knowing it would have butchered my DB, but hopefully just a bit, speeding up things for me in the end. It happened, but from 16-18 seconds the guilty page went down to 12-13, which was something but not what I was hoping. The wizard claimed a 28% speed increase: true, but not enough.

After this delusion, I went on inspecting the trace (enable it setting Trace="true" in the top page declaration, or @ app level from web.config) and I noticed KBytes of useless stuff being sent back and forth as ViewState (2). The app had a coulple of user controls dynamically generated every Page.Load, so I just disabled the ViewState for those (EnableviewState = "false") and the app speed dramatically increased (50% in my case). Good, but still it was taking 6-7 goddamn seconds to load. I also took off the SmartNavigation="true" page property: it might be the pre-AJAX coolest thing but it's deprecated and it saved me almost 2 seconds: down to 5.

I started looking at the code, spotting un-necessary open/close operations for connections that could've been shared, loads of butchery in there, of the finest quality, and I noticed ALL the stored procedures were being recompiled (3) because of a massive use of temporary tables and dynamic SQL, even when non necessary (if the stored procedure is being recompiled there's no gain speed, ergo no point in having it as stored procedure). I didn't really want to change the code, a work of art is a work of art, so I decided to roam a little bit more through the trace looking for hot-spots.

I noticed the page was laoding pretty fast looking at the trace latencies. I put some Trace.Warn("HereandThere") but there was nothing major, the whole page was taking only around 1 sec to process and render, but I was still seeing the content trhough the browser after 5 secs. Then again a look at the ViewState and controls sizes and it happened: I saw a 900KB dropdownlist (4). Turned out that drop down was being populated with more than 10.000 record (yes > 10^4) and the browser was obviously taking forever (around 3 secs) to load it. Took that out (set up a popup with only the dropdown for that selection) and EUREKA: loading time went down to 1-3 secs, which considering shitty server and crappy network is more than acceptable (compare it with 18 seconds if you don't agree).

As I said, there was (and there is) a lot more to change and optimize in this app, as per stored procedures code and code behind, but the art is art and I wanna keep this mess untidy as long as I can, to inspire me and to remind me what butchery truly means.

Monday, January 21, 2008

[BookReview] Learning ASP.NET 2.0 with AJAX

BookRef: Learning ASP.NET 2.0 with AJAX (


Comment: Starts with the right foot and finishes with the wrong one. Enjoyable at the beginning, this O'Reilly book loses nerve ongoing; moreover, the last chapters are jokes-free (what's an O'Reilly book without jokes?). The cover says "with AJAX" but the book covers AJAX.NET just briefly, so if you're looking for an AJAX training this is not the book for you. If you know VB.NET/C# and you're looking for something to introduce you to the ASP.NET world (including AJAX) this might be the right option. Again, without knowing a little VB.NET/C# the reading wouldn't make much sense.

Favourite Quotes:

"The first use of the term as an acronym for “Asynchronous JavaScript and XML”
was by Jesse James Garrett in February 2005. Garrett thought of the term
while in the shower (if you must know), when he realized the need for a shorthand term to represent the suite of technologies he was proposing to a client (who, we are assured, was not in the shower with him)."

[ASP.NET] Page.MaintainScrollPositionOnPostBack

I recently discovered this property you can set to "true" in the page header declaration (or set programmatically if you're not ok with static declarations) in order to maintain scrolling state on Postback. It's really useful and I managed somehow not to notice it's been introduced since framework 2.0.

Obviously AJAX.NET is a better option, but if you have an old app and you don't wanna bother or don't have the time to enable AJAX ... here you go.

Thursday, January 3, 2008

[.NET] Events and Delegates

Lately I've been reflecting about Events and delegates in the .NET framework: to my understanding event is actually not a type, just a keyword.

Quoting from MSDN:

The event keyword lets you specify a delegate that will be called upon the
occurrence of some "event" in your code. The delegate can have one or more
associated methods that will be called when your code indicates that the event
has occurred.

You can specify your own events, but in order to specify events and handle them you should:
//1) declare a delegate:
public delegate void myEventHandler(object sender, AlarmEventArgs e);
//2) "declare" an event on your delegate
//(read the first sentence from the quote now):
public event myEventHandler myEvent;
//3)Wire event and SomeMethod through the event delegate
//(At some initialization stage)

myControl.myEvent += new myEventHandler(SomeMethod);

You can do this without explictly declaring a delegate and event if you are using .NET built in controls, because they already have their own events and delegates (EventHandler - which uses a generic System.EventHandler delegate) declared so you can just wire an event to SomeMethod using the generic delegate called EventHandler, like this:

button.Click += new EventHandler(this.Button_Clicked);

Where button is the name of the control, Click is the event and Button_Clicked is the name of your method.

This stuff is not-so-easy-to-catch, so hope it might help someone.