Friday, April 15, 2005

C# Course day five

I installed the latest version of Mono on my Mac and the latest version of NAnt (an open source build tool) and managed to compile some of the Lab sample code from this course.
  • System.Threading namespace for creating threads, mutexes, etc.
  • Thread class takes a ThreadStart object in its constructor. A ThreadStart class is a delegate that points to the method you want to run in the thread. Call Thread.Start() to actually kick things off.
  • There are foreground and background threads and a Thread.IsBackground property. An AppDomain will not close as long as there is one foreground thread.
  • Signalling between threads can be done with the WaitHandle class.
  • You can create thread local storage by putting an attribute on a static variable [ThreadStatic] public static in count;
  • Visual Studio kinda sucks for working with Threads. Eclipse is better for this.
  • You can call Thread.Abort() to abort a thread, however a magic ThreadAbortException will get thrown and rethrown out of any catch block unless you call ResetAbort().
  • To Synchronize a method use [MethodImpl(MethodImplOptions.Synchronized}] I think its easier to use Java's synchronized keyword.
  • Can use lock{...} to define a critical section.
  • The Interlocked class's methods can create more optimized locking for simple operations on shared data like increment and decrement.
  • Can use a Windows OS Mutex to lock across processes. A Mutex is more expensive to use.
  • A ReaderWriterLock allows multiple reader or only one writer at a time.
  • The Timer class uses a delegate to call a callback method on a particular interval
  • There is a ThreadPool class that is handy for executing short running methods in the background with a normal priority.
  • IOCompletionCallback is used for processing data in a thread from the pool after an IO operation.
  • Use syntax like [DllImport (, Entrypoint=, CharSet= MyMethodName([...]); to call externall DLL methods.
  • tlbimp.exe is for importing a COM DLL.
  • There are roughly 10-40 instructions called when going from/to .NET from/to COM, not including the data marshalling. It is expensive so be careful.
  • SQL & Oracle clients are written all in managed code (kinda like JDBC drivers) & are much faster than going through OLE DB drivers

Thursday, April 14, 2005

C# Course day four

Wow. The Serialization and Remoting functionality in C# looks just like Serialization and RMI in Java.


  • Serialization is marked with an attribute [Serializable]
  • Have the option of Serializing to XML (with a SOAP flavour)
  • Remoting has the option of using HTTP, XML & SOAP or a binary protocol. Unfortunately the XML option isn't very interoperable with frameworks other than .NET.
  • use {WebService(Namespace=http://www.example.com/endpoint)] attribute for declaring web service
  • use [WebMethod] attribute for declaring exposed methods
  • Suggest creating a virtual directory in IIS before creating Web Service project in VisualStudio so that you can control where the IDE puts your files.
  • Can use WSDL.exe to read a wsdl XML file exposed through IIS to generate client proxies.
  • When adding reference in Visual Studio you can change a property of the reference to dynamic so that the URL is stored in a config file rather than in the C# code.

So to summarize:

  • .NET Remoting isn't getting much attention from MS
  • The Web Services available in Visual Studio are good for simple stuff without transactions, security, reliability, etc.
  • WSE 2.0 (Web Services Extensions) introduces transactions etc but there isn't and IDE support
  • WSE 3.0 still being defined
  • Indigo a MS term for their technology to make "serious" web services with transactions, security, etc. commonplace and easy to build with Visual Studio (1-1.5 years away)

Wednesday, April 13, 2005

C# Course day three


  • COM is done

  • Classic VB (6) is done

  • Big sell job on garbage collection. Commentary: It's good (I am a Java developer after all) and yes you can introduce bugs doing it manually but most of the time developers are quite capable of managing memory.

  • GC does heap compaction to deal with memory fragmentation

  • destructors/finalizers in C# look like ~ClassName(){} and are used for implicitly freeing resources. More important in C# than Java because of Windows' finite resource limitations (e.g., Fonts)

  • Unreachable objects with finalizers are moved to freachable queue & finalizers are not called on GC thread. Finalize thread comes along and calls finalizers and then on second GC run the object is collected. Which all means objects with finalizers stay around longer. Secondly their generational flags are bumped up meaning they're more expensive to clean up (i.e., more exhaustive GC search required). Don't use finalizers if possible.

  • C# idiom is to provide an explicit method for freeing finite resources as well as an implicit destructor. If using the explicit method then call GC.SuppressFinalize(object) to prevent the GC from duplicating the work. The explicit method should be an implementation of IDisposable. Eclipse's SWT suffers some of this same dispose problem because it uses native Windows resources. Ugh!

  • Finalizers are not guaranteed to run (like Java) so avoid them if possible.

  • A try-finally block for freeing allocated resources can be replaced with something like using(Resource r1 = new Resource()){}

  • WeakReference class allows an object to be collected if memory is low. Used for something like caching.

  • Can use the Windows Performance Monitor (i.e., perfmon) for viewing the CLR Memory. Pretty graphs... ;-)

  • There is multiprocessor support but uses a different CLR DLL (i.e., Workstation and Server). All console apps run using the Workstation VM unless you make some config changes.

  • An unsafe block is available for executing code and preventing the GC from moving objects around in memory. This is important for calling C DLLs for example. Looks like unsafe{}

  • IO Streams are very similar to Java. Functionality is added to the basic stream using the Decorator pattern. And there are Reader and Writer classes for dealing with text. C#'s one major difference is that there is just Stream not InputStream and OutputStream. Instead you define read or write using constructor parameters.

  • There is a File and a Directory class is C#. Java only has a File class with an isDirectory() method. The File class has some handy Factory methods for creating Streams.

  • There is a utility Path class for manipulating path strings.

  • FileSystemWatcher allows you to eliminate directory polling and receive events for things happening to a file or a directory.

  • IsolatedStorage is a handy class for providing 10MB of storage on the local file system for applications started from an http address. The data is stored in "c:\Documents & Settings\\LocalSettings\Application Data\Isolated Storage\". The only problem is that the directories in here are cryptically named.

  • CredentialCache class useful for getting the credentials of the current user.

iPod Shuffle on Windows XP (at last)

During my C# course I tried plugging my iPod shuffle into the USB port of my Windows XP machine and voila! It mounted like a hard drive without any trouble at all. I could drag and drop files onto it and even see all my MP3s. Very nice. Now if I can only figure out why my Windows machine at work can't see it I would be very happy.

Tuesday, April 12, 2005

C# Course day two

Not a single Java comment today. Amazing.


  • System.Globalization for i18n (internationalization)

  • String.Format does println kind-of functionality. The patterns are a bit different however "The value is {0,-10:f2}"

  • Did my first lab with Visual Studio. Struggled a bit with the syntax differences. Things like defining Properties in an Interface, or operator overloading, overriding methods (stupid virtual/override keywords), and defining an explicit cast operator.

  • Eclipse is a way better code editor than Visual Studio. Studio may have other advantages (like visual form editing) but Eclipse owns this one.

  • Can use syntax like @"c:\folder\folder2\file.txt" so that you don't have to escape each back slash. Well maybe if MS used a forward slash in the first place this wouldn't be an issue ;-)

  • C# supports regular expressions that are designed to be compatible with Perl 5.

  • IComparable = Java's Comparable interface and IComparerer = Java's Comparator

  • There is not equivalent of Java's Set collection in .NET. Seems like an odd omission

  • Can use the indexing syntax of square brackets (e.g., collection[2] ) with both hashmaps and lists.

  • ArrayList.ReadOnly(list) is an easy way to make an immutable collection

  • System.Collections namespace contains a StringCollection that is specially tuned for dealing with strings.

  • Can call delegates asynchronously with IASyncCallback

  • Can use += and -= instead of the methods Combine() and Remove() respectively for multicast delegates.

Monday, April 11, 2005

C# Course day one

A day-by-day, blow-by-blow account of my Microsoft C# course. I'll update this particular entry throughout the day.

First of all, why would I attend a C# course when I've been a Java guy for so long... Well this just comes down to ensuring that I'm open to all technologies. I know people who talk poorly about technologies that aren't their favorite and usually they bash away without knowing what they're talking about. Personally I like to bash from a position of knowledge not ignorance. ;-)

Secondly, I already looked at C# about a month ago and was fairly happy with what I saw. I'm really only lacking some knowledge about the frameworks.

Finally, it's free. A company I worked for about two and a half years ago already paid for this so why not take advantage of it.

So now onto the course...

  • 10:30 AM I've learned nothing so far. Boring.

  • I've sat quietly through some Sun, Java bashing from the instructor no less. That was a bit irritating. That will definitely come up in my evaluation.

  • 12:16 PM Namespaces usually take the form of CompanyName.Application.Layer (e.g., Sundog.Retail.Data)

  • Can have multiple entry points in an app (many classes with Main methods) just need to specify which one in compiler settings

  • csc.exe is the command line compiler

  • a "module" is equivalent to a Java .class file

  • an "assembly" is equivalent to a Java .jar file. Contains a Manifest file that specifies version and other meta data.

  • ilasm.exe produces assemblies (not sure about this...)

  • ildasm.exe is a disassembler to look at manifest and generated MSIL code. ".NET Reflector" is a 3rd party tool that disassembles into C#, VB, or Delphi. Obfuscator may be good for commercial .NET

  • Can use ngen.exe to precompile assemblies into native code. Not always better.

  • Application Domains are like separate processes for different applications in one VM. It's done programatically so usually used by app server not individual apps.

  • Can create C# alias when multiple classes from multiple namespaces have the same name. e.g., using CSStringComp = CompCS.StringComponent;

  • 4:11 PM ASP Output cache allows the reserving of previously generated output. If the data's not changing quickly, this may be useful. Also works with page fragments.

  • .NET Framework around 24MB. How does that compare to Java. Everyone used to complain about how bit it was.

  • App can be launched from HTTP or File server and execution rights are reduced unless app is signed. Very much like Java WebStart.

  • No DLL Hell. Assemblies are typically deployed privately (in the same dir as the exe).

  • There is a "Gloabl Assembly Cache" (GAC) in c:\windows\assembly which is shared and can contain multiple versions of assemblies.

  • Assemblies must be signed to go into the GAC. Apps are compiled against a specific version. Versioning is much better handled in .NET than Java.

  • Visual Studio has a Setup project that can be added to a solution to create an MSI file (MS Installer). Nice touch.

  • Java got bashed a couple more times and I had to correct the instructor and let him know that autoboxing, enums and attributes are all part of Java and that the default behavior of virtual methods isn't necessarily a bad thing. Jeesh. I hope he shuts up now. ;-)

  • C# has structs but the instructor and apparently MS discourages using them. You don't get a performance boost and they're less flexible. Use only when you're interfacing with legacy code.

  • enums are also good for interfacing with legacy code. The [Flags] attribute can be used to assign bit values.

  • The internal keyword marks something for use by classes in the same assembly. Not quite the same as the package scope in Java.

  • Use Object.ReferenceEquals() instead of Equals() (unlike Java). Here == and Equals() should mean the same thing.

  • Can overload operators (+,-,*,/,%,<,>,==, etc) in C# using something like static public bool operator == (Class obj1, Class obj2){[...]}

  • ToString() is here too

  • Instructor made a big deal that implementing a Singleton in Java was hard. Here's an article he was referencing. Basically you do this in C#: public static readonly ExampleClass Instance = new ExampleClass(); Well in Java you do private static ExampleClass instance = new ExampleClass(); and provide a static accessor.

  • Instead of using ExampleClass.class in Java you use typeof(ExampleClass) in C#.

  • Operators like is, as, and typeof for working with Types.

  • generics will show up in .NET 2.0. Already there in Java 1.5, but Anders Hejlsberg (MS .NET Architect) suggests that the Java implementation isn't as good, primarily because Sun chose not to introduce new bytecodes in the VM to implement this functionality.

  • Can implement two interfaces that specify the same signature by explicitly defining the name of the interface in the method implementation.

  • pinvoke is the way to call "classic" DLLs. Looks much easier than JNI.

  • For COM compatibility .NET objects can be exposed as COM objects and COM objects can show up as .NET classes. Very reminiscent of Delphi.

Thursday, April 07, 2005

Libraries

Apparently someone was dumping some older computer books by donating them to our local public library to sell. Well I happened along and picked up the "pickaxe" book Programming Ruby (1st edition), Learning the bash Shell, and Learning Python (the last two from O-Reilly) for the princely sum of $1.50! Sweet! BTW: bash is the default shell and both Python and Ruby are installed with Mac OS X. Naturally. ;-) Public Libraries truly are wonderful things!

Wednesday, April 06, 2005

Those Damn Liberals

Over the last few days the Canadian press has been talking about an American blogger dishing the details about Jean Brault's testimony at the Gomery Inquiry into the federal sponsorship scandal. So I went over to Google, did a little search and found the blog that the press was talking about. If some of that stuff is correct then the Liberal party and former prime minister Jean Chretian are going to have a lot to answer for. It must be nice to be Stephen Harper right now...

Hibernate lets me down...

Well the new version of Hibernate is out there and apparently version 3.0 has been seriously worked over by the Hibernate team. Specifically I'm referring to the brand-new ANTLR-based HQL/SQL query translator... but back to that in a second.

I generally keep up with the latest version of Hibernate and up until I tried 3.0 it was a no-brainer. You just downloaded it and everything just worked. Not this time:

First of all, the packages all changed from net.sf.hibernate to org.hibernate. While it's nice that the package reflects Hibernate's domain I don't think this change really needed to be inflicted on its users. TopLink did that to me when it changed hands from The Object People to WebGain and then to Oracle. It's a pain in the ass.

Secondly, "Since it is best practice to map almost all classes and collections using lazy="true", that is now the default." While I agree with the point, I was a little annoyed to discover that much of my second level caching stopped working. Easy enough to fix but still...

Thirdly, back to the new HQL/SQL Query translator. It fails to parse several of my existing queries. Damn. Worse is that the documentation says I can set the hibernate.query.factory_class property to use the ClassicQueryTranslatorFactory but that doesn't work either. So I'm forced to use native JDBC calls instead. That's what Hibernate is supposed to help me avoid!

Finally, Hibernate 3.0 has a "revamped Query API". This was my whole reason for trying Hibernate 3.0 and unfortunately when I use criteria.createCriteria() or criteria.createAlias() the alias for the joined table doesn't show up in my generated SQL!!

Agghhh! I still like Hibernate (most of it still works) and I'm going to stick with v3 but this was not what I've come to expect of the Hibernate team. It sounds like the HQL/SQL parser thing was the right choice but this release needed a little more time in the oven.

Cocoa Core Data

When Apple introduced the binding controllers in Panther (Mac OS 10.3) they eliminated a lot of the glue code people used to write to keep the model and view of their applications in sync. Now they're aiming to make the persistence of the model simple too with Core Data, a new framework in Tiger (Mac OS 10.4). This article on Apple's Developer Connection website explains it with a bit more detail. While it somewhat resembles Object Relational mapping it looks to be a file based persistence mechanism. The developers of Delicious Library had good things to say about Cocoa Bindings:
We rewrote everything in a day or two—I think we deleted over a thousand lines of code that just wasn’t needed any more.

...so I'm hoping that Core Data will be equally well received and productive.