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;
pathWithFileName=System.Reflection.Assembly.GetExecutingAssembly().Location;


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:

pathWithoutFileName=System.IO.Directory.GetCurrentDirectory();

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:

pathWithoutFileName=System.IO.Forms.Application.StartupPath;

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 =
DocumentBuilderFactory.newInstance();

//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(
filePath);

}catch(IOException ioe) {
ioe.printStackTrace();
}
}
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)
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader reader = new StringReader(xml);
InputSource source = new InputSource(reader);
return db.parse(source);
}
catch(Exception e){
e.printStackTrace();
}

}

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);
serial.asDOMSerializer();
serial.serialize(document.getDocumentElement());
return stringOut.toString();

} catch (Exception e) {
e.printStackTrace();
}
}

...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){
try{

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){
e.printStackTrace();
}
}

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 = "http://www.w3.org/2001/XMLSchema";
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) {
e.printStackTrace();
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 del.icio.us 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 del.icio.us links.

solution: copy-paste the following wherever you want:

<a href='' id='delicious'>
<img alt='Add the butchers to your Del.icio.us!'
height='15'
src='http://images.del.icio.us/static/img/delicious.42px.gif'/>

</a>
<script language='javascript'
type='text/javascript'>

var currentURL = window.location;
document.getElementById('delicious').href =
"http://del.icio.us/post?url=" + currentURL;

</script>


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 ( http://support.microsoft.com/kb/166389 ) which won't help you to solve it. I discovered the solution by empirical method (read RANDOM trials).

Talk Ya'll soon.