Monday, December 29, 2008

Testers are cool at prime numbers

A software tester, a software developer, and a project manager are told: 
“All odd numbers are prime”
The Developer says:
“Let's see, 3 is prime, 5 is prime, 7 is prime - looks like it‟s true”
The Project Manager says:
“Let's see, 3 is prime, 5 is prime, 7 is prime, 9 is prime, 11 is prime –looks like it‟s true.”
The Tester says:
That's silly, nine is a non-prime odd number - looks like it's bullshit”

I recently heard this very sad anecdote while attending a lecture about Software Testing. 

Everybody (except maybe a Test Manager) knows the developer would look up prime numbers on google before even trying to answer.

Anyway - here's a good resource about odd prime numbers humour.

Wednesday, December 24, 2008

[Poll] How many development feeds can you take?

To all of you information addicts out there - I was wondering how much information can people take.

At the moment I have 104 active subscriptions on my google reader, mostly development stuff, and I can barely keep up. I do not really read all the stuff that gets posted - I scan with my eyes and if my fast forward algorithm gets some keyword that I am interested in I go back and read the post.

If you add twitter to that there's enough for an overdose of information (but twitter is more about what people are doing and you don't really try to keep up if you don't wanna go mad).

How many feeds do-you/can-you follow (assuming you have a day-job)? Check-out the poll.

P.S. Happy Christmas to all the butchers out there from .NET Butchering 

[POLL RESULT]














kick it on DotNetKicks.com

Friday, December 12, 2008

Recession will (hopefully) wipe SEO off the earth

I am no economics nostradamus or anything, but it's likely in my opinion that recession will bring people back to the real thing, and wipe SEO scums who lure between marketing an IT off the internet (and hopefully the earth).

I know there are loads (well, maybe not that much... ) of respectable professionals out there who offer SEO as part of their services - and they'll probably survive, but If I already believed that  "if you do SEO for a living, you will be out of business or irrelevant in 3 years" (quoting SEO is dead) recession seems now to be only accellerating things from this point of view.

I already stated my views on SEO in a previous post, but if you have a look at this link you'll notice that this guy's English is way better than mine and his approach to SEO deconstruction is way less simplistic; we're basically saying the same thing though: SEO is piss-easy. Even if I worked in marketing, I'd never invest solely on SEO because it's a soap bubble that's gonna explode in people faces sooner or later. 

Go ahead - tell me I am an idiot. 

Wednesday, December 10, 2008

[T-SQL] How to boost 'joined' Update Performance

Time for some real boring stuff.

The first thing people are tempted to write when they have to run an update on a table picking stuff from another table is probably something like this:

--method 1: nested select
--around 15 mins to execute on 100.000 records
UPDATE myTable
SET myTable_field = (SELECT myOtherTable_field
FROM myOtherTable
WHERE myOtherTable_someID = myTable_someID)

This way the nested select will run once for each record you're updating (100k times in my example) and you'll get shit performance.

Alternative to this are:

--method 2: update FROM more than one table
--around 45 secs to execute on 100.000 records
UPDATE myTable
SET myTable_field = b.cache_VmiID
FROM myTable a, myOtherTable b
WHERE b.myOtherTable_someID = a.myTable_someID


or, more intuitive:

--method 3: JOINED UPDATE
--42 secs to execute on 100.000 records
UPDATE myTable
SET a.myTable_field = b.myOtherTable_field
FROM myTable a join myOtherTable b
on b.myOtherTable_someID = a.myTable_someID


Execution times assume you're clearing SQLServer cache with fucking DROPCLEANBUFFERS (without clearing cache method 2 and 3 take about 4-5 secs).

kick it on DotNetKicks.com

Thursday, December 4, 2008

[.NET] A Microsoft race

My Microsoft Visual Studio 2008 is screwed. Cannot start the application. After trying to fix it with the troubleshooting guide from Microsoft without any joy it looked as if the best solution was to use the canonical uninstall/reinstall pattern. A poll for you all: is it gonna take longer to uninstall Microsoft Visual Studio 2008 or to download the 3gigs ISO from Torrents? After 30minutes it looks very tight, who's gonna win?

[SQLServer2005] computer localhost does not exist on the network

This really bugged me out.

Talking about useful error messages from SQL Server, After installing SQL Server 2005 whatever edition on Vista and setting up a few DBs on management studio I tried to access SQL Server Surface Area Configuration and I got the following genial error message:
"computer localhost does not exist on the network (...)"
this is some epic bullshit, obviously followed by some other useless crap which I won't mention.

This obviously gave me no clue - so just out of curiosity I tried to open SQL Server Configuration Manager and I got another happy error message which makes even less sense:
"Cannot connect to WMI provider"
WTF is this supposed to mean? I have no clue what a WMI provider is. Anyway - the only resort I was left was good old Google. So I started googlin' like crazy and I found some crazy SOAB of an MVP on a msdn forum thread who was trying to convince some indian guy to reinstall Windows and SQLServer. 

I kept looking till I found something that did the trick: 



Apparently the problem is due to some SQLServer installation fuckup with some MOF files.

If you run this in your cmd line it should solve it:
C:\Program Files\Microsoft SQL Server\90\Shared>mofcomp "C:\Program Files\Microsoft SQL Server\90\Shared\sqlmgmproviderxpsp2up.mof"


kick it on DotNetKicks.com

Wednesday, December 3, 2008

[.NET] How to sort DataTable

There's no way to automatically sort a DataTable after it's populated.

A way around this is to sort the DefaultView of the DataTable (or any other DataView associated with the DataTable).

You can achieve this using the Sort property of the DataView. This is a string which specifies the column (or columns) to sort on, and the order (ASC or DESC).

myDataTable.DefaultView.Sort = "myColumnOfChoice DESC";

The DefaultView can now be used as datasource for stuff or to do whatever you need it for.

Friday, November 28, 2008

[T-SQL] How to get length of TEXT field

To calculate the lenght of a TEXT field the LEN function used to calculate the length of VARCHAR fields won't work. 

You need to use the DATALENGTH T-SQL function:

SELECT DATALENGTH(myTextField) AS lengthOfMyTextField



kick it on DotNetKicks.com

Tuesday, November 25, 2008

[SQLServer] Error 3205: too many devices specified for backup or restore only 64 are allowed

Problem: restoring a backup on SQLServer I get the following error:
[Error 3205: too many devices specified for backup or restore only 64 are allowed]

Solution: you're probably trying to restore a SQL2005 backup on a SQL2000 instance. There's no backward compatibility for backup operations bewteen SQL2005 and SQL2000. Installing SQL2005 will make the error go away (I know - it sucks).

I recently came across the cryptic error message in subject. At first I was puzzled - then google helped me understand the problem was not my lack of sweet SQLServer skills...

Sunday, November 23, 2008

Learning SQL with Ganesh - Part 1 of ?


I found (and shared) this desperate help request yesterday on my google reader - I felt a burning desire to help the poor guy and I immediately followed the link to StackOverflow, but folks over there already edited the heck out of the original question.
Anyway this is what I'do to find AND delete duplicate rows on a table (with Identity):

DELETE
FROM MyTable
WHERE ColumnID NOT IN
( SELECT MIN(ColumnID)
FROM MyTable
GROUP BY Column1, Column2, ..., ColumnN )
If you don't have an identity on the table you can add it then drop it when you're done.

Anyway - I obviously up-modded the guy and went ahead to have look at other questions from him and - guess what - I found a pair of pearls (the previous one was pretty OK besides the original title):

Probably weirdest SQL questions ever asked, but anyway, even if I HATE SQL, I tried to find answers anyway ('cause that's human nature - I guess).

To get the top 10 rows without sorting I'd probably do some rocket science:
select top 10 *
from MyTable
-- duh!
but then, if random order is required (?), maybe something like:
select top 10 *
from MyTable
order by NEWID()
To get the last 5 rows without sorting I'd rather go with:
select top 5 *
from MyTable
order by ColumnID desc

But what if you don't have an ID? What does without sorting mean? In doubt, I'd probably do something like the following:

select top 5 *
from ( select *
from MyTable
order by newId() desc)

Which is some crazy shit and without doubt doesn't make any sense.

kick it on DotNetKicks.com

Friday, November 21, 2008

Fags and The Military Got My .NET

I use to read Monsters Got My .NET posts. I subscribed to the feed on google reader and I very much enjoy the concept behind this blog, being a fan of horror movies and a programmer.

Posts on this blog are usually quite verbose - it usually takes me a while to figure out what the heck they talk about (maybe 'cause I am a bit slow), but the content is quite good and honestly I can't wait to see the horror movie mini-poster on the next post. 

I particularly enjoyed a recent post (it was pretty straightforward and enjoyable compared to the intellectualoid standard) and decided to leave a comment that went something like:
This is a very nice post, short enough to be readable and useless enough for me to be able to enjoy it.

I really like the concept behind this site - I'll probably start another blog and call it "Fags and The Military Got My .NET", instead of horror movies I'll post military posters with subtle homosexual hints.
The author didn't appreciate my comment - meant to be a joke - and canceled it mentioning in another comment that some retard posted an inappropriate comment forcing him to moderate his blog.

At this point I had no other chance left than creating Fags and the Military Got My .NET for real:


Saturday, November 15, 2008

How to get and format date in a bat file

Sooner or later everyone needs to mess up with some batch file Voodoo for some reason - often to pipe the output of some console application into some kind of log file. At this point you'll probably want to put a timestamp on the log file - but you need to reformat the standard date to elminate slashes and stuff. This is how you do it (depending on your operating system):

REM US Operating System: set yyyymmdd=%date:~10%%date:~4,2%%date:~7,2%
REM EU Operating System: set yyyymmdd=%date:~6,4%%date:~3,2%%date:~0,2%

This formats the date into a variable called yyyymmdd (pretty self-explanatory, uh), which you can use later in our lame script in you log file name (or whatever you need it for - In this case I am piping stuff into a log file):

REM EU Operating System
set yyyymmdd=%date:~6,4%%date:~3,2%%date:~0,2%

ECHO myConsoleApp output: >> myLog_%yyyymmdd%.txt
myConsoleApp.exe >> myLog_%yyyymmdd%.txt

This stuff sucks - but I couldn't find the date formatting thing - pretty cryptic, uh? - anywhere on the web (I stole it off a collegue of mine who's kind of a batch files guru) so it might be useful to people.

Thursday, November 13, 2008

How I feel about SQL


I really tried hard to make friends with SQL, I even got a few books, and O'Reilly ones (they all sucked, but - hey - it's SQL we're talking about). I eventually came to cope with my feelings - if you gotta hate something, SQL ain't too bad a pick. Ain't too bad for poor SQL either, there's a whole lot of awesome indian dudes who love it to death. 
Maybe it's because I've been too lazy to install intellisense plugins for SQL Management Studio so far, maybe because of the cryptic error messages ("there's a fuck up around line 345" - jeez, Javascript is easier to debug) or maybe just because that's the way it is, you gotta hate it. 

P.S. There's been a lot going on lately - mostly going crazy with a solution that builds fine manually but fails to build through CruiseControl.NET - but I've been a lazy ass and didn't post anything about it. You can read about it here and here for now.

Monday, November 3, 2008

New Warnings World Record?

Just wondering if this might be the Visual Studio Warnings World Record:

1493 is a pretty darn good number - I am getting it from a monster solution composed by something like 65 projects (.NET, COM, MFC/C++ ... a bit of everything).

Tried to Google up "Visual Studio Warnings World Record", but no luck. It'd be nice to make it to the Guinness Book of World Records for something so useless. 


Sunday, November 2, 2008

Let that boy copy paste (with SQL2005 and Excel)

I heard Papa tell Mama
Let that boy copy paste from SQLServer2005 to Excel
It's in him
And it got to come out

John Lee Hooker - Boogie Chillen (1948)

Being a software engineer - I pretty much hate messing with DBs.

Nonetheless, more often than not, even the brightest designers - such as myself - are called to get their hands dirty with some SQL or moving some data around when the team's DB guy (usually indian) is badly sick at home.

I remember how painful it was the first time I had to understand with SQL2000 how to export to excel a simple resultset from a select - must have wasted a full afternoon of frustration trying to do that a few years back. 

A couple of months ago I was shocked in discovering that with SQL2005 you can just select all and copy/paste a resultset to excel. This means that if you have to import/export some records you don't need to mess with import/export wizards and all that comes after. Shrinking to 3 clicks (select all - copy - paste) a 5 minutes painful procedure. 

Forget about TRY CATCH, CLR support, and all that fancy stuff, copy/paste to/from excel is my favourite SQL2005 new feature (ok - this sounds something like 3 years late, but it's not what this post is about).

DB purists might not like it but copy/paste is "de way 2 go".  


kick it on DotNetKicks.com

Saturday, October 25, 2008

[Blogger] How to dinamically change Blog Title

You can dinamically change your Blogger Blog title to whatever you want (in this case you're changin it into 'NEW KICK-ASS TITLE') using the following Javascript snippet:


var myKickAssScript = "document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'NEW KICK-ASS TITLE'";
setTimeout(myKickAssScript, 2000);



We have to set a timeout in order to wait for the title element to be injected by the blogger engine. You can put this js code in the script element that's in the head section of the markup (you can edit it from 'edit HTML' section on your blog settings). 
If you put the snippet (passed as string to the timeOut function above) at the bottom of the page (or as event handler for the onLoad event) you obviously don't need to set up a timer.


It'll work as long as they decide to keep the page markup as it is now.

P.S. check-out my NEW KICK-ASS TITLE

Friday, October 24, 2008

[C++] convert std::string to const char * (and back)

Kind of a lousy-ass post but Straight to the point (with UNICODE on):

#include <string>
using namespace std;

//..

//from std::string to const char*
string originalStr("Bunny Colvin Kicks Ass");
const char* cnstCharPtr = str.c_str();

//the other way around
string convertedStr(cnstCharPtr); //as simple as this
 
I found myself googlin' this up a number of times and I always forgot everything soon enough since I don't use it often. I decided to post it as a reference for myself and to increase chances to find an answer for anyone else who might be looking for it.

Cheers

Wednesday, October 22, 2008

The Unmentionable NECRONOMICON of WinApps (BAD Code is Language Independent)

I am working on a MFC app internally referred as the unmentionable NECRONOMICON of WinApps. This thing is a dying beast composed by an indefinite number of dlls: it seems put together as an ad-hoc example of the so-called DLL HELL. It compiles and builds by magic and by magic only. The thing is so scary no-one ever attempted touching it for 7 years or so. There are stories about the last guy who tried to fix a few bugs: he went crazy and left the company with no reason (OK, he just left the company). 

Anyway, most of this thing is coded in C++ and MFCs (except a bunch of cryptic COM components in VB6 and stuff which hopefully I'll never have to touch).  After having a thorough look at the code I can say that YES, the app is way far from being mainteinable, but - surprise - it's not because of C++. Same stuff written in C# would scare eggs out of (SCRUM) chickens.

Loads of people seems to hate C++, because it's error-prone (...), verbose, kinda cranky and not that cool anymore. Most of them probably don't even know about copy-constructors and destructors otherwise they'd hate C++ even more. I agree with most of this complaints and no-one would ever dream of developing a brand new WinApp today using MFCs. We got away from that and now we can focus on making cool apps, not just "working" ones.

Getting to the point, the fact that C++ apps do not write themselves seems to be ignored - people tend to forget one of the basic laws of programming: BAD code is language independent.

P.S. Wish me luck, I need it

Sunday, October 19, 2008

Software Development Methodologies Zoo


[Waterfall - 1970]
The waterfall model is a sequential software development process (...) in which development is seen as flowing steadily downwards (like a waterfall) through the phases of requirements analysis, design, implementation, testing (validation), integration, and maintenance.
You can't stop a waterfall - meaning that if you're in the middle of a project and requirements change ... well ... let's say you're in troubles.


[V-Model - late '80s]
The V-model is a software development process which can be presumed to be the extension of the waterfall model. Instead of moving down in a linear way, the process steps are bent upwards after the coding phase, to form the typical V shape. The V-Model demonstrates the relationships between each phase of the development life cycle and its associated phase of testing.



This is a zombie model, it's dead but plenty of ISO and CMM fanatics out there think V-Model is still pretty cool. V-Model is indeed a very good methodology for high-ceremony organizations for its ability to give management a sense of false security.


[Cowboy Coding - wild west]
Cowboy Coding is a term used to describe software development where the developers have autonomy over the development process. This includes control of the project's schedule, algorithms, tools, and coding style.

In an ideal world, this would be my favourite. Whenever I start my own company I am pretty sure I'll adopt and formalize Cowboy Coding [yippy kayay!].

[SCRUM - early '90s]
Scrum is an iterative incremental process of software development commonly used with agile software development. (...)
Scrum is a process skeleton that includes a set of practices and predefined roles. The main roles in Scrum are the ScrumMaster who maintains the processes and works similar to a project manager, the Product Owner who represents the stakeholders, and the Team which includes the developers [chicken and pigs!].
During each sprint, a 15-30 day period (length decided by the team), the team creates an increment of potential shippable (usable) software. The set of features that go into each sprint come from the product backlog, which is a prioritized set of high level requirements of work to be done.


Conceptually born in early '90s, SCRUM started being widely adopted 10 years later. It's like the model farm of AGILE software development with ScrumMaster to coordinate chicken and pigs. All you need to know is pigs do all the work.

[ICONIX - late '90s]
ICONIX is a software development methodology which predates both the Rational Unified Process (RUP), Extreme Programming(XP) and Agile software development. Like RUP, the ICONIX process is UML Use Case driven but more lightweight than RUP. Unlike the XP and Agile approaches, ICONIX provides sufficient requirement and design documentation, but without analysis paralysis. The ICONIX Process uses only four UML based diagrams in a four step process that turns use case text into working code.
A principle distinction of ICONIX is its use of robustness analysis (...). This process makes the use cases much easier to design, test and estimate.

ICONIX basically combines an AGILE approach with a robustness oriented low-ceremony design. This Process carries the strictly necessary amount of weight to still ride fast. This is the process I use at the moment, you can read more about it on this post.

[Extreme Programming - XP]
Extreme Programming (XP) is a software engineering methodology prescribing a set of daily stakeholder practices that embody and encourage particular XP values. Proponents believe that exercising these practices—traditional software engineering practices taken to so-called "extreme" levels—leads to a development process that is more responsive to customer needs ("agile") than traditional methods, while creating software of better quality.
Proponents of Extreme Programming and agile methodologies in general regard ongoing changes to requirements as a natural, inescapable and desirable aspect of software development projects; they believe that adaptability to changing requirements at any point during the project life is a more realistic and better approach than attempting to define all requirements at the beginning of a project and then expending effort to control changes to the requirements.
XP is all about speed, and we all like speed if it means no documentation. Biggest drawbacks of this approach may be problems like feature creep and scope creep - moslty due to lack of persistent reference.

Thursday, October 16, 2008

[SSIS] How to remotely run a DTSX package from bat file?

Short answer (or at least the conclusion I came to after a fair amount of research  - and plenty of hair pulling): you can't .

Long Answer: I started from this cmd, which works like charm locally:


DTEXEC /DTS "\File System\MY_PACKAGE_NAME" /SERVER MY_SERVER_NAME /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING V


If you try to use the same cmd remotely it will miserably fail with some nasty timeout.

After a bit of googling it looks like it is impossible to run DTEXEC cmd remotely (it needs to be run locally - remote execution apparently is not supported).

To overcome this limitation the following method seems to be broadly implemented:
  • set up a SQL job to run the DTSX package
  • set up a Stored Procedure to run the job
  • use isql command line in a BAT file (remotely executed) to run the stored procedure on the relevant SQL instance (with SQL credentials and not machine credentials)
Might work - but kinda sucks.

Wednesday, October 15, 2008

[.NET] Why are Exceptions not Checked in C#?

Going from Java to C#, I've been stunned by the absence of  the "throws" clause in the declaration of a method, in which you want to throw a particular exception.
Actually it hasn't caused me so much pain, but the knowledge at compile time of the possibility that an exception could be thrown sounded very useful to me.
Asking to the StackOverflow community, I found out Java is one of the few programming languages where exceptions are "caught" at compile time.
The philosophy behind C# is that what is useful about exceptions is not handling them, but mostly cleaning resources, implementing the IDisposable pattern (The trouble with Checked expcetions).
If you know that a particular method can throw an exception, you also know what it does and how to handle it, otherwise you will handle a generic exception, without need to specify it at compile time; moreover handling exceptions is something that comes near the caller of a method reather than the method itself, so there is no need to specify a chain of "throws" declarations, and that is so useful in versioning, because adding a new exception (or removing an old one) doesn't require a refactoring of your lib.
It is worth noting that C# supports the <exception> tag in the documentation section, with which the compiler informs you that an exception (whose type is anyway checked for existence) can be thrown, without any further constraints.
If you have other issues or different opinions I'd like to hear them.

Good butchering!

Friday, October 10, 2008

ICONIX Process Rocks

Today we talk about my favorite software development process, so-called ICONIX.
This should probably give an answer to the few dinosaurs who like going around saying that AGILE is an excuse for not having a well-defined process (they probably think the V-Model still rocks - good lads).

ICONIX adopts a subset of core AGILE techniques and it is a behavioral requirements (Use Cases) driven process. The ICONIX process aims to be as low-celebration as possible carrying as little documentation as possible through iterations - in order to allow you to easily keep it up-to-date (this is a big difference from other AGILE processes, as XP, which aim at carrying no documentation at all).
For fans of TDD (Test Driven Development), it has been proved that ICONIX can be easily paired with the latter: http://www.springerlink.com/content/k15l318vq1013057/

Here's a practical overview of the process:
  1. Quick Draft of Functional Requirements (in theory throw-away)
  2. Quick Definition of a Domain Model (identify entities and classes)
  3. Model Use Cases on the base of previous steps (This is what drives development)
  4. Draw a throw-away robustness diagram for each use case (to understand relations between your classes)
  5. Draw a Sequence Diagram for each use case (here you'll understand which methods you really need)
  6. Model your test-cases on the use cases
  7. Implement
  8. Test
At each step you review your work as a whole updating your domain model (it's impossible to get it right first time) and adding comments on your use cases. By the end of step (5) you end up with ready-to-implement classes and logic with just little documentation to maintain if you re-factor or change anything. The following is indeed the only documentation you need to carry through iterations:
  • Use case diagram
  • Sequence Diagram for each use case
  • Test case diagram (or test plan)
If you need to add features, you add new use cases and follow the whole process.
 
In my experience the ICONIX process works regardless of the size of the project. In a medium-large project you just split the implementation of features in short iterations in an AGILE fashion. It is worth underlining that the big difference between most extreme AGILE processes and ICONIX is that you do keep documentation up-to-date, you don't just throw it away after each iteration. This is possible because the process aims (again) at keeping very light-weight documentation.

Thursday, October 9, 2008

[JAVA] Calendar Months Start from Zero

I don't have time to make a big deal out of this but please tell me which month is the 12th one in the year. I was so stupid to think it was December. Thanks to the JAVAAPI guys I got enlightened. The 12th month is Janaury cause the count starts from 0, it goes to 11 and then starts over again. Grand job to the java.util.Calendar guy!

Thursday, October 2, 2008

[.NET] How to Programmatically Create and Access Custom ConfigurationSections

.NET app.config and web.config are powerful instruments to store simple key value pairs and connections strings.When you need to store config data in some specific format and key value pairs are not enough you can use Custom Configuration Sections as they are not complex to use (unless you need a fairly complex section):

1) Define your custom section:

public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("LastName", IsRequired = true,DefaultValue = "TEST")]
public String LastName
{
get { return (String)base["LastName"]; }
set { base["LastName"] = value; }
}

[ConfigurationProperty("FirstName", IsRequired = true, DefaultValue = "TEST")]
public String FirstName
{
get { return (String)base["FirstName"]; }
set { base["FirstName"] = value; }
}

public CustomSection()
{

}
}



2) Programmatically create your section (if it doesn't already exist):

// Create a custom section.
static void CreateSection()
{
try
{

CustomSection customSection;
// Get the current configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe");

// Create the section entry
// and the
// related target section
if (config.Sections["CustomSection"] == null)
{
customSection = new CustomSection();
config.Sections.Add("CustomSection", customSection);
customSection.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
}
}
catch (ConfigurationErrorsException err)
{
//manage exception - give feedback or whatever
}

}



Following CustomSection definition and actual CustomSection will be created for you:

<configuration>
<configsections>
<section name="CustomSection" type="ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowlocation="true" allowdefinition="Everywhere" allowexedefinition="MachineToApplication" overridemodedefault="Allow" restartonexternalchanges="true" requirepermission="true">
</section>
</configsections>
<customsection lastname="TEST" firstname="TEST">
</customsection>
</configuration>


3) Now Retrieve your section properties:

CustomSection section=(CustomSection)ConfigurationManager.GetSection("CustomSection");
string lastName = section.LastName;
string firstName = section.FirstName;


This is all good stuff - nice and easy as you can see.

P.S. This post orginally appeared on this  StackOverflow link, but since I wrote it I thought it would do no harm to recycle my own rubbish here.


kick it on DotNetKicks.com

Friday, September 26, 2008

Jimmy Sole the Renown PHP Programmer is Back Online

Check out this great post from DIGG:
[Jimmy Sole had decided to take a break from blogging for a while. Now he is back and beginning to blog about PHP and will soon be blogging about many other web related programing tasks and perhaps some gaming and photography. Check out JimmySole.com today.]

Apparently Jimmy Sole changed his mind and for some reason he's not going to post any great PHP article in the near foreseeable future.

.NET Butchering is trying to launch an initiative to convince him to change his mind. If you're not sure just yet wether you wanna support the initiative or not my advice would be to go have a look at Jimmy's website and you'll make up your mind soon enough. If you decide to endorse Jimmy Sole please leave a comment on his blog.

read more | digg story

Thursday, September 25, 2008

[.NET] Generics Perfomance Myth (and Tony Northrup VS Wendy Sarret)

According to Microsoft, Generics are faster than casting (even in absence of boxing/unboxing).

Tony Northrup - co-author of MCTS 70-536: Application Development Foundation (which BTW totally sucks, a review will probably follow) - states in the same book the following:

I haven’t been able to reproduce the performance benefits of generics; however, according to Microsoft, generics are faster than using casting. In practice, casting proved to be several times faster than using a generic. However, you probably won’t notice performance differences in your applications. (My tests over 100,000 iterations took only a few seconds.) So you should still use generics because they are type-safe.


I haven't been able to reproduce such performance benefits myself (and I am, as a Certified .NET Butcher, way more reliable than MCTS books) - so I'd say the performance gain is "supposed" more than "significant", unless someone is able to prove it. Until that moment .NET Generic amazing performance will remain a myth.

If you know something more than me about this - please share.


P.S. BTW - isn't Tony Northrup real HOT (I'd rather date him over Wendy Sarret)?

kick it on DotNetKicks.com

Sunday, September 21, 2008

[.NET vs Java] Event Handling: Are you sure pure OOP is always the simplest?


After a long time I'm again here for another post!
I will talk about event handling, focusing at first on .NET way to supply it, and then spending 2 words about the Java style.
What I want to talk about is delegates and how are they used...I know old good Giovacchia has already spoken about them in a previous post (here) but I wanna talk about them again.
Why?
I'm leaving for a while the Java world and walking through the .NET Framework (I have to take some Microsoft Certifications, 2 or maybe 3 exams in just 1 month and a half...sounds crazy but it's my task in the short term): this means I have to study, as for now, 2 book of about 1000 pages each one.
I'm not taking part in the war between Open Source Multi Platforms Java Conding and Mama Microsoft Windows-Platform Framework yet, but in this path toward the MS certifications I will try to catch what's good and what's not in both frameworks.
At a first sight (I'm about at the half of the first book) 2 years of experience in Java programming has helped me a lot, but I stopped a while learning about delegates.
I don't want to explain what actually they are (Giovacchia in his post said it perfectly), let's just say delegates are a kind of function pointers, and you have to subscribe a delegate to a particular event in order to make it running when that event is raised.
Because my memory is so short term (could it be Google's fault?), during the reading I made a simple schema to remember which key words to use when declaring a delegate and rasing your own event.


namespace HereIsMyDelegateNamespace{
. . .

public delegate void MyEventHandler(object o, System.EventArgs ev);

. . .

public class MyClass{
. . .
public event MyEventHandler MyEvent;
. . .

/* this method raises an event */
publlic ReturnType RaisingMethod()
{
System.EventArgs ev = new System.EventArgs();
. . .
MyEvent(this,ev);
. . .
}
}
}

namespace ConsumerNamespace{

public class Consumer{

public static void Main(string[] args)
{
. . .
MyClass m = new MyClass();
m.MyEvent += MyEventHandler(m_MyEvent);
. . .
/* from now on we can call a method
* or make an action which causes MyClass to
* raise the MyEvent event */

m.SomeMethodThatRaisesTheEvent();
. . .
}

public static void m_MyEvent(object o, System.EventArgs ev)
{
. . .
/* handles the event */
}
}

}


You have to remember few things:


  • The signature of the delegate has to be the same of your own handling method

  • The signature of the delagete has to contain 2 parameters: the first one is an object reference, that refers to the object that launches the event, and the second one must be a subclass of System.EventArgs (there are a lots of them implemented for the common events)

  • You can subscribe to an event using the overloaded operator += but you can also unsubscribe by using the -=

  • For common applications, you won't need to raise yourself an event, but just supply a method and subscribe it to the event (the method, as said, has to have the same signature of the needed delegate)


And what about Java?
Learning Java I actually never had the need to write down some code to remember how Event Handling works.
Why? There are no delegates, in the sense you need to specify an entire class as the delegate for that event. What does it happen when you need to subscribe to an event?
In that situation Java is more OO then .NET, indeed you only use your Handler Class (such as MouseListener class, but for the common events, e.g. such as Mouse and Keyboard, you have at your disposal tons of ready-to-use classes) to manage the event. In this scenario you call directly by the object that throws the event, an addXXXListener() or removeXXXListener(), and inside your class, in which you surely have an array of potential listeners, when you want to raise the event, you have to iterate manually by calling all the needed methods of the listeners subscribed.
IMHO Java is straightforward to the OOP, but you need more code, and .NET allow you by using delegate and event keywords not to think to the propagation of the event. Moreover, in .NET you won't need to specify an entire class to handle the event, bringing to a more concise code style.

I'm not as experienced in .NET as I'm in Java, so maybe in few weeks I will post the exact opposite kind of opinion, but as for now I'm feeling better using C#, as it seems it has taken the good in Java and brought it to a more powerfull level (I'm refering to the whole framework ofcourse and not to the language itself).


kick it on DotNetKicks.com

Saturday, September 20, 2008

[.NET] How to send debug text to output (or file)

If you landed here because you want to send debug text to the output console do not worry, it's piss-easy:
//////////////////////////////////////////////////////////
// you can choose between this:
// first par: "a description of the importance of the message"
// second par: text 'category'
Debugger.Log(2, "Test", "this text in the output console - 1");
//or this
Debug.Write("this text in the output console - 2");
//or this
Debug.WriteLine("this text in the output console - 3");
//or this
Trace.Write("this text in the output console - 4");
//////////////////////////////////////////////////////////


Obviously you have to build in debug mode to see any output (if you do not know this you're a really lousy developer && human being).

If you feel sophisticated of you have some obscure reason to send your debug text not only to the output console but to a log file, you do like the following:
//////////////////////////////////////////////////////////
// clean-up the mess
Trace.Listeners.Clear();
//create new listener
DefaultTraceListener yourListener = new DefaultTraceListener();
//add new listener to trace
Trace.Listeners.Add(yourListener);
//set log file path
yourListener.LogFileName = @"log_test.txt";
//send text to console && log file like this
Trace.Write("butchers will be butchers"); 
//////////////////////////////////////////////////////////

In the case above you can use the Debug class the same way you use Trace (so you could write Debug.Write instead of Trace.Write and so on). Difference between the two is that Trace is implemented in Release build as well while Debug only in Debug mode (will be ignored if you build in Release).

P.S. Lately I've been to lazy to properly format the code - suck it up


kick it on DotNetKicks.com

Monday, September 15, 2008

How long can a developer survive without Google?

How many times did your boss come up with "can we do X?" and you didn't have a clue about it but answered "Yes, no probs at all - consider it done"? You were probably thinking "WTF - I have no idea about this", and first thing you do when you're back and safe at your desk is googling the damn thing up. We can do stuff like that only because developers are merging into a collective intelligence through internet + Google.

Mortality rate (= getting the axe = being let go = being fired) would be dramatically higher between developers if Google wasn't there to keep them from falling apart (or reverting to slow and painful alternatives) every time they have to learn something new (meaning almost every day unless you are a Reporting Engineer - if so good luck with that).

I am not saying nothing new here, just that today being able to quickly find answers on Google is - if not the most important - at least the second or third most important skill of a developer/software engineer.

Said so, I tried a little experiment: I kept track of how many times I look up work-related stuff using Google during an average day of work (9 to 5 let's say):

10:05 - looked up C# 'as' operator to refresh a few concepts

10:48 - looked up COM on C# sample (there's always something wrong - if you do suck)

12:30 - looked up CoCreateInstance COM function

14:30 - looked up Abstract Factory Pattern sample (no good - Factory is enough for me)

15:55 - looked up T-SQL reference for 'collate' statement

16:40 - looked up osql to run .sql scripts from SQL through xp_cmdshell (BAD idea!)

So turns out on an average day I looked up 6 times on Google - none of those things were crucial for what I was doing but I needed to shed some light on some doubts or explore possibilities I wouldn't have had otherwise. To answer the headline, I start craving for Google after a couple of hours. After a day I would probably start to freak out. After a week or two I'd probably quit (OK , maybe not, maybe I'd switch to Yahoo before quitting). I am not able anymore to count all the times Google really made my day- and I have to say that this is the reason why I opened this blog, to participate in this awesome process of merging my experience based knowledge with the average guy out there who's probably doing the same.

In my experience sometimes people are ashamed of looking up stuff on Google - well they shouldn't be since today is more the 'look up on google skill' is more valuable for a developer than any other static skill and you don't have to waste your time trying to memorize APIs or looking for perfect references 'cause google is the perfect reference (if you know how to filter all the crap - obvious). Sometimes it is astonishing to see people that revert to Google (or the web in general) only if all other means fail after a few days of blood-sweating quests (meaning all the books on the shelves and everyone in the company have been consulted) - it is (most of the times) the other way around guys.

I won't go as far as saying that I couldn't do my job without google (did I already do that?) - but certainly I couldn't be as productive without.

OK - enough boredom for today.

P.S. if you don't agree I'd like to hear why.


kick it on DotNetKicks.com

Thursday, September 11, 2008

[.NET] How to create a shared folder in C#

To cut a not so long story even shorter, this can be done with the following snippet: 

//////////////////////////////////////////////
using System.IO;
using System.Management;

//...

//First create your directory
DirectoryInfo myDir = new DirectoryInfo(@"C:\shared");
myDir.Create();

//...

// Create an instance of ManagementClass
ManagementClass managementClass = new ManagementClass("Win32_Share");
// ManagementBaseObjects reference for in and out parameters
ManagementBaseObject inParams;
ManagementBaseObject outParams;
inParams = managementClass.GetMethodParameters("Create");
// Set input parameters
inParams["Description"] = "Shared directory";
inParams["Name"] = "shared";//this needs to match with folder name!
inParams["Path"] = @"C:\shared";
inParams["Type"] = 0x0; // Disk Drive
// InvokeMethod call on the ManagementClass object
outParams = managementClass.InvokeMethod("Create", inParams, null);
// Check outcome
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
   //Unable to share directory
}
////////////////////////////////////////

The above solution is quite sweet and seems to work perfectly - for further details see the article where I originally found the snippet to share the directory: http://www.sarampalis.org/articles/dotnet/dotnet0002.shtml

Man - do I suck!?!


kick it on DotNetKicks.com

Thursday, September 4, 2008

[.NET] C# 'is' operator

The C# 'is' operator looks like a boring little fella at first, but once you get to know it you will eventually appreciate it - it checks if you can safely cast an instance of an object to a type:
///////////////////////////////////////
//example 1
string testStr = "";
object obj = testStr;

//..somewhere else in your code
string newStr;

if (obj is String)
{
   newStr = (string)obj;
   //go nuts with your string
}
///////////////////////////////////////


It is important to understand that since the 'is' operator is just checking if it is safe to cast the following expression will always be true for any type:
///////////////////////////////////////
//example 2
string var = "whatever";

if(var is object) //<-always true (for var of any type)
{
    //always executed 
}
 /////////////////////////////////////// 
The above is always true for any type because everything in .NET inherits from object. This means you can safely cast to object (box) value types for example, and even if quite obvious it helps understanding how the 'is' operator works. 

You can obtain a result similar to example 1 using GetType and typeof if you're resolving types down to an inheritance line with this code: 
/////////////////////////////////////// 
//example 3 
string testStr = ""; 
object obj = testStr; 

//..somewhere else in your code 
string newStr; 

if (obj.GetType().Equals(typeof(String))) 
   newStr = (string)obj; 
   //have fun with your string 
/////////////////////////////////////// 
But here you're just checking for equality and not for safe casting in general, as you do with operator 'is' (i.e. example 2 with GetType Equals typeof returns false - because GetType returns string does not equal object). For an insight on GetType and typeof see this post.

Closing - a probably more efficient way - depending on your taste - to check if casting is safe is to go ahead and cast using the operator 'as', like this:
///////////////////////////////////////
//example 4
MyClass test =  new MyClass("read between the lines");
object obj = test;

//..somewhere else in your code
MyClass newTest = (obj as MyClass);

if (newStr != null)
{
   //do CRAZY stuff with YourClass
}
///////////////////////////////////////

For more details about the 'as' operator have a look right here.

kick it on DotNetKicks.com

Wednesday, September 3, 2008

[SQLServer] SQLServer2008: Workgroup VS Standard

You might be in doubt when choosing between SQLServer2008 Standard or Workgroup edition (most people rule out the Enterprise edition since it's 7500 € or so) - here's a list of the differences bewteen the two (in red most relevant).

Reporting Services memory limits : unlimited for Standard - 4GB for workgroup

Standard features not supported by workgroup:

Standard algorithms
Data mining tools: wizards, editors, query builders
SQL Server Analysis Services service
SQL Server Analysis Services backup
General performance/scale improvements
SSIS Designer including VSTA scripting
Integration Services service, wizards, and command prompt utilities
Basic tasks and transformations
Log providers and logging
Data profiling tools
Additional sources and destinations
: (Raw File source, XML source, DataReader destination, Raw File destination, Recordset destination, SQL Server Compact destination, SQL Server destination)
Business Intelligence Development Studio
MDX edit, debug, and design tools
Standard performance reports
Plan guides
Plan freezing for plan guides
Policy-based best practices
Multi-server policy-based management
Heterogeneous subscribers
Database mirroring
(witness only)
Failover clustering (very limited in workgroup)
Dynamic AWE
Failover without client configuration
Automatic corruption recovery from mirror


The Workgroup edition apparently includes 5 CAL licences (a license is around 130 €) - I see that as the only possible reason you might go for it since the price of the piece of software itself is very similar (around 600 € for the workgroup against 750 for the standard).

For more details http://msdn.microsoft.com/en-us/library/cc645993.aspx

kick it on DotNetKicks.com

Tuesday, September 2, 2008

Google Chrome Drawbacks (for lazy developers)

If as a user and software engineer I am nothing less than aroused by Google Chrome release after reading the brilliant comic (Google Chrome Comic) they are using as presentation, as a mere nitty-gritty developer I am somewhat worried about the fact that we'll have to bitch with yet another browser in order to produce cross-browser web apps.

It might seems a little obtuse (or plain lazy) - but yet at the moment if you are developing a ASP.NET application and you set as a system requirement IE x - no one complains.
On the other end we all now that if you start requiring something different than IE (i.e. Firefox or Google Chrome now) complaints will flood back like crazy.

Hence you have two possible ways to go:

1) develop your ASP.NET web-app optmized for IE (short for 'we didn't even bother running it even once on Firefox or anything else, so if it breaks it is YOUR problem')
2) develop a cross-browser application (short for 'we developed it on Firefox and que serà serà')

Option 2 could now assume a hell of a new meaning (I am talking stuff like adding yet another 'if' to all your javascripts) - possibly nothing will change since the google guys are sound guys and the webkit blah blah blah and the new javascript virtual machine (V8 - that has a specific API which can be included by other browsers and so forth) hell yeah.

Anyway apart from complaining regardless (I am a developer - it's my nature), I am looking forward to put my hands on the thing and assist to a new chapter of Browser Wars (coming soon on your machines and portable devices).

kick it on DotNetKicks.com

Monday, September 1, 2008

[.NET] Difference between GetType and typeof

GetType and typeof come in useful when you need to mess with objects types before casting and so forth.

The difference between the two is the following:
GetType is a method of the object class - from which everything inherits in .NET - while typeof is an expression that operates on a type (same as you declare variables with).
While GetType takes into account inheritance and gives you back the actual Type of your instance at runtime - typeof just resolves the type into a System.Type object (jeez) at compiletime.

To cut a long story short: GetType extracts the Type from the object - typeof extracts the correspondent System.Type object from a type (declaration).


Have a look @ an example and it will be clearer:
////////////////////////////////////////////////
Type myType;
//the following blocks of code are equivalent
{
myType = typeof(int);
}

{
int i;
myType = i.GetType();
}
/////////////////////////////////////////////////

Good stuff - ain't it? No, it ain't - this post is child of absolute boredom.

kick it on DotNetKicks.com

Friday, August 29, 2008

[.NET] Difference between casting and 'as' operator in C#

This is an easy one - but it can be useful to someone so here it comes:

The 'as' operator in C# is a tentative cast - if it's impossible to cast (types are not compatible) instead of throwing an exception as the direct cast the 'as' operator sets the reference to null.

So you can have something like:

MyClass myObj = new MyClass();
MyOtherClass myOtherObj = myObj as MyOtherClass;
if (obj != null)
{
//cast was successful
}
else
{
//a little bit of a fuck-up
}

The correspondent in VB is the TryCast (usage is the same as DirectCast but it doesn't throw any exception).