DateTime Serialization to XML

I have an C# serializable object with a DateTime property like this:

        public class MyClass {
public DateTime Date1 {get;set;}
}

When serialized to XML, it gives me something like this


        <MyClass>
<Date1>2010-11-30T00:00:00</Date1>
</MyClass>

I could not get it to give me this, which is in the proper  xml date format:


        <MyClass>
<Date1>2010-11-30</Date1>
</MyClass>

After a couple of wasted days, it turned out that the solution is really simple:


        public class MyClass {
[System.Xml.Serialization.XmlElement("Date1", DataType="date")]
public DateTime Date1 {get;set;}
}

Does your employer own your side projects?

Apparently, according to Joel Spolsky, they do:

…So before you hire this guy, you agree, "hey listen, I know that inventing happens all the time, and it's impossible to prove whether you invented something while you were sitting in the chair I supplied in the cubicle I supplied or not. I don't just want to buy your 9-5 inventions. I want them all, and I'm going to pay you a nice salary to get them all," and he agrees to that, so now you want to sign something that says that all his inventions belong to the company as long as he is employed by the company.

This is where we are by default. This is the standard employment contract for programmers, inventors, and researchers.
[Read rest of the discussion at answers.onstartups.com…]

One Interesting corollary: if you spend your day-time working for an employer and night time working on a github open source project, and 2 years from now the OS project becomes wildly popular (wink), your open source project is probably not very “open” afterall, unless you’ve had the appropriate work-for-hire clauses stipulated in your employment agreement. I’m reminded of a vaguely similar case in recent history: the infamous SCO v. IBM debacle from a few years back.

Convert string to DateTime object

Two C# functions that may be useful in accepting date/time strings of various formats:

        /// <summary>
/// Converts date string value, of various formats into DateTime object.
/// Example formats are DDMMYYYY,DD/MM/YYYY,MM/dd/YYYY,MMDDYYYY,...
/// </summary>
/// <param name="dateValue">date string</param>
/// <returns>resulting DateTime object</returns>
public DateTime ConvertDateStringToDateTime(string dateValue) {
string[] dateFormats = { "MM/yyyy",
"M/d/yyyy", "M/dd/yyyy", "MM/dd/yyyy",
"dd/MM/yyyy", "ddMMyyyy","dd/MM/yyyy","MMddyyyy",
"MM-dd-yyyy" };
try {
return DateTime.ParseExact(dateValue, dateFormats, CultureInfo.CurrentCulture, DateTimeStyles.None);
} catch (FormatException fe) {
throw new DataException(dateValue + ": " + fe.Message);
}
}

/// <summary>
/// Converts a time string of various formats into a DateTime object.
/// Example formats are: 7:00,700AM, 7:00AM, 7:00A, 0700AM, 07:00 AM, ...
/// </summary>
/// <param name="timeValue">time string</param>
/// <returns>resulting DateTime object</returns>
public DateTime ConvertTimeStringToDateTime(string timeValue) {
string[] timeFormats = {"HHmm","Hmmtt",
"H:mm", "H:mmtt", "H:mmt", "HHmmtt", "HH:mm tt", "HH:mmtt","HH:mmt", "HHmmtt", "HHMMt"};
// DateTime string cannot be blank, so if it is, assume "00:00"
if (string.IsNullOrEmpty(timeValue)) timeValue = "00:00";
try {
return DateTime.ParseExact(timeValue.ToUpper(), timeFormats, CultureInfo.CurrentCulture, DateTimeStyles.None);
} catch (FormatException fe) {
throw new DataException(timeValue + ": " + fe.Message);
}
}

Blog v3.0

This old techie blog of mine seemed to be dead silent lately that I feel compelled to resurrect it.

Let’s review a bit of history: In my mind, version 1.0 of my blog was on Bloglines (circa 2004). Version 2.0 was when I switch to blogspot and using the Kubrick theme.  It’s now time once again to resharpen the toolkit, beginning with a fresh new look, hat tip to the fine folks at Deluxe Templates for the iNove theme

TODO: I like this theme, but one thing I might change is to make a little more room for the content pane.

Also trying to install Alex Gorbatchev’s SyntaxHighligher scripts. Let’s see if this works:

    /**
* Sample code in C# to test SyntaxHighlighter.
*/
public Argument ArgueWith(Person person) {
if (person == null) {
throw new ArgumentException("no object to argue with");
}
// prepare argument
Argument arg = new Argument(person);
return arg;
}


Update 01/30/2011 11:44pm EST: SyntaxHighlighter worked great. I had to use dropbox.com to host the scripts. I think I spotted a bug, though, on Safari for iOS 4.1: line number is a bit out of whack.  Let’s have a closer look at PasteBin, as Gavin suggested:


Debugging hybrid VB6/C/C# app crashes with WinDbg

I was troubleshooting one of two (2) different app crashes this past week in which the app simply dies without any prior warning.  At first I thought: crappy VB6! But then, after looking in the Event Log, I found out this was not Visual Basic 6.0 Runtime’s fault, but rather it’s the .NET Runtime version 2.0 Fatal Execution Engine that erred fatally. Below is how I went about debugging the crash.

First of all, two sets of tools are needed:

  1. Debugging Tools for Windows (WinDbg)
  2. Debugging symbol (.pdb) files. These are useful but not essential.   PDB files are generated automatically in Visual Studio .NET, and can be turned on in VB6 IDE via the project properties under the Compile tab.

In using WinDbg to troubleshoot app crashes, I found this blog post Using WinDbg - Hunting Exceptions  by Johan Straarup to be tremendously helpful.

As anyone who’s ever involved in troubleshooting any software bug would know, the hardest part is to reproduce it in a consistent manner, and an app crash is (or should be) the rarest (and most feared by programmers) of bugs. Yet, an app crash is nothing more than an exception that has gone uncaught by the application.

In WinDbg, I used the Attach to a Process menu option to connect to the running app. Then, I issued the gn command (Go [until] Unhandled Exception) command, and let the app run its course.  Eventually, it came a stop with this message:

(4a4.1e4): CLR exception - code e0434f4d (!!! second chance !!!)
eax=0129ecfc ebx=0017d328 ecx=00000000 edx=00000025 esi=0129ed88 edi=e0434f4d
eip=7c812afb esp=0129ecf8 ebp=0129ed4c iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

I then used “!analyze –v” and subsequently “!pe”, which gave me this:

0:002> !PrintException
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll -
PDB symbol for mscorwks.dll not loaded
Exception object: 019138a0
Exception type: System.IO.FileLoadException
Message: Could not load file or assembly 'Interop.SHDocVw, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
InnerException: <none>
StackTrace (generated):
    SP       IP       Function
    00000000 00000001 MyAssembly1.MyClass1.Finalize()

So, this crash was the result of a referenced assembly version mismatch in one of the plugin components. That's one easy problem solved.

The other crash is a bit more elusive, which, after two weeks, I'm still in the process of trying to reproduce.

FF 3.5.3 crashed again

My Firefox 3.5.3 crashed again for the third time today:

Add-ons: {2B8EFF80-1240-11DB-BF6C-934CD2EFDFE8}:20080728.334,{CF40ACC5-E1BB-4aff-AC72-04C2F616BCA7}:1.5.2.35,toolbar@alexa.com:1.3.0,{2fa4ed95-0317-4c6a-a74c-5f3e3912c1f9}:2.1.062,firebug@software.joehewitt.com:1.4.2,{d37dc5d0-431d-44e5-8c91-49419370caa1}:2.5.35,{e4a8a97b-f2ed-450b-b12d-ee082ba24781}:0.8.20090123.1,{CAFEEFAC-0016-0000-0007-ABCDEFFEDCBA}:6.0.07,{CAFEEFAC-0016-0000-0011-ABCDEFFEDCBA}:6.0.11,{CAFEEFAC-0016-0000-0015-ABCDEFFEDCBA}:6.0.15,LogMeInClient@logmein.com:1.0.0.460,{B7082FAA-CB62-4872-9106-E42DD88EDE45}:3.0,{20a82645-c095-46ed-80e3-08825760534b}:1.1,pencil@evolus.vn:1.0.6,refractor@developer.mozilla.org:1.0b2,twitternotifier@naan.net:1.8.3,web@veoh.com:1.4,{972ce4c6-7e08-4474-a285-3208198ce6fd}:3.5.3
BuildID: 20090824101458
CrashTime: 1253813633
InstallTime: 1252611358
ProductName: Firefox
SecondsSinceLastCrash: 70976
StartupTime: 1253811215
Theme: classic/1.0
Throttleable: 1
URL: about:blank
Vendor: Mozilla
Version: 3.5.3

This happened while I was doing Google searches…probably one of the add-ons’ fault (probably the Alexa toolbar). 

Update 17:40 EDT: It’s not the Alexa toolbar. Next guess: McAfee SiteAdvisor 3.0

One of the design goals that one should aim to achieve, when building any plug-in architecture, is isolation, to the extent that  a crash in one of the  plug-ins should not bring down the entire application.

Somehow, that is very hard to do, isn’t it?

Guilty as charged.

COMException : Creating an instance of the COM component with CLSID {…}

I recently changed my NAnt build script, as part of its post-build cleanup step,  to unregister all .NET COM interop components after doing the build. Now my unit tests fails with this error:

System.Runtime.InteropServices.COMException : Creating an instance of the COM component with CLSID {596C3AA2-D5EC-4F86-85E3-7FAF86EC17A3} from the IClassFactory failed due to the following error: 800a005b.

What’s the cause?

Here are the facts: My .NET lib X depends on a  COM lib Y (596C3AA2-D5EC-4F86-85E3-7FAF86EC17A3), which depends on COM lib Z, which in turn invokes  .NET COM interop lib N.

It turns out that the real culprit was N, which wasn’t registered for some reason, even though I’ve told it to register via the regasm NAnt task.

Well, as it turned out, I needed to add the codebase=”true” attribute to the regasm task that registers N, which makes sense in hindsight, because my DLLs are not all in the same directory. Another “doh!” I suppose.

AccessViolationException in OpenFileDialog.ShowDialog()

Note to self:  Next time I get this error, when running in a 64-bit OS, make sure to specify x86 for Platform target in the Build options.

PageRequestManagerParserErrorException

Good tips from Eilon Lipton on this error:

Microsoft Internet Explorer
---------------------------
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

I suppose I fell into trap #5 listed on the article.  I was looking to do parameter passing from the current page to the redirected page. Basically, I had a general “catch all” event handler that catches unhandled exception, and forwards the detail to an error display page.  There doesn’t seem to be any direct way of passing parameters from one  .aspx page to another. So I stuffed this parameter into the HttpContext object.  The problem is: Reponse.Redirect() wipes out all parameters stored in the context. This problem doesn’t happen if I use Server.Transfer().

All of this was happening inside an UpdatePanel,  just as Eilon explained.  Hence, the PageRequestManagerParserErrorException. I looked in my ErrorStack, saw what the originating error was, fixed it, and the PageRequestManagerParserErrorException was gone.

I guess the next step would be to figure out how to display the error properly when invoked from an UpdatePanel, as it is working well everywhere else.

Wow!

I want a Mac for Christmas:


Just kidding.

Flight scheduling system test case: flight number re-use

Scenario:

  • Mom books a flight from airline X, gets assigned flight number 123, arriving at airport YYZ @ 5:45am
  • Mom tells son: “my flight #123 arrives tomorrow @ 5:45am”
  • “Tomorrow” comes. Son goes online and checks flight info, which states that flight 123 is on-time.
  • 6:15am: son arrives at YYZ to pick up mom.
  • Son checks the Arrivals Fight Info board, which says flight 123 has landed. Son waits at the Arrivals Area.
  • Three hours later. Mom was “no show”. Son calls mom, who says “oh, did I say ‘today’? I meant ‘tomorrow’. Tomorrow @ 5:45am.”

Why someone would design a flight number assignment algorithm such that any X flight departing XXX for YYZ at time hh:mm, on any day of the week, would get assigned the exact same flight number, is beyond me. Are flight numbers so scarce that they have to reuse the same numbers every day?

LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String)' method

I’ve been dabbling with the ADO.NET Entity Framework in .NET 3.5, was trying to convert this SQL WHERE clause, which uses the LIKE operator, into LINQ syntax:

String strWhereClause = String.Format(CultureInfo.CurrentCulture, "Type={0} AND Name LIKE '*{0}*'", orgType, orgName);

I read somewhere which suggested to use the SqlMethods helper class. So I tried:

var objQuery = repository.Organization.Where(vendor => vendor.Type == orgType && SqlMethods.Like(vendor.Name, "”%” + orgName + “%”));

The query is targeting an Organization table. repository is an instance of an ObjectContext subclass which has been  auto generated by Visual Studio’s ADO.NET Entity Data Model wizard.  orgType and orgName are passed-in parameters.

The above approach resulted in the following runtime error (notice the redundant occurrence of the word ‘method’ in the error message):

LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String)' method, and this method cannot be translated into a store expression

I then saw a post on stackoverflow which suggested to use Contains(), StartsWith(), or EndsWith() to mimick the LIKE operator. So I tried:

var objQuery = repository.Organization.Where(vendor => vendor.Type == orgType && vendor.Name.Contains(orgName));

This works, but if orgName.Length is zero, then the query returns zero rows.  So finally, a slight mod to the above query achieved the desired effect:

var objQuery = repository.Organization.Where(vendor => vendor.Type == orgType && (orgName.Length == 0 || vendor.Name.Contains(orgName)));

“The underlying provider failed on Open.”

I’m deploying my ASP.NET app to a brand new server with a fresh install of SQL Server 2008 Express. The db connection step failed with this error:

Message: The underlying provider failed on Open.
StackTrace:  at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) at System.Data.EntityClient.EntityConnection.Open() at System.Data.Objects.ObjectContext.EnsureConnection() at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)

I checked the connectionString, which uses Windows authentication, and it looked fine.

Somebody suggested to Allow Remote Clients in the Network DTC Access settings. That option is already enabled on my environment.

I looked at the Event Viewer, and noticed this entry:

Event Type:    Failure Audit
Event Source:    MSSQL$MSSQL
Event Category:    Logon
Event ID:    18456
User:        NT AUTHORITY\NETWORK SERVICE
Description:
Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. Reason: Failed to open the explicitly specified database. [CLIENT: <local machine>]

So IIS is trying to access the database under the credential   'NT AUTHORITY\NETWORK SERVICE' .  I looked that the db settings via SQL Server Management Studio and, sure enough, that account is not listed as one of the users allowed to connect. So I added him. And the web app was able to connect successfully.

Which config file to put the db connectionString for ADO.NET (3.5) Entity Data Model?

Normally this goes in the App.config. VS2008 designer wizard automatically creates this file and puts it in the same location as the  assembly in which your database layer resides. But if you’re calling that assembly from an ASP.NET app, you’ll  need to move that connectionString to the Web.config.  Otherwise, you’ll get this error upon  instantiation of the ObjectContext:

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.

Google Wave

Just watched the Google Wave demo, via @tylerwhitaker. Board game playing via email--I've thought of this before but seeing it implemented with Wave is so much cooler!


Appropriate levels of abstraction

I've learned over the years, through the many facets of my job, to don a different hat depending to whether I'm talking to a programmer, a business person, or an end user.

Which is why it always freaks me out when I see my fellow developers showing my CEO how to run regasm to get a particular new product feature to work. Good God!

I guess in some sense it's good, because now when something is not working quite right, my CEO would ask "Do I need to rerun regasm?"

Why does UnhookWindowsHookEx() fail?

I’m debugging a Windows hook DLL that’s misbehaving. Actually I’m still not sure whether it’s the hook DLL, or the C# library that calls it, that is the culprit. Here’s the problem symptom. My app DLL installs a mouse hook into a running application. The running app terminates. My app detects that it has terminated and attempts to remove the hook—this fails (1). On subsequent startup of the app in question, I try to re-install the hook onto it, and that fails (2). I’m actually more interested in failure #2 than failure #1, but the latter is probably a consequence of the former. So I needed to track down why #1 happened.

Side fact:

When you install a thread-specific Windows hook, your hook DLL is actually loaded in 2 places: one instance is loaded in your app's process space, and the other in the target app's.

At first, I thought that Windows was failing to do its DLL cleanup duties when the unhook step failed, so I was ready to look into manually forcing the unload and reload of the native DLL—often a bad idea to circumvent the garbage collector, but, hey, what else can you do?

Then I spotted the culprit:

DLLEXPORT HHOOK SetHook(HWND hWndTarget, HWND hWndListener) {
if(m_hWndListener != NULL) return NULL; // already hooked!
// install the hook via SetWindowsHookEx()


m_hWndListener = hWndListener;

}

DLLEXPORT BOOL ClearHook(HHOOK hook) {
BOOL unhooked = UnhookWindowsHookEx(hook);
if (unhooked) {
m_hWndListener = NULL;
// do other cleanup stuff
}
return unhooked;
}

It turned out: m_hWndListener was not being cleared when UnhookWindowsHookEx() failed.

Yet again, it goes to show that: just when I thought that the developers at Microsoft are a bunch of idiots who had no clue what they were doing when they invented the Windows API, it turns out that the idiot is me.

As to why UnhookWindowsHookEx() failed, my guess is that the hook was already being automatically removed by the OS when the target app terminated.

Adding custom properties to the MOSS2007 Advanced Search page

Recently, I’ve been playing a bit with MOSS2007. Actually I've dabbled with it a little bit when SharePoint 2003 came out, but not to the extent that I am now.

Installation was a bitch at the start, but thankfully there is a lot of useful resources out on the web this time around. I was looking to set up metadata (custom column) searching, and this article, Searching Custom Column Values in MOSS 2007  by Jonathon Frost, was extremely helpful. I did find, however, a couple of subtleties not mentioned in Jonathan's post.

For instance, I needed to add the corresponding PropertyRefs in the All Results ResultType section:

<PropertyDefs>

  <PropertyDef Name="Vendor" DataType="text" DisplayName="Vendor#"/>
  <PropertyDef Name="Invoice" DataType="text" DisplayName="Invoice#"/>
</PropertyDefs>

<ResultType DisplayName="All Results" Name="default">

    <PropertyRef Name="Vendor" />
     <PropertyRef Name="Invoice" />
</ResultType>

Originally, I mistakenly added my PropertyRefs in the “Word Documents” section, and was scratching my head for some time, wondering why my changes wouldn’t show up on the refresh of the Advanced Search page.

I also noted that I needed to manually run a Full Crawl for the custom properties to show up in the "”Mappings to crawled properties” section—which makes sense in hindsight.

Another thing I observed was that if I made changes to the Properties XML, I had to do an Incremental Crawl for it to take effect. For instance, I originally had the DisplayName for the “Vendor” property as simply “Vendor”. Later, I went back and changed this to Vendor#. The change would be reflected immediately on on the Advanced Search page, but the search was returning no results, until I manually ran the Incremental Crawl.

stdole 7.0.3300.0

When I first got this error during the initialization phase of my component:

Could not load file or assembly 'stdole, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I thought that it wanted Interop.stdole.dll, which was sitting right there in the working directory. But as it turned out, it meant the Primary Interop Assembly called stdole.dll, which was indeed missing.  Duh!

Setting up a WIX 3.0 build environment

I recently encountered some problem with heat.exe with respect to COM registry harvesting, and wanted to step through the code in the debugger, to see what was the problem.

I had some initial trouble setting up a dev environment for WiX, have read Neil Sleightholm's post on  How To Create a WiX build machine, but it didn’t go so well for me.  The process is really simple, with the following commands:

  • do a cvs checkout per instruction here:
    • cvs -d:pserver:anonymous@wix.cvs.sourceforge.net:/cvsroot/wix login
    • cvs -z3 -d:pserver:anonymous@wix.cvs.sourceforge.net:/cvsroot/wix co -P wix
  • set WIX_ROOT environment variable
  • cd to %WIX_ROOT%
  • Run bin\wixenv.bat,
  • Run NAnt

Yet, when I ran the NAnt command, I kept getting this error:

Failed to initialize the 'Microsoft .NET Framework 2.0' (net-2.0) target
framework. Property evaluation failed.
Expression: ${path::combine(sdkInstallRoot, 'bin')}
^^^^^^^^^^^^^^
Property 'sdkInstallRoot' has not been set.

Part of the problem was that it needed a post-0.86-beta1 build of NAnt, which unfortunately, is not available on the NAnt project home page. I managed to find it by googling, leading to  this download link (the version I downloaded was 0.86.3317.0, 30/01/2009).  Once I got NAnt 0.86.3317.0 in place, the wix build finished without a hitch.