Who doesn’t like mixing their Raisin Flakes with their Oaty-O’s in the morning? Yum! But it’s not a good idea if you’re talking about serial formats in C# 3.5 instead of breakfast cereals. You’ll get output that might leave a bad taste in your mouth.
Question: You’re writing a web API for an application. To give developers the most flexibility in interacting with your system, you want to expose classes that can be serialized to either XML or JSON. Using WCF and C# 3.5 SP1, what are your options?
Answer: There’s only one option unless you rely on 3rd party serialization libraries. You must mark the class with the [DataContract] attribute and mark each serializable member with [DataMember]. This allows you to serialize and deserialize using the DataContractSerializer and DataContractJsonSerializer for XML and JSON respectively.
I mention this because we’d gone to great lengths to customize our XML using the IXmlSerializable interface. This gave us fine control over the properties we wanted to appear in our XML output and how they were formatted. But if you use the IXmlSerializable interface, you can’t also annotate the class with the [DataContract] attribute. You’ll get a compiler error. Sowmy Srinivasan explains this serialization restriction.
I know what you’re thinking: If the framework provides an IXmlSerializable interface, isn’t there also an IJsonSerializable interface? Sadly, no. There’s no way to fine-tune the JSON output. Sigh.
So, if you’re currently using IXmlSerializable, you can forget about the DataContractJsonSerializer. Or you can accept that you’re fighting the framework, forget about your fancy-pants XML format, and accept the default serialization, keeping these data member best practices in mind.
Infovark has too much invested in our XML layout at this point. We’ve built our XSD files, XSL Transforms, and many, many unit tests. So we gave up on the DataContractJsonSerializer and turned to the excellent JSON.NET, written by James Newton-King. It’s now version 3.0 and fully supports the new LINQ constructs.
It’s a little more work, but we think it’s worth it.
I’m not sure whether it’s the fastest way to convert an enumerable collection of longs or ints to a comma-delimited list in C#, but it might be the shortest.
If you need a LINQ-free version for backward compatibility, check out Missing Functions on IEnumerable on Steve Cooper’s blog.
Sometimes COM Objects return a HRESULT that is outside of the bounds of a C# integer.
Unfortunately, the only way to correctly handle a COM Exception in .NET is to use the ComException Class. But if the HRESULT isn’t an Int, and the ErrorCode Property on the ComException class is an Int, how are you supposed to ever be able to catch that specific HRESULT?
Fear not! Here’s how to handle a COM ErrorCode that can’t be converted to an Int (in this example, it’s unsigned)
The magic happens in the ‘unchecked’ statement – which tells the compiler not to perform the overflow-checking context for integral-type arithmetic operations and conversions.
More on the Unchecked Operator over on MSDN.
The ConfigurationManager class introduced in .NET 2.0 makes it easy to read application settings from an XML file. I especially like the ability to derive a class from ConfigurationSection to hold custom settings for your application. This MSDN tutorial on creating custom configuration sections can help you get started.
I used this to make the configuration files for several of our Infovark add-ins, but ran into a snag with our main API library. In order to interoperate with COM, we had to put out Infovark.Api.dll in the GAC.
This presents a big problem for using *.config files. If your assembly is in the GAC, your configuration file must live in the GAC as well. (By default, configuration files are sidecar files located in the same directory as your *.exe file.) Since the GAC lives in a special place on a Windows machine, it’s difficult to read and write from that location without special permissions. And you can forget about browsing to it using Windows Explorer. This makes it tough for folks to change configuration options, which defeats the whole point of XML-based configuration files.
It’d be nice if we could load the configuration file from an specific spot on the computer. But while the Configuration object has both Save() and SaveAs() methods, there’s no corresponding Load() method. Huh? According to MSDN, the “right” way to point your application at a different configuration file is to create a whole new app domain with the appropriate settings. Um… sure.
How about we just hack up a workaround instead?
You can fool the configuration object into loading settings from whatever .config file you want, if you don’t mind a hack or two. The Configuration object exposes an OpenExeConfiguration() method that takes a string. Despite its name, you don’t have to pass it an .exe file. Any file path will do, as long as the path exists.
Since my .dll was in the GAC, I didn’t have a target for the OpenExeConfiguration() to use. I could have pointed it at another .dll — or at a .txt file for that matter — but that wouldn’t be very intuitive. Instead, I created a temporary file without an extension in the location I wanted to save the configuration file. Then I can open a Configuration object using the dummy target. Saving the Configuration object will cause it to write a file named “[configurationTarget].config” to the path I specified. You can see the code I used below.
Once I’ve opened the Configuration object, I don’t need the dummy file any more. I delete it to avoid have weird extension-less files hanging around.
It’s not pretty, but it gets the job done.
We just finished our trial period for ReSharper from JetBrains. We’re buying licenses right now. It’s become indispensable to us. It’s that good.
ReSharper is like pair programming for introverts. It’s like a real-time FxCop, offering refactorings and best practices advice while you type.
Gordon had used ReSharper in its 2.0 days. I’d heard many positive things about ReSharper, but hadn’t tried it myself. The recently released 4.0 version offers support for C# 3.5, including the var keyword, object and collection initializers, and lambda expressions. Check out the in-depth review by Simon Hart if you want more details. Or just try it yourself.