Eclipse 3.2 vs Netbeans 5.5

How times change.... I'm now into Java land evaluating IDEs... Seems like yesterday when it looked like I would be doing .NET and C# winforms till I pass out!

  • Configuring offline javadoc API help:
Just get the offline docs zip at http://java.sun.com/docs/index.html
Then it was a matter of configuring the IDEs to bring them up at a keypress.
In Netbeans it was just a matter of unzipping them to a docs folder under your jdk directory. Press Alt + F1 and you're on your way.
In Eclipse it was a whole lot of work, you have to unzip the archive as above. Then open up project properties (Project Menu > Properties). Change the javadoc setting to use the offline doc folder path instead of the http:/// online help setting . See the attached image to see where it is hidden ... definitely not meant for idiots like me. Then press Shift+F2 to bring up in an external browser or F1 to bring it up in an IDE view.
+ 1 to Netbeans !!!!




ASP.NET 2.0 membership provider not working with SQL 2005

I faced a peculiar problem while deploying my Web application.
I developed the application using Express editions. This tied me to SQL Express behind the scenes with some magic default connection strings. The machine for deployment had SQL 2005 installed and no SQL Express. I used the security controls to set up the login-to-website flow quick n easy and now they barfed like there's no tomorrow on the target machine.

To cut a long story short, there are some mods required to get the default SQL membership provider to work with SQL 2005. Here's the dope on that...

http://weblogs.asp.net/bsimser/archive/2005/11/20/431029.aspx
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/ConfigASPNET_SQL.asp


Thanks both you guys... this was driving me nuts.

Die! Die! Excel, you Fiend !

I was recently drafted to write an ASP Site that documents on the server to create a "status" page. Given the affinity towards Word and Excel for people in QA, it was no surprise I was soon wrestling with Excel to read some stuff from an xls file.

I got the site running with some major hiccups like not finding type definitions for objects returned by some functions. In the end I ended up using Reflection to get at the custom properties in the excel document.

Now to my horror, I found that the task manager showing zillions of Excel instances quietly ganging up on my web server. So I asked around and I was amazed at the reputation Excel had carved up for itself. I first suspected COM References... I have a negative bias towards unmanaged code of any nature.
First stop: Guidelines on how to release Word or Excel if it is not shutting down gracefully
http://support.microsoft.com/kb/317109/

Still no luck! Next I was lucky to have my logic in a separate DLL that I was test driving via NUnit. This allowed me to make the interesting observation that a test run did not leave Excel instances running. That means my code is good. It has something to do with that ASP.NET 2.0 web page. I did a quick scan and found I had hardly any code in there to cause this. More googling and finally it dawned on me

I will post the gems I found after a week of manic activity

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when run in this environment.

WARNING: Office was not designed, and is not safe, for unattended execution on a server. Developers who use Office in this manner do so at their own risk.

http://support.microsoft.com/kb/257757/
http://support.microsoft.com/kb/288368/

The answer seems to be that Office applications were not built for scalabilty or running in a multi-threaded environment. So until Office 2007 hold on to your horses !!!

I ended up not creating multiple instances and settling for an instance that is stashed away as a static variable, which seems to slowly eating up memory. But this is an internal web site, so I don't mind.... I think ASP.NET will restart the app if the memory consumed goes above a certain limit.

Integrating NCover code coverage with your CCNet CIS

I managed to read one more chapter in the CIS story. This one is called ‘Integrating NCover with CruiseControl’.
The CruiseControl documentation page has most of the help you need.
CruiseControl.NET/Doc/CCNET/Using%20CruiseControl.NET%20with%20NCover.html
But NCover has always been a tricky one. If that page worked, I wouldn’t be writing this piece here.

Ingredients:


  1. A CruiseControl.Net (I use v1.0.1) build server running all green. And you better be TDDing that code too…J.

  2. NAnt I use this (v 0.85) to build my code.

  3. NCover I use version 1.3.3 since that’s the only one there that still works with VS2003. Pick up 1.5.x for VS 2005.


Once you have all that in place, it’s time to get this started. To run NCover we need to add a task to our build file. It differs from the one on the CCNet doc page in the placement of the quotation marks. I found my solution by watching the Nant Build log on the CCNet dashboard

<exec program="l:\tools\NCover\ncover.console.exe" commandline="/w AT_Bin\Debug /c &quot;L:\Program Files\NUnit_227\bin\nunit-console.exe&quot; TestBearings.dll" />


Save that one. Now move onto the ccnet.config file. Add this to the tasks block of your project element there. We need this so that code coverage report is merged to the Nant build output file.

<merge>
<files>
<file>L:\BuildFolder\AT_Bin\debug\Coverage.Xml</file>
</files>
</merge>


That’s it. Save and start a build. Hopefully that’s a green. Click on the green build link on the Recent Builds tab. Click on NCover report. You should be seeing something like this.


Now to find out why I don’t have 100% coverage J
Just that you know it is possible, If you have a different stylesheet for NCover results, rename and replace the stylesheet named

CruiseControl.NET\server\xsl\NCover.xsl
with your own. Hit F5 to refresh your browser and you should see the new results. Here I have use the default xsl that comes with NCover – although the CCNet version is more to the point. The one I mentioned in my earlier post is the best. I got an unexpected console listing at the top … but no big deal.


How to make your .NET application disappear from the Task Switch (Alt + Tab) list

I kinda stumbled on this via a bug-report.
Basically if you have your WinForm (e.g. a modal dialog) properties
• BorderStyle set to FixedToolWindow or SizableToolWindow
• AND ShowInTaskBar set to false

When the form is up and you hit Alt+Tab, the task switch won't have your application in the list. You live you learn...

Task: Write an automated test for a detected deadlock

Here is a simplified version of the problem case

public void PingLicense()
{
lock(this)
{
CheckAuthorization();
}
}

public void GetLicense( out License obCurLicense)
{
lock(this)
{
//talk to non-threadsafe 3rd party lib to query the license info
}
}

CheckAuth() function does a GetLicense and raises events to notify others if a change in License occurs.
Ping License is called by a helper thread via a Timer object (every minute )

So here is how the deadlock occurred, if I remove the license h/w device midway. On the next PingLicense call, helper thread acquires the lock on the object and raises the event for everyone to switch to Unauth mode.
One of the subscribers is the UI ( to enable/disable UI elements ). *Any changes to the UI in .NET must be done on the thread in which the UI was created*
So the event handler requests a switch to the UI (Main) Thread. In the event handler, there is a call to GetLicense(). DeadLock !!!
UI thread is stuck requesting a lock for the object (which PingLicense currently holds). Ping License won't relinquish the lock since the event handler hasn't returned.

Agreed that it seems dumb now. But Hindsight is always...

Now the fix is - PingLicense doesn't need a lock block ( a result of a mindless strafing run inserting lock blocks ) . Removing that solved it.
But no code change without a failing test... Also it kinda bugged me that this got thru my AT Test store.



My Attempt

After some discussion with the nice folks on the TDD list, here's my AT (took 10 mins with Console Output verification)

[Test]
public void Test_CR9672_PollingThread_ShouldNotAcquireLock_BlocksEventHandlers_OnGetLicense()
{
LicTestHelper.WriteLicenseConfig(LicTestHelper.LocalHL_LIC_INFO);
LicenseManager.Instance.EvApplicationAuthorized += new EventHandler(On_LicMgr_EvApplicationAuthorized_CR9672);

DynamicMock obMockHL = SetupDynamicMockHLWrapper();
//... set up a mock to mock out the license hardware

GObjectSpy.CallPrivateMethod( LicenseManager.Instance, ReflectionStrings.S_LICMGR_PINGLICENSE_METH, new object[]{null} );
//Code will block here if a deadlock happens.
// If test completes, the test has passed
obMockHL.Verify();

}

private void On_LicMgr_EvApplicationAuthorized_CR9672(object sender, EventArgs e)
{
Thread obAnotherThread = new Thread( new ThreadStart( this.DummyHandler ) );
obAnotherThread.Start();
obAnotherThread.Join();
}

private void DummyHandler()
{
License obCurLicense;
// Query License which blocks indefinitely if PingLicense is holding a lock
LicenseManager.Instance.GetLicense(out obCurLicense);
}



I added a temporary log via Console.WriteLine to prove the test is authentic
# Test Failure log - test hangs
Lock Request by Thread 353 (PingLicense)
GotLock!
First Thread 353
Event Handler Thread 268
Lock Request by Thread 268 (GetLicense)

# Test Success log
Lock Request by Thread 359 (PingLicense) // did not remove Console.WriteLine - actually no lock request
GotLock! // did not remove Console.WriteLine - actually no lock request
First Thread 359
Event Handler Thread 261
Lock Request by Thread 261 (GetLicense)
GotLock!
EventHandler exit
PingLicense exit

Task completed!

Validate a string for being a Valid IP Address using .NET/C# code

Googled a bit for this but could not find anything. Then turned to my living .NET google - Aniket Palkar. Once again - Kneel down to the deep .NET knowledge pool.

Problem: Validate a string to check if it contains a valid IP Address. I mean 455.12.56.999 should be kicked out.

Here's the quick and simple way :
if(UriHostNameType.IPv4 == Uri.CheckHostName(sStringThatShouldContainIP) ||
UriHostNameType.IPv6 == Uri.CheckHostName(sStringThatShouldContainIP))
This will return if the specified string is IPv4 or v6 or just a DNS style name. Thanks to the guy who wrote this .NET class.. I'm 're-using' or mooching this one.

Here's my was-to-be-unleashed-uber Plan B:
Use this regex from Expresso with some boilerplate regex matching .NET Code.
(?2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?2[0-4]\d|25[0-5]|[01]?\d\d?)

A point to human searches against online searches ?

XSL: Special Characters being rendered for whitespace after Transformation is applied in .NET

While using .NET 1.1 for XSL Transforms, I was running into funky special
characters ": Pump Go " which were sprinkled wherever I had intentionally added white space in the xsl stylesheet file.
Google didn't throw up anything on this... Could I be the first man to step here. No - couldn't be...
Here's the snippet I used

XmlResolver obResolver=new XmlUrlResolver();
XPathDocument obFasterPerfDoc=
new XPathDocument(sDataStorePath);
XslTransform obTransformer=
new XslTransform();
obTransformer.Load(sXSL_StyleSheetPath);
using (FileStream fs=new FileStream(sReportPath, FileMode.Create, FileAccess.Write, FileShare.None)){
using (TextWriter tw=new StreamWriter(fs)){
obTransformer.Transform(obFasterPerfDoc,
null, tw, obResolver);
}
}

I struggled with it for a bit then let it be.. But now I seem to have run into the
solution. Use XMLTextWriter instead of TextWriter. XMLTextWriter doesn't implement
IDisposable. So can't use "using" blocks but the special character issue has gone away now.
So here's the modded code

*snip using
(FileStream fs=new FileStream(sReportPath, FileMode.Create, FileAccess.Write, FileShare.None)){
XmlTextWriter xtw=
new XmlTextWriter(fs, System.Text.Encoding.Unicode);
try {
XslTransform obTransformer=
new XslTransform();
obTransformer.Transform(obFasterPerfDoc, null, xtw, obResolver);
}
finally {
xtw.Close();
}
}
*snip

XSL: Applying Transformation to a Single Node / SubTree in .NET 1.1

I'm a recent XSL recruit oohing and aahing my way thru XML Transformations. It's pretty neat. Sadly we coders am not supposed to be in a happy state for too long. Soon enough I ran into the following issue:
How do I transform a single sub-tree in XML?
For example, I should be able to transform one subtree (e.g. Authors) with StyleSheet 1 and second subtree (e.g. Publishers) with stylesheet2.
StyleSheet 1 and 2 may contain overlapping templates, but that should not be an issue ... or so I thought. So I soon had my XML Ready, the XSL StyleSheet ready. I put up code similar to the one below.


----------------------Code Snippet

using
System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using Multiconn.Xml;
namespace XslPeeves{
///
/// Summary description for Class1.
///

class XslDemo {
///
/// The main entry point for the application.
///

[STAThread]
static void Main (string[] args){
try {
XmlDocument obXMLDoc=
new XmlDocument();
obXMLDoc.Load(
@"..\..\DemoSample.xml");
XslTransform obTransformer=
new XslTransform();
using (FileStream fs=new FileStream("Output.html", FileMode.Create, FileAccess.Write, FileShare.None)){
XmlTextWriter xtw=
new XmlTextWriter(fs, System.Text.Encoding.Unicode);

obTransformer.Load(
@"..\..\StyleSheet1.xsl");
obTransformer.Transform(
obXMLDoc.SelectSingleNode("/DocRoot/Authors"), null, xtw, new XmlUrlResolver());

obTransformer.Load(
@"..\..\StyleSheet2.xsl");
obTransformer.Transform(
obXMLDoc.SelectSingleNode("/DocRoot/Pubs"), null, xtw, new XmlUrlResolver());
xtw.Close();
}
}
catch (Exception obExcep){
Console.WriteLine(
"Oops!"+Environment.NewLine+obExcep.ToString());
}
}

}

}

Yikes! it's a mess, I have elements being transformed repeatedly. It is not honouring my sub-tree specification. It seems to be taking the entire document each time. Google was initially reluctant to divulge anything. A couple of search hacks and soon I see the light.
XslCompiledTransform in .NET 2.0 is supposed to handle this. XslTransform for .NET 1.1 always takes the entire tree even if you pass in an XMLNode. Crap! I need this now. Google finally takes pity and gives me the following link ..
http://www.tkachenko.com/blog/archives/000117.html
Code Download at
http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=599837ac-6a0a-4da1-b666-baea91e2dacc

Thank you Mr. Oleg, you're a life saver. I referenced the XMLNodeNavigator as a DLL and made the following mods to the code
*snip
XmlTextWriter xtw=new XmlTextWriter(fs, System.Text.Encoding.Unicode);
XPathNavigator obNavigator=
new XmlNodeNavigator(obXMLDoc.SelectSingleNode("/DocRoot/Authors"));
obTransformer.Load(
@"..\..\StyleSheet1.xsl");
obTransformer.Transform(obNavigator,
null, xtw, new XmlUrlResolver());
*snip
It works! It works! The XmlNodeNavigator is a custom derivation that prevents navigation outside of the sub-tree.
Another solution was loading the sub-tree in a seperate XMLDocument and passing that into XsTransform.Transform(). Naah!

Just got to slip Mr.Oleg a mail asking him permission to use this. There ends one of the tougher Xsl fights to date..

Code Coverage with NCover from Nunit runs

NCover by Peter Waldschmidt
http://www.ncover.org/downloads.html

NCover is a code coverage tool that runs straight out of the box on your production dlls. No pesky slow instrumentation builds. At run-time it intercepts CLR calls and adds what it needs on the run. Cool !
Getting it to run is another matter altogether. After a couple of frustrating attempts,
(there's a Win32Exception that's just top of the pops.) I think I have got it to run now with NUnit.
So I get automated tests with Code Coverage. Now is that cool or is that cool ? 8)

Running NCover.Console.exe:
use the /w to specify a working directory
Use the /a switch to specify semicolon delimited list of DLLs that it should monitor. By default, NCover will take all it finds in the directory. Use /a to prune the list.
Use the /c switch to specify a command line op that will run thru your code-base. Could be your Main executable or a test app or ... you guessed it NUnit at work!

"e:\Program Files\NCover\NCover.Console.exe" /w "G:\Dev\TestApplications\AutomatedTests\TestDlls\debug" /a GCommon;Licensing /c "e:\Program Files\NUnit 2.2.4\bin\nunit-console.exe" LicenseTests.nunit

Where I messed up
  • NCover doesn't like you "helping" it by giving complete DLL Names. So no 'licensing.dll' instead use 'licensing'
  • Specify the complete path to NUnit - it helps.
  • The coverage log (linked to coverage.xsl by default) caused some kind of problems for browsers. To get around, open up the xml in an editor and remove all instances of '&#x0;' I think that this caused the hyperlinks in the document to blow up but atleast you can now view the coverage report. Dunno why this is so... will post on NCover forum

And last of all,
Get the style sheet from http://blog.hishambaz.com/archive/2004/07/05/153.aspx
To use it, open coverage.xml and modify the stylesheet ref
... ?xml-stylesheet href="coverage2.xsl" ...
Save & Open the file in a browser and you are done. IE gave some active content warning and blanked on enabling active content. No such hassles with Firefox :)