views:

100

answers:

3

Is there a way, even a very sneaky way, to change the time that a DateTime.UtcNow returns for a process or thread?

The SetSystemTime() win32 API call will change the time on the entire system. I've used this before but I would like a method that is less evil to other processes running on the system. Messing with the time is bad kungfoo on automated build servers.

C# seems to lack the language features required to override the default behavior.

Perhaps the method that .Net uses to obtain the current time could be proxied in some way?

+2  A: 

The DateTime.UtcNow probably calls into Kernel32!GetSystemTimeAsFileTime() or something similar. You could probably use the Detour library from Microsoft Research to hook this API, then in your hook function, detect the process and thread IDs which you'd like to dupe.

Good luck running the software!

Heath Hunnicutt
I like it! Devious, underhanded, sneaky and robust.
Gareth Farrington
And for the record you are correct, it is calling `GetSystemTimeAsFileTime()`It will take some work to get Detoure built and wrap it in a C# API but it should work.
Gareth Farrington
+4  A: 

You should wrap the current time in your own proxy class and use that instead, then you're free to return whatever you like.

GraemeF
I thought of this but other libraries running in the process space will report inconsistent times. C# doesn't allow extensions of existing methods or static methods so I cant simply override it either.The only way to really fake it for all the code, mine and others, is to do it at the OS level.
Gareth Farrington
A: 

Yeah, define interface IKnowCurrentTime with single property UtcNow. Use dependency injection to inject that into your classes. Make default implementation call DateTime.UtcNow and pass that to your classes in PROD. For testing purposes, make a mock of IKnowCurrentTime and have that return whatever. The way of the future baby.

zvolkov