Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create or get specific SPTimeZone instance

What is the most convenient way to create a specific instance of Microsoft.SharePoint.SPTimeZone as the following one:

SPTimeZone utc = SPRegionalSettings.GlobalTimeZones                                    .OfType<SPTimeZone>()                                    .FirstOrDefault(tz => tz.Information.Bias == 0                                                    && tz.Information.DaylightBias == 0); 

Is this hack the best one I can get...

This is in particular a problem for me, since I would like to mock this part of code for unit testing and to force it to always return UTC. The property GlobalTimeZones seems to depend on HttpContext.Current or an actual request - a prerequisite I don't have in my Unit Tests...

N.B: I know that there is System.TimeZoneInfo but a third party assembly forces me into using SPTimeZone ...

like image 444
Markus Avatar asked May 22 '15 07:05

Markus


1 Answers

To stop the discussion I decided to finally answer this question on my own.

There are several really helpful solutions in the comments which I want to gather in this short answer:

  • Introducing a facade / adapter
  • MS Fakes or other frameworks to
    • fake access to SPTimeZone
    • create a fake HttpContext
  • go with the hack described in the question above ...

I for my part decided to go with MSFakes to shim the whole 3rd party call (since I didn't wan't to test its behavior anyways) and to shim all properties of SPTimeZone that I use in my method. Introducing an adapter unfortunately wasn't an option for me, since I had to preserve the (internal) API.

like image 60
Markus Avatar answered Sep 22 '22 06:09

Markus