The Pitfall of ICloneable

Or, why you should never use ICloneable.

So I decided I needed to support cloning for my objects so I can modify the object and compare it to the original (very useful for unit-testing, dirty checking, etc.). The .Net framework comes with a handy interface to publish this ability called ICloneable. The documentation states "Supports cloning, which creates a new instance of a class with the same value as an existing instance". Great! It comes with one method: Clone. Can't be too hard to implement this interface, right?

A quick peek at the documentation for the Clone method says the implementation "Creates a new object that is a copy of the current instance". And so every textbook implementation goes on to show you how you do that:

public object Clone()
{
   return this.MemberwiseClone();
}

But what is the point of that, besides adding more code to maintain? EVERY object already supports MemberwiseClone! Oh yes, we were trying to satisfy an interface contract... But hold on, it gets worse as the documentation then opens up an infinite can of worms with this remark:

Clone can be implemented either as a deep copy or a shallow copy. In a deep copy, all objects are duplicated; whereas, in a shallow copy, only the top-level objects are duplicated and the lower levels contain references.

The resulting clone must be of the same type as or a compatible type to the original instance.

The Clone method, and thus the ICloneable interface just became a free-for-all, do as you like, contract. You may deep copy, shallow copy, heck you can even change the type! Technically this can all result in correct code, but the sheer absence of semantics turns the use of this interface into a humongous pitfall. Within your own sphere of influence you can set an expected semantic, but as soon as your code leaves this safe place, or you introduce code from another source which applied different semantics to the ICloneable interface you are in for a debugging session from hell.

ICloneable just became unusable.

Go ahead and mark it as obsolete in your copy of the framework. Not all is lost however, you can work around this issue by defining your own interface contract with its own semantics, but do not inherit it from ICloneable as this would reintroduce the issue. For example:

/// <summary>
/// Supports deep-copy cloning, which creates a 
/// new instance of a class of the same type and 
/// with the same value as an existing instance.
/// </summary>
/// <typeparam name="T">Type of the class 
/// being cloned.</typeparam>
public interface IDeepCloneable<T>
{
   /// <summary>
   /// Creates an equally typed deep-copy clone 
   /// of this object.
   /// </summary>
   /// <returns>An equally typed deep-copy clone 
   /// of this object.</returns>
   T Clone();
}

This interface contract sets a clear copy and type expectation (and gets rid of the pesky Object return type, that was so 1.0 baby!), but defining cloning semantics is not an easy task. Data containers, business- and UI-objects all have different needs and come with different cloning behaviors. Defining an interface for each of those will help keep expectations clear and ease integration with 3rd party components. However, unless you explicitly implement those interfaces on all classes you will also have to make sure the method names in those interfaces are unique else it will still be too easy to mix incompatible implementations. Always keep the consumer in mind while designing your interface!

I'm curious to know how you approached your cloning challenge. Leave me a comment!

 

References

Black Screen after Vista Wakes Up from Sleep with NVidia Driver Version 7.15.11.7521

It's actually not completely black, the top line of pixels still works properly! This problem started for me after I installed the driver update supplied by Windows NVidia_GeForce6150LE_v7.15.11.7521Update for the GeForce 6150 LE; Driver Provider: NVIDIA, Driver Date: 5/22/2008, Driver Version: 7.15.11.7521. Both manually forcing it and idling to sleep or hibernate produce the same results.

The rest of the system appears to be functioning properly and pressing the power button will turn off the system. Hitting the [WIN], typing 'shutdown /r /t 0' and pressing [enter] will reboot the system. Upon reboot the screen is fine again and neither the EventLog nor Reliability Monitor show any problems.

Rollback_Driver_ErrorI decided to roll back to the previous driver (7.15.11.6222, 7/6/2007), which produced four RunDLL error dialogs: "Error in NVCPL.DLL - Missing entry:NvCplRestorePersistence". Ouch!

Now the screen works properly when waking up, but I get greeted with that error dialog. Again, no errors or warning in the EventLog or Reliability Monitor.

Time for the windows cure-all... DAS (RE)BOOT!

Excellent! The reboot cleared up that issue.

Has anyone else experienced this issue? Did you resolve it? How?

Related posts:

Nerdettes are the source of beautiful code?

Emma McGrattan, the senior vice-president of engineering for computer-database company Ingres–and one of Silicon Valley’s highest-ranking female programmers–insists that men and women write code differently. Women are more touchy-feely and considerate of those who will use the code later, she says. They’ll intersperse their code–those strings of instructions that result in nifty applications and programs–with helpful comments and directions, explaining why they wrote the lines the way they did and exactly how they did it.
The code becomes a type of “roadmap” for others who might want to alter it or add to it later...

Did she just say I code like a girl? My pursuit of writing maintainable code is really an exploration of my feminine side? That is quite the flamebait Mrs. McGratten treated the nerdiverse on. :)

Her goal is noble, but I think Agile is wasted on Ingress:

In an effort to make Ingres’s computer code more user-friendly and gender-neutral, McGrattan helped institute new coding standards at the company. They require programmers to include a detailed set of comments before each block of code explaining what the piece of code does and why; developers also must supply a detailed history of any changes they have made to the code. The rules apply to both Ingres employees and members of the open-source community who contribute code to Ingres’s products.

My question to you: Do you get anything done? Or is 90% of time spent on adding code-pretties?

Realtek HD Audio - upgrading from 6.0.1.5502 to 6.0.1.5548

The Software & Driver download page for my HP Pavilion a1750e had an updated audio driver on it, but I assumed Windows Update also had the latest Realtek HD Audio drivers for Vista. Since I religiously keep up to date with Windows Update I assumed I was running with the latest drivers. Alas, I was wrong mistaken!

What is going on here? Why do I have to pick those drivers up from HP? It looks like Microsoft would have to keep a lot of vendor specific updates available, considering this disclaimer found on the Realtek drivers download entry page.

Audio drivers available for download from the Realtek website are general drivers for our audio ICs, and may not offer the customizations made by your system/motherboard manufacturer. To be sure you obtain the full features/customizations provided in your original audio product, please download the latest drivers from your system/motherboard manufacturer's website.

Yuck! This is lawyer speak for "we don't do drivers, we're in the hardware business". Ergo, you want drivers? Go talk to your hardware vendor. And so I did. Current installed version 6.0.1.5502; Time to put the upgrade to version 6.0.1.5548 to the test. (Release date: 2008-03-01, Description: Realtek High Definition Audio driver update resolves excessive noise issue with HDMI audio.)

Strangely enough HP software updates still do not seem to be able to use a wizard style for their update dialog, so after running sp37324.exe I am presented with the plea to press YES! ClickYes

Ick! Ok, then. I wonder what the difference is between "No" and "Cancel". :)

Next up, a little progress dialog...

PleaseWait

Eeeep! No progress shown here, just the moving piece of green that shows it is busy. And after a bit the update is done; Time to click YES again, or No, or Cancel!

UpdateCompleted

I chose to be nice, and click YES, the system restarted, and I still had sound. Yay! Unfortunately all my audio configuration settings were wiped out again, so I had to set front and back channels to be split again, but that was the only heartache I got. And just to be sure I checked the version dialog:

driver-v6.0.1.5548-infopanel

Success!

My question to you, dear reader, is: Where do YOU pull your Realtek HD Audio driver updates from?

Building Software, Evil and Getting Things Done

Jeff Atwood  wrote a passionate blog entry about Craigslist and the demise of the Personals section (amongst others) now that Evil forces have taken over with the help of ever more sophisticated tools and creative solutions. Wouldn't you agree such is the natural result of the open approach used by Craigslist? Anyone can post an ad. If they had not taken this approach Craigslist would not have been so successful. Lowering the bar for getting your classifieds in meant getting more ads, because everybody could do it, without having to sign away their life. Just like tourist destinations attract pickpockets (and loose women?), open high-traffic websites attract spammers.

Craigslist was a great idea. A great idea that became more than just an idea, it actually got implemented. Maybe the implementation was not perfect by today's standards but it worked and has paid the bills for over thirteen years! A proper threat-modeling session in the early days would surely have brought these issues to light, and business-need would have overruled security/abuse. Unfortunately this business model might have seen its' longest days by now.

Nowadays such openness is no longer feasible. Spammers and crackers are abusing the system every which way they can for personal gain forcing our software solutions to be able to handle every known attack angle and mitigate the future ones as much as possible. Any programmer that takes himself seriously should invest in getting properly educated on the security aspects of programming. Not just because he should create solid code, but because sooner or later it will become a liability. Everybody with a little knack for logic and the ability to use google can cut and paste together a piece of software. Creativity and innovation flourishes! But... would you send your kids out on the road in an innovative car with no brakes? I think not!

When you make a living writing business software there is a constant struggle between getting things done, and getting them done right. Being able to get things done right generally means you already need to know how to do them right because there is no time to search the web all day for the perfect solution, that deadline is approaching fast. What's worse, you might not even be aware there is a problem with the chosen implementation. If you are a contractor, do you invest in your security education, or do you focus on getting up to speed on the latest fizz-buzzwords? If you are a wage-slave, does your company invest in your education, or are you merely a mindless implementer of business requirements? Do you invest in yourself?

Invest in yourself!

How do I invest in myself? Personally I still prefer a good book over online reading. The author of a book has put an effort into putting together a cohesive set of information to help you advance. When you randomly pull a single chapter out of a book you generally miss context or concepts. Browsing the web is like pulling a subtract of a chapter out of a giant book and all the other related information goes wasted on you. You get a quick answer to a specific detail to a problem, but never get to grasp the whole problem. When I do decide to stick with using the free online resources I make sure I do my research properly; Follow links, make sure I get the context. Granted, most bloggers/authors on the web put a lot of effort into their content, slowly weaving a never-ending book online, but that is not the same as having a book covering a specific topic. :) (Some day we might all go the way of the Kindle, but I prefer the feeling of a solid paper book.)

In the end we are all responsible for the solutions we produce, so next time you get to implement a great idea make sure you (know how to) do some threat-modeling first (online, book). That shortcut you were about to take might have changed the fate of the planet!

Does Universal Beautiful Code Exist?

A lot of debate is going on about "Beautiful Code". How can you measure the beauty of code? Is it "solid" code? Or perhaps easily readable for humans? An efficient algorithm, or a fast one? Terse sample code that shows a concept, or production code that is robust and fault tolerant? Perhaps a clever solution to a problem, or code that follows coding conventions and guidelines? Or should it be patterns based? What about curly-braces, indentation, comments, letter-casing (NO SHOUTING, IT'S RUDE!) or programming language? Should it exploit all features of the language it was written in, or only use some generic feature-set, libraries or framework commonly found in the language type (imperative, functional, .Net, C-Libraries)? What about cyclomatic complexity and other software metrics?

Most of those "beauty metrics" are purely gut-feeling based and enforcing metrics like a low cyclomatic complexity generally does not improve code beauty (good luck polishing a coal until it's a diamond). In my experience code often mirrors the authors' understanding of the problem and thought-process. No amount of computer assisted code analysis can improve that.

Beautiful code can come in the form of little one-liner gems, or huge elegant architectural diamonds that solve a real-world problem. You will generally find more little gems than big diamonds.

In the end nobody can win: Beauty is in the eye of the beholder!

I cannot put it better than David Hume:

Beauty in things exists merely in the mind which contemplates them.

Code beauty is determined by the observers' frame of reference; programming exposure (languages (C, C++, Java, Visual Basic, F#, Ruby, Lisp), Patterns, Algorithms, Operating Systems, formal training, experience (how many times has the beholder been burned by mistakes?), etc.), native language, organizational position (Junior Programmer vs. Senior Architect vs IT Director, they have different stakes in the code produced) and even aesthetical preferences.

Back to my original question: Does UNIVERSAL beautiful code exist?

Think about that for a minute, I'll wait... What do you think the Greys use as their programming language? Something based on hieroglyphs and flow-charts? What about my Ferengi friend Quark? Quantum languages like QCL or QFC?

Good luck getting consensus on that! :)

So, is there Beautiful Architecture?

Process Explorer for Windows Mobile

My iPAQ with Windows Mobile was acting sluggish, so I went hunting for a Task Manager/Process Explorer like utility for it and came across this little gem. Saved me some coding! In the end I  was unable to figure out what exactly caused the slugginesh because the problem went away, but next time it happens I will be prepared!

TaskMgr for WM* is a must-have for every Windows Mobile user, like a Swiss Army Knife my Leatherman (don't leave home without it)! All the basic tools a user needs to keep the system running smooth: Process manager, CPU usage, Application Manager, Service Manager, Device Manager (only WM2005 and above), Windows Manager, Notification Manager, IP Config utility, Ping utility, Net Stats utility, Registry Editor and a 'Run program' utility. Kudos to Dotfred!

<rant>I should not need a tool like TaskMgr to keep my system running smoothly. Windows CE is supposed to run a mobile phone, which can be a life-saving device... Last thing I need is a frozen (phrozen?) phone!</rant>

Monitor Your System Performance With Samurize

Have you ever wondered what is going on under the hood of your Windows system? Why is it so sluggish and slow (read: sloooooooooow)? Why is my harddisk continuously blinking? Or that CPU fan sounding like a jet engine? - As a software developer with a passion for code quality and performance I always strive to produce solid code and software algorithms, but you will not know how it actually behaves until you measure. Even though software the development environments of today come with an army of sophisticated tools to help you squeeze out the numbers during a test run they do not give you a general feel of how your system normally performs. Windows comes with perfmon, but configuration and interpretation of those graphs is a pain at best. Samurize to the rescue!!!

Samurize to the rescue!
Using Samurize and a little imagination you can build a very slick system status display that will make your friends turn green with envy! The configuration I use looks like this:
Once you have settled in on a base set of performance counters and how you would like them displayed, CPU-, Memory- and Disk-Usage histograms are a good place to start, it is easy to expand your configuration to include more items you want to monitor like SQL Server, Network traffic, etc. After creating and selecting your configuration you will want to set the display position to "docked" so the meters are always visible.

Here is a link to download the configuration I currently use.


I will explain how to interpret the different sections of this configuration in future posts.

Update: Replaced configuration file contents with a download link.

One month with Vista SP1 - One hickup: mobile device not recognized

So I have been using Vista SP1 for a month now and have yet to run into any major issues. I get the impression memory usage has been slightly improved, but apart from that I did not notice any improvements or degradations. Same old Vista to me. :)

One minor issue I ran into: My IPaq failed to get recognized. This manifested itself when I woke up the PC from standby mode. The screen came up, the cursor was blinking, but the mouse and keyboard were unresponsive for over a minute. THAT had never happened before. As a matter of fact, it seems that my keyboard is recognized quicker when waking up from standby with SP1. I should have taken hard measurements, before & after, too late now! But I digress, back to the main issue... Once my peripherals were finally online I noticed synchronization with my IPaq was not happening anymore, even worse, there was no IPaq! Removing and reinserting it in the cradle did not help either. Performing a soft-reset on the IPaq fixed the issue and it has not occurred since.

On that note... Today, Microsoft announced they are beginning automatic distribution of SP1 in English, French, German, Spanish, and Japanese.

Related posts:

Neurotic Drum Beat Robots - A Glympse of the Future?

Very cute, totally neurotic little robot that drums on whatever it is "enticed" to play on... Dress her up in pink and you got yourself an energizer bunny! :) via Synthopia

Appleseed Ex Machina Review

This month Appleseed Ex Machina (Appleseed 2), another masterpiece by Masamune Shirow, was released so I had to pick me up a copy. As the sequal to the great movie Appleseed the bar is set pretty high already, and it definately lived up to my expectations. The plot.
Deunan Knute, a young female warrior, and Briareos, a veteran cyborg-soldier, are both partners and lovers. As members of E.S.W.A.T., the elite special forces serving Olympus, they are deployed whenever trouble strikes. During a mission involving several high-ranking E.U. officials held hostage by a group of unknown and heavily-armed cyborgs, Briareos is injured protecting Deunan from an ensuing blast. As a last ditch effort by an injured cyborg, E.S.W.A.T. assigns Deunan a new partner, a bioroid named Tereus. Largely based on Briareos' DNA, Tereus was designed as a prototype for a new kind of fighter bioroid. His appearance is very similar to the way Briareos looked before he became a cyborg. Deunan is not agreeable to the idea of having a new partner, but eventually befriends him. (from Wikipedia)
Sounds like a mushy love story doesn't it? :) Good thing this plot gets dressed up with all the cybernetical action goodness you can expect from Masamune: Cyborgs, Bioroids, even humans (I always said cellphones were evil!) go out of control; taken over by a nutty scientist who is trying to make the world a better place. Movie Execution The movie itself is a captivating blend of visual goodness and clever action scenes. Rendering and effects are fantastic, and I get a good chuckle out of the action scene choreography which reminds me of the fresh new style that was introduced by The Matrix trilogy. BUT... East meets west? Where is the liquid red stuff? This is an anime, right? One of the reasons I enjoy watching anime is seeing the raw exaggerated fiction of the harshness of life... IT'S NOT THERE!!! (Okay, its there twice, without any of the exaggeration). It was there in the first movie. If it had not been I would not have cared, but this movie is so clean my 3 year old would ask to see it again! From the occasional abrupt cuts I would speculate it has been sanitized to introduce it to the American mainstream. - Is this another case of censorship, like what happened to Urotsukidōji? That American version was cut up so bad you lost about half the movie. - BAD Warner Video? BAD John Woo? (East meets East?!?) However, I have not been able to find any indications the original Japanese version would live up to this expectation. Please leave me a note if you know more about this. Conclusion Despite the lack of red splattering this movie is definately a must see, worth your time and money! The movie comes in single DVD format (HD-DVD/DVD combo - nice an cheap!, Blu-ray) and Two disk special edition (DVD format). If you have not seen the original Appleseed movie yet make sure you watch it first! Enjoy! - Doc.

Vista SP1 upgrade with Realtek High Definition sound driver v6.0.1.5502 successful!

This weekend I was pleasantly surprised with an available download for Vista SP1 through windows update (why did it take so long?!?). I was fearful of losing my sound with the upgrade due to "SP1 not available cause #5", my driver version is v6.0.1.5502, but the upgrade went well (turns out I have a High Definition Audio Codec, not AC'97, ooops). The custom settings for the sound card were reset (I like to split all input/output jacks into different channels, the default ties them all together), but that was it. Sound is totally functional from the get-go!

Hurrah!

I haven't seen any difference in performance yet. Feels like same old Vista so far.


Related posts:

Vista Easter-Egg

Happy Easter! Here's the "full picture"...
But Vista! You were the chosen one!

Environment.TickCount: Int32 (aka SIGNED integer)

Did you know that Environtment.TickCount returns a signed 32 bit integer? Did you know the sign on this property flips every 24.9 days? From the MSDN documentation: The value of this property is derived from the system timer and is stored as a 32-bit signed integer. Consequently, if the system runs continuously, TickCount will increment from zero to Int32.MaxValue for approximately 24.9 days, then jump to Int32.MinValue, which is a negative number, then increment back to zero during the next 24.9 days. Ouch! Good thing windows updates get pushed once a month (and generally kindly coerce you to reboot); you might not notice the couple of days at the end when you're pulling negative numbers. But alas, today the negative tickcount decided to hit me. I was running unittests and noticed I was sending out negative request numbers?!? WTF! ROTFL! :) A little investigation turned up the culprit; trusty old TickCount wasn't that trusty after all. (That will teach me for stopping the windows update service to stop the reboot nagging, right?)
What happened to the days when you could boast about your system uptime? My linux box easily ran into hundreds of days (the resets were caused by power outtages)! What happened to my linux box?!?
What is a developer to do? Eureka! You can cast it to a Uint32! Twice the positive size, twice the fun, right?

UInt32 tickCount = (UInt32)Environment.TickCount;

Nah, you'll still wrap around after 59.8 days, which means you cannot use it to calculate the system uptime or measure time intervals... Here's how to calculate system uptime:

PerformanceCounter uptimeCounter = new PerformanceCounter("System", "System Up Time", true); uptimeCounter.NextValue();// init counter float uptime = uptimeCounter.NextValue(); // get uptime in secs TimeSpan uptimespan = TimeSpan.FromSeconds(uptime); Trace.WriteLine("Uptime: " + uptimespan.ToString());

And this is how you measure a time interval:

Stopwatch sw = new Stopwatch(); sw.Start(); // do lengthy stuff sw.Stop(); Trace.WriteLine("Elapsed: " + sw.Elapsed.ToString());

Enjoy! - Doc. How do YOU determine your system uptime programmatically?

ClientCertificates and WebException: The request was aborted: Could not create SSL/TLS secure channel.

If you are using X509 ClientCertificates with a webservice client called from IIS and the service endpoint uses the HTTPS protocol (SSL) the following exception can occur: WebException: The request was aborted: Could not create SSL/TLS secure channel.
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. at System.Web.Services.Protocols. WebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols. HttpWebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols. SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
The curious part is that everything works great while running unittests on the service directly; it's IIS that throws a wrench in it. To add some more grief to the equation this particular scenario played out in a test environment with self-signed certificates. So my initial investigation concentrated on making sure the root certificate was in the right place (LocalMachine\My and Root). All seemed well, but the exception persisted. I resorted to disabling certificate verification, still the exception persisted. Finally Microsoft KB article 901183 'How to call a Web service by using a client certificate for authentication in an ASP.NET Web application' put me on the right track:
Step 2: Configure access to the client certificate In this step, you must grant permission for the ASP.NET account to access the client certificate that is stored in the local machine store. The Network Service account is the default account for running Web applications on Windows Server 2003. Therefore, you must grant access to the certificate for the Network Service account. If you have configured a custom account to run ASP.NET, you must grant access for the custom account. Note In Microsoft Internet Information Server (IIS) 5.0, ASP.NET runs under the ASPNET account and not under the Network Service account. Therefore, you must to grant permissions for the ASPNET account on a computer that is running IIS 5.0. To grant access for a specific user account, run the following command at a command prompt: WinHttpCertCfg.exe -g -c LOCAL_MACHINE\MY -s "IssuedToName" -a "AccountName"
And voila! My service client happily zoomed along again. Why did it work while unittesting and not in IIS? The certificate was installed under the developer account, which grants the necessary permissions to the private key for that account immediately, but the NetworkService account was lacking them which caused the underlying connection to be closed... Microsoft has included the tool FindPrivateKey in the Windows Communication Foundation (WCF), Windows Workflow Foundation (WF) and Windows CardSpace Samples which can help you locate the private key file and check (and change) its permissions. I hope it helps some of you out there struggling with the same issue!

My Latest Track